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(){

    Serial.write("goodbye", 7);
    Serial.write("hello", 5);

In this situation, it takes long time to write "goodbye" after I sent data to Arduino.

  • Please edit your question and post your code. Format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you. – Nick Gammon Dec 21 '16 at 0:33
  • @Nick Gammon, done. –  thoron Dec 21 '16 at 0:44
  • 1
    That's not all your code is it? What baud rate are you using? In any case, since you are sending "hello" every time around loop the output buffer will be filled with hello before you get a chance to insert goodbye. Your "delay" solution probably gives the output buffer time to empty. – Nick Gammon Dec 21 '16 at 4:25
  • @Nick Gammon 9600. –  thoron Dec 21 '16 at 9:47
  • And I lid a led when receive message. I forget to write it. Ill add full code when Im open PC. I dont have full code by now. –  thoron Dec 21 '16 at 9:49

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
  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
      g_char_count = 0;
    } else if (g_char_count < SERIAL_BUFFER_LENGTH) {
      g_serial_buffer[g_char_count++] = c;
  digitalWrite(LED_BUILTIN, LOW);

// process_buffer: do whatever it is you intended to do with a 
// line of received text...
void process_buffer(char *buffer) {

Try this:

    Serial.write("goodbye", 7);
    Serial.write("hello", 5);

I think you have to read what you get in the serial port.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.