Search code examples
pythonarduinopyserialarduino-unoarduino-c++

Arduino code not running when getting pre-determined string from python on serial


I am trying to have my arduino uno run when code is sent to it, however, nothing happens except the lights blinking back and forth for a second when it is sent and then nothing. I am just sending a string on serial, and using an if statement so it should be super straight forward but I am not sure what is happening to cause it not to work. Code below, any help would be awesome. Python

import serial, time
arduino = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
cmd = ''
while cmd != '0':
        cmd = input('Enter a cmd ')
        arduino.write(cmd.encode('ascii'))

Arduino

void setup() {
Serial.begin(9600);
}

void loop() {
    delay(100);
    if (Serial.available() > 0) {
    String stringFromSerial = Serial.readString();
    if (stringFromSerial == "1") {
        Serial.println("1");

    } else if (stringFromSerial == "2") {
        Serial.println("2");

    } else if (stringFromSerial == "3") {
        Serial.println("3");

    } else {
        Serial.println("Not recognized cmd");

    }
  }
}

Update: Thanks for the help, I have updated the code to what actually works.


Solution

  • As indicated by hcheung, the string you want to send isn't correct.

    Looking at the w3schools and programiz, I suggest you do something similar to

    cmd = 'fwd'
    arduino.write(cmd.encode('ascii'))
    

    Or, for non-ASCII character commands, you can encode as 'UTF-8'. But I doubt you'd be happy with those encodings.

    arduino.write(cmd.encode(encoding='UTF-8'))
    

    You could also send multiple commands from Python like so:

    in = ''
    while in != '0':
        in = input('Enter a command: ')
        arduino.write(in.encode('ascii'))
        # this loop will exit if you enter '0',
        # but will first send the exit command to the Arduino
    

    and receive multiple commands on the Arduino side:

    void loop() {
        delay(100);
        if (Serial.available() > 0) {
        String stringFromSerial = Serial.readString();
        if (stringFromSerial == "1") {
            // do something for command 1
    
        } else if (stringFromSerial == "2") {
            // do something for command 2
    
        } else if (stringFromSerial == "3") {
            // do something for command 3
    
        } else {
            // do an exit command perhaps
    
        }
    }