Weird problem when using serial.ReadString()

I am attempting to write a string from a python application (Integer converted to string for use with PySerial) and for whatever reason when i use this code to parse it on the arduino side it simply doesnt work. if i send a '4' through the serial monitor to the arduino it sets the pin that corresponds with the number high and then low like its supposed to. however if my software sends a '4' it doesn't respond at all.
Below is my Arduino Code



float bitsTime[255] = {}; // 

void setup() 
{
  pinMode(4,OUTPUT);
  pinMode(7,OUTPUT);
  Serial.begin(250000);
  delay(500); // prevents outputs from momentarily going high during startup. 
}


  void loop() 
 {
   
  float lastActivation = millis();
  for (int i=0; i <8 ; i++ ) { 
    if( lastActivation - bitsTime[i] < 33.3 ) { // has to be the frame time set in software or else it will cause flickering due to serial data only being sent once every 33.3ms
      
          digitalWrite(i,HIGH);
          
    }
    
    else {
      
          digitalWrite(i,LOW);
          
         }
  }
    if (Serial.available() > 0 ) { 
          String a = Serial.readString();
          int test = a.toInt();
          Serial.print(test);
          bitsTime[test] = millis(); 

        }
   }


and here is the function on the python side that sends data through the serial port:

def shiftOutBit(bit,frame):
   bittosearch = bit
   bitList = bit.split(" ")
   for x in bitList:
       print(x)
       SerialObj.write(str(x).encode('utf-8'))

because most of the time we have multiple different numbers being sent " " is used as a deliminator and then it is converted into a list with each value being written one at a time to the arduino.
I really don't understand why this isn't working properly. I apologize if this isn't a good description its my first time posting here. Any help will be greatly appreciated. Thank you

Would Arduino be happier if you encoded in Ascii? Not sure if it matters but I never see Unicode mentioned anywhere in Arduino resources

I don't think encoding in ASCII would've made much of a difference. I ended up using Serial.readStringUntil() and just sending an _ at the end of each bit of data and that ended up fixing the problem it seems.

1 Like

I'm a fan of

Serial.readStringUntil('\n');

as it seems to be the popular way to have it catch the ln() at the end of Serial.println();

Glad you got it sorted.

1 Like

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