I am trying to use Serial reading from a python serial code (which is running on my Jetson Nano) in my project, but in some loop in my code, my data is receiving wrong.
- I use Serial.readBytesUntil() function for interrupt-like reading.
- I use standart blue mini-USB cable for communication.
- My Arduino Nano also connected a nRF24L01 module with SPI.
- Baudrate is 9600 for both devices. I tried 115200 but there is no difference.
- The data loss is about %10 of all loops with both test codes (image-1, image-2).
- There is no positive difference when I use RX/TX pins on both boards with level shifter.
- When I use the test code in my main code with USB connection, the data loss increases %50 of all loops. But Arduino serial monitor is fine like image-3.
- When I use the test code in my main code with RX/TX pins, Arduino serial monitor looks like image-4 and Arduino IDE gives error like image-5.
Here is my receiver test code on my Arduino Nano.
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
while (!Serial) {}
}
void loop() {
char buffer[4];
int deger = 0;
if (Serial.available() > 0) {
int size = Serial.readBytesUntil('\n', buffer, 4);
if (size == 4) {
Serial.print("deger: ");
Serial.write(buffer);
Serial.print(" size: ");
Serial.print(size);
// Bytes to integer
deger = (buffer[1] - 48) * 100 + (int(buffer[2]) - 48) * 10 + (buffer[3] - 48);
if (buffer[0] == '1') {
deger = -1*deger; }
Serial.print(" Sayi: ");
Serial.println(deger);
}
if (deger < 0) {
digitalWrite(LED_BUILTIN, HIGH);
}
else {
digitalWrite(LED_BUILTIN, LOW);
}
}
}
And the python serial transmitter test code.
import serial
ser = serial.Serial('/dev/ttyUSB0',baudrate=9600,timeout=10)
while True:
hata = -58
if hata > 0:
hata = str(hata)
if len(hata) == 2:
hata = '00' + hata
elif len(hata) == 1:
hata = '000' + hata
else:
hata = '0' + hata #Pozitive, Added 0
elif hata < 0:
hata = -1 * hata
hata = str(hata)
if len(hata) == 2:
hata = '10' + hata
elif len(hata) == 1:
hata = '100' + hata
else:
hata = '1' + hata #Negative, Added 1
else:
hata = str(hata)
hata = '000' + hata
# For every loop, sends 4 character and "\n" Example: 1058\n
gonder = hata + '\n' # For readBytesUntil function
ser.write(gonder.encode('utf-8'))
print(gonder.encode('utf-8'))
image-1: Arduino test code serial monitor screenshot
image-2: Python test code serial terminal screenshot
image-3: Arduino main project code monitor with USB cable screenshot
image-4: Arduino main project code monitor with RX/TX pins on GPIO screenshot
image-5: Arduino main project code IDE error
So, what did i do wrong? Thank you!