Arduino send data to PC each iteration. When I'm trying to send data to Arduino while receiving data from it, it takes too long. Serial.available()
returns false even I sent data from PC. But if I add delay like 20-30 ms, problem fixed. Can't I use serial simultaneously?
PS: It's Arduino mega and I'm using http://www.teuniz.net/RS-232/ library for serial communication.
Example code:
void loop(){
if(Serial.available())
Serial.write("goodbye", 7);
Serial.write("hello", 5);
}
In this situation, it takes long time to write "goodbye" after I sent data to Arduino.
2 Answers 2
Following up on what Nick Gammon says, don't try to use the serial output to debug serial. Perhaps try using the built-in LED instead; you can use an oscilloscope to find out how much time it is spending reading characters.
The following is how I've been reading a line at a time using non-blocking operations:
const int SERIAL_BUFFER_LENGTH = 100;
// The +1 assures we'll always have room for null termination
char g_serial_buffer[SERIAL_BUFFER_LENGTH+1];
int g_char_count; // index into serial buffer
void setup() {
Serial.begin(9600); // or 115200 if your host supports it
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
g_char_count = 0;
}
void loop() {
while(Serial.available() > 0) {
digitalWrite(LED_BUILTIN, HIGH);
char c = Serial.read(); // won't block because Serial.available() > 0
if (c == '\n') {
g_serial_buffer[g_char_count] = '0円'; // null terminate
process_buffer(g_serial_buffer);
g_char_count = 0;
} else if (g_char_count < SERIAL_BUFFER_LENGTH) {
g_serial_buffer[g_char_count++] = c;
}
}
digitalWrite(LED_BUILTIN, LOW);
Serial.print(".");
}
// process_buffer: do whatever it is you intended to do with a
// line of received text...
void process_buffer(char *buffer) {
}
Try this:
if(Serial.available())
while(Serial.read());
Serial.write("goodbye", 7);
Serial.write("hello", 5);
}
I think you have to read what you get in the serial port.
Ctrl+K
to have your browser do this for you.loop
the output buffer will be filled withhello
before you get a chance to insertgoodbye
. Your "delay" solution probably gives the output buffer time to empty.ll add full code when I
m open PC. I dont have full code by now.