0

I have a project in which an Arduino is reading a sensor and printing that value to the serial port. When connected to the serial monitor in the Arduino IDE on my PC, the data is printed flawlessly.

I wrote a script in Python on my Raspberry Pi to essentially work as a serial monitor but it is not behaving properly. When I run the script it starts printing the first data it gets, but won't change. So for instance if my sensor is at 0 when the script starts, the Pi will just keep printing zero forever, even when the value changes. If the sensor is at 540, it will keep returning 540 forever, and so on.

It is printing the values b'993\r\n' and so on but it's almost like it's not registering the newline. Although sometimes it'll keep printing values around the original value, i.e. 993, 994,990,992,993,etc.

Here is the code on my Pi:

import serial
import time
ser = serial.Serial('/dev/ttyUSB1',9600)

while True:
    print(ser.readline())
    time.sleep(0.1)

I have to believe the issue is with the pi since the Arduino communicates to the serial monitor in the IDE fine. I think the issue is that it's not recognizing the EOL characters and so it gets stuck reading the same line, but that's just a guess. Not to mention, if that is the case, I am unsure how to fix that!

I am running an Adafruit Metro Mini, Raspberry Pi 3B, Python 3.5.3 .

  • 1
    If you think Raspberry Pi is part of the problem, try running that Python code on a laptop. – Dmitry Grigoryev Oct 23 at 11:22
0

If you think it's an issue with the EOL characters, try this:

on the python side:

import serial
import time
ser = serial.Serial('/dev/ttyUSB1',9600)

while True:
    print(ser.readline().strip()) # notice the added .strip(). this strips it of EOL characters.
    ser.flushInput() #flushes serial input so it doesn't have old messages stuck in it.
    time.sleep(0.1)

on the arduino side:

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

void loop() {
  //other code
  flushSerial(); //create a pause so that the serial gets sent without being interupted
  Serial.println(your_number);
}
  • let me know if it works :) this worked for me. – scitronboy Mar 26 '18 at 2:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.