I need some help with data reading. In my situation, I have an Arduino Uno connected via USB to the RPi. The Arduino is sending data to the RPi with Serial.write(). The Arduino outputs 128 bytes each read out period.
Part of the Arduino code which produces the output looks like this:
void loop()
{
unsigned char ADC_value;
unsigned char first_byte = 0;
if(conv_complete)
{
if(first_sample)
{
first_sample = 0;
Serial.write(first_byte);
}
else
{
ADC_value = ADCH;
Serial.write(ADC_value);
}
conv_complete = 0;
}
}
Currently I have my Python code like this:
import time, serial
import numpy as np
ser = serial.Serial('/dev/ttyACM0',115200)
start = time.time()
PERIOD_OF_TIME = 300
reading = ser.read()
f = open('data.txt','a')
while reading is not None:
f.write(reading)
reading = ser.read()
if time.time()>start+PERIOD_OF_TIME:break
I tried using ser.read() but the output I got are a bunch of symbols. If I modify the code in Arduino to Serial.println() I can read the data with ser.readline() on the RPi side but the data obtained doesn't have 128 samples in a period (I only got around 40 samples in a period). I think this could be due to the Serial.println() command which converted 3 bytes into an integer value and these are not usable for me.
I understand there is a difference with Serial.println and Serial.write. Serial.write writes binary data to the serial port and Serial.print prints data to the serial port as human-readable ASCII text.
I want to convert the received data to uint8 format by adding another line of python code like this:
x = np.fromfile(f,dtype=np.uint8)
So that I would be able to see values (0-255). I'm still having trouble with this. Any advise? Any help is much appreciated. :)