Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serial available always returns 0 in Arduino

Tags:

arduino

Why do I keep getting 0? I tried several ways and took the sample code on the Arduino site, but that didn’t work either. I always get Serial.available() = 0.

int incomingByte = 0;  // For incoming serial data

void setup() {
    Serial.begin(9600);  // Opens serial port, sets data rate to 9600 bit/s
}

void loop() {

    // Send data only when you receive data:
    if (Serial.available() > 0) {
        // Read the incoming byte:
        incomingByte = Serial.read();

        // Say what you got:
        Serial.print("I received: ");
        Serial.println(incomingByte, DEC);
    }
    else
        Serial.print("I received nothing ");
}
like image 782
hammies Avatar asked Oct 20 '25 15:10

hammies


1 Answers

Your program works fine on my Arduino although you need some delays to stop the rapid-fire "I received nothing " messages. I would change the "I received nothing " block to include a delay of a few seconds e.g. delay(3000) for a 3-second delay.

Also, consider changing your code to use a SerialEvent() procedure such as depicted here: SerialEvent example

String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
}

void loop() {
  // print the string when a newline arrives:
  if (stringComplete) {
    Serial.println(inputString);
    // clear the string:
    inputString = "";
    stringComplete = false;
  }
}

/*
  SerialEvent occurs whenever a new data comes in the
 hardware serial RX.  This routine is run between each
 time loop() runs, so using delay inside loop can delay
 response.  Multiple bytes of data may be available.
 */
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}
like image 148
Richard Elkins Avatar answered Oct 23 '25 20:10

Richard Elkins