Using Python pyserial with Arduino

I am Arduino Uno As my hardware. i wanted to use python for some evaluation test cases.

My Arduino sample test code look like this:

char incomingByte = 0;  // for incoming serial data
char myCommand;

void setup() {
  pinMode(13, OUTPUT);
  Serial.begin(9600);  // opens serial port, sets data rate to 9600 bps
}

void loop() {
  // send data only when you receive data:
  if (Serial.available() > 0) {
    // read the incoming byte:
    incomingByte = Serial.read();

    // say what you got:
    Serial.print("I received: ");
    Serial.println(incomingByte);

    if (incomingByte >= 'a' && incomingByte < 'd') {
      myCommand = incomingByte;
    }
  }

  switch (myCommand) {
    case 'a':
      Serial.print("Testcase1: ");
      Serial.print(",");
      Serial.print("value:");
      Serial.print(1);
      Serial.print(",");
      Serial.print("value1: ");
      Serial.println(1);
      break;

    case 'b':
      Serial.print("Testcase2: ");
      Serial.print(",");
      Serial.print("value2:");
      Serial.print(2);
      Serial.print(",");
      Serial.print("value3: ");
      Serial.println(2);
      break;

    case 'c':
      Serial.print("Testcase3: ");
      Serial.print(",");
      Serial.print("value3:");
      Serial.print(3);
      Serial.print(",");
      Serial.print("value3: ");
      Serial.println(3);
      break;

    default:
      break;

  }  //END of  switch...case
  delay(1000);
}  //end of    loop()

Currently using other UART port I make ensure its working. Now I want to these done by python and pyserial.

  • pyserial should able to send commands like input. input might be any command short cut from PC and enable input

  • It should read comma-separated value sent from Arduino value

  • read the value and write into csv file for calculation.

My question is how I can use python and pyserial in Jupiter lab.

I thought of thinking like this
This code will check if p to tun and expect serial command and can be used to write serially…Q used to quit the application

import keyboard
def KeyPressCheck():
    while True:
        if keyboard.read_key() == "p":
            print("You pressed p")
            Test=input("value:")
            print(Test)
            continue
        if keyboard.read_key() == "q":
            print("You pressed q")            
            break       

if __name__ == '__main__':
    KeyPressCheck();