Send data via Arduino serial communication - Raspberry

Asked

Viewed 157 times

2

Good morning, I’m having problems receiving the data that the Arduino is sending, what I want to read the line information, play this information in a variable and compare the values in Raspberry. The problem is that as I want to separate the information by line, I have to use the command in Arduino Serial.println, which in Raspberry generates, in addition to the desired number/text, the characters of jump line " r n", generating conflict in my comparison in rasp. How can I separate this information without generating these characters?

Code on the Arduin:

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

void loop() {
  // put your main code here, to run repeatedly:
Serial.println("1");
delay(500);
Serial.println("2");
delay(500);
Serial.println("11");
delay(500);
}

Code on the Raspberry:

import serial
comunicacaoSerial=serial.Serial('/dev/ttyUSB0',9600)
k=str()

while 1:
      k=comunicacaoSerial.read()
      int_k = int(k)
      print(k==1)
  • Tried to give a .split('\n') in its variable 'k'? k = k.split('\n')[0]

2 answers

0

Hello

The method .read() is not the most indicated in this scenario, as it assumes the value of 1 byte by default and this can cause you to read only a part of the buffer. In this case it is recommended to use the .readline(), but for it to work properly you must set the reading timeout or the application will be eternally awaiting the " n", for this you must pass the reading timeout value when instantiating the Serial class. Example:

# Timeout de 2 segundos
my_serial = Serial('/dev/ttyAMA0', baudrate=9600, timeout=2)

For more hints look at this link

0

You can handle that \n in your Raspberry code, with split() in the variable k, or try to use:

k=comunicacaoSerial.readlines()

instead of

k=comunicacaoSerial.read()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.