Python to Arduino Serial char Fail

I'm using Python 3.10 to send an Arduino Uno integers to light up LEDs on a FastLED WS2812B strip. I can get the code to light the correct LED if between 0 and 9 (inclusive). However, anything above that fails.

Arduino code:

  if (Serial.available()>0){ // If-01
    char option = Serial.read(); // Convert incoming BYTE to CHAR
    option -= '0';
    v_LEDs[option] = CRGB(255, 69, 0);
    FastLED.show();
}

Python 3.10 Code:

import serial
arduino = serial.Serial("COM3", 9600)
time.sleep(5) # Comm. port init. wait
arduino.write(b'7') # Succeeds
arduino.write(b'201') # Fails
arduino.write('201.encode()') # Also Fails
arduino.close()

How do I get the Arduino to convert correctly numbers sent to it from Python?

Thank you.

Actually you are sending "characters" because your Arduino program has to convert them to integers. Did you notice that sometimes the Python program sends TWO characters, like when you enter "10"? But your Arduino program only reads and process just ONE character, so the second character is lost.

I solved this by having Python send the INT as a STRING then converting the STRING to an INT in Arduino.

Python:

    # integer to send
    numberToSend=99
    # convert integer to string
    stringConverted=str(numberToSend)
    # write the message
    arduino.write(bytes(stringConverted, 'utf-8'))

Arduino code:

  if (Serial.available()>0){ // If-01
    v_This = Serial.readString();
    int number1=v_This.toInt();
}

Thank you.

You should use 'ascii' instead of 'utf-8'.
In this case it may not be important but it can cause problems in other projects.
Better get used to the fact that you have to use ASCII encoding (because arduino does not "understand" UTF-8 encoding).

1 Like

Arduino deals with utf-8 - all the strings you type in the IDE are utf-8 encoded

Try compiling this and printing it out to the Serial monitor

const char * utf8String = "Щасливого Різдва, Joyeux Noël, 圣诞快乐, Καλά Χριστούγεννα";

If you only send ASCII there is no difference in the byte stream anyway (standard ascii has the same codes in utf-8)

1 Like

I had problems sending/receiving in UTF-8 from Python and it was hard for me to understand what the problem was, but that being the case, it may have been my mistake.
Thanks for the clarification.
Regards

@isawittoo The Python serial write method needs an object with the buffer protocol for example a character array or a byte array, there are several ways to do that here is an example with a function containing a one element bytearray

def send_data(value):
    data = bytearray(1)
    data[0] = value
    ser.write(data)

and a second option

def send_data(value):
    ser.write(bytearray([value]))

The Arduino data type for this data should be a byte or unsigned char

unsigned char option = Serial.read();

byte option = Serial.read();

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.