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);
}
1 Answer 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.
parseInt
. Ever. It's rancid. Read serial properly : majenko.co.uk/blog/reading-serial-arduino