Hi there, I hope I'm in the right category. My first post here, so please mods move this if I'm not in the right spot!
Firstly I realize the scope of this may go beyond Arduino itself, but I figured maybe someone here can help. I'm testing some really basic code to send simple sensor data from the Arduino (Uno, Nano) to a Raspberry Pi via USB and using Pyserial (Python3) and in the example here everything ultimately works fine except when the Analog sensor is being read on the other end. In other words, it will Serial.print() just perfect in the IDE, but if I attempt to read from within Python, the sensor value is randomly switching from the correct numbers to totally random numbers.
I hope this screenshot contains everything to explain what I'm attempting here, and the outputs. What's perplexing me is that it's getting the data MOST of the time, but every few prints on the Python side it's not correct. I've tried changing delays etc. but that makes no difference in the integrity. If I for example change that sensor data to a static number of any type, the output is consistent. I hope this is the right place to ask for help I'm running out of ideas here!
To be honest I just started throwing different arrangements of code at it to see if I could get any sort of different results And my bad I thought I had included the code as well. I can go ahead and retry.
Arduino code:
int PWM_PIN1 = A0;
int pwm_value1;
void setup() {
Serial.begin(9600);
pinMode(PWM_PIN1, INPUT);
}
void loop() {
String stringOne = "Sensor value with lots of text goes like this: ";
pwm_value1 = pulseIn(PWM_PIN1, HIGH); // Test sensor output
String stringTWO = String(pwm_value1);
String stringThree = stringOne + stringTWO;
Serial.println(stringThree);
delay(100);
}
Python Code:
#!/usr/bin/env python3
import serial
while True:
ser = serial.Serial('/dev/ttyUSB0', 9600)
ser.flushInput()
ser_bytes = ser.readline().decode('utf-8')
new_bytes =ser_bytes.rstrip()
print(new_bytes)
Okay it gets even weirder. This may in fact be a Pi question at this point because I just tried plugging in multiple Arduinos into multiple Pi’s (3 and 4) while using the Arduino IDE to test serial monitor output and they are all showing the same weird output in there. It only seems to do this with any signal reading via Analog. I’m stumped at this point as to why it’s happening.
SOLVED! I was using a different power supply on the sensor that did not share a ground with this Arduino, so I added a GND between the sensor and the Arduino, and voila! No more issues. Considering it was PWM signal I overlooked that, but the erratic behavior over the Serial connection on the Pi end was 100% to do with the common ground. Glad to have resolved the issue, as I could not find anything on Google easily. Moderators you may close this topic.