0

In my project, I have to read the input pin number(send by RPi), where 8 sensors are attached to Arduino Nano, after reading Arduino Nano send the real-time values of all sensors through serial USB communication. All is fine, but my problem is that I need to speed up the sending of data since it takes to long to read from Rasberry pi. I put the delay of 70 milliseconds but if I try to reduce more than that, I encounter a problem i.e data overwrites. My baud rate is 115200. Kindly help me with the code to make it fast.

int analogInputPin;
float voltage;
void setup() {
 // initialize serial communications at 9600 bps:
 Serial.begin(115200);
}
void loop() {
 // if any data on the serial port are available
 // read it and try to update the analogInputPin
 // based on the number that was read on the serial 
 if (Serial.available() > 0) {
 analogInputPin = Serial.parseInt();
 }
 // read the analog value:
 int analogInputPinValue = analogRead(analogInputPin);
 voltage=(5./1023.)*analogInputPinValue;
 // print the results to the serial port:
 // the output should have the following form: INPUTPIN:VALUE
 // followed by a newline character
 Serial.print(analogInputPin);
 Serial.print(":");
 Serial.print(voltage);
 Serial.println("");
 // wait 50 milliseconds before the next loop
 delay(50);
}
asked Aug 18, 2019 at 11:27
2
  • 1
    Hint: Look at the source code for Serial.parseInt(). Consider reading to a buffer instead. Commented Aug 18, 2019 at 11:41
  • 1
    Don't use parseInt. Ever. It's rancid. Read serial properly : majenko.co.uk/blog/reading-serial-arduino Commented Aug 18, 2019 at 11:51

1 Answer 1

1

parseInt reads digits and stops after a non-digit characters occurs or the function times out because no next characters arrives. The timeout is at default 1 second. So this is where you loose time.

Simplest solution for your code is to send some non-digit character after the number sent from Raspberry. This will terminate parseInt immediately. Usual is to send a new line character. It will separate the numbers nice if you debug the communication with prints to serial terminal.

Not a very good option, but I mention it, is to set the timeout of blocking read functions like the parseInt to a smaller time with Serial.setTimeout(ms).

To really speed up the communication you would send the numbers in binary form and not as text like you do now.

answered Aug 18, 2019 at 12:33

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.