Search code examples
pythonpython-3.xarduinopyserial

Python 3 adding extra tags to string while reading data over Arduino Serial Port (myserial)


I am JUST now learning some python after running through a 30 episode series of arduino programming. The runner-up python series I am following seems to be a little out-dated as far as the package modules go and I've seen some strange syntax things happening that aren't occurring in the original video material.

The objective for this lesson was to get Python to read a String counter over Arduino's serial port.

Counter for Arduino over serial port (Code):

int cnt=0;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  Serial.print("I am counting ");
  Serial.print(cnt);
  Serial.println(" Mississippi");
  cnt=cnt+1;
  delay(1000);
}

Read from serial port in PyCharm (Code):

import serial

arduinoSerialData = serial.Serial('com4', 9600)

while (1==1):
    if (arduinoSerialData.inWaiting()>0):
        myData = arduinoSerialData.readline()
        print (myData)

Terminal Results:

b'I am counting 0 Mississippi\r\n'
b'I am counting 1 Mississippi\r\n'
b'I am counting 2 Mississippi\r\n'
b'I am counting 3 Mississippi\r\n'

What are the b \r \n tags. and why does it apply some automatic formatting like 'string'? This does not happen in his videos.

Also, on Python's side of things the print (myData) was formatted as print myData without (). It would not even compile otherwise but it worked fine in his video. Are these just changes in the syntax from updating from Python 2 to Python 3?


Solution

  • \r is the carriage return character and \n is new line

    they originate in the

       Serial.println(" Mississippi");
    

    line of your arduino code, notice how .println is different from print

    the b in front of the string indicates that this is a byte string, if instead of

    print(myData)
    

    you do

    print(myData.decode())
    

    you should no longer see them