I am doing a project with bluetooth and an LED. I wrote a code which supposed to turn on an LED after it receives a byte of value 1 after 5 seconds, unless it receive another byte of value 1 (which make it need to wait another 5 seconds) so that if it receive the byte periodically, the LED doesnt turn on, and only turn on if byte value sending is stopped/bluetooth disconnected. I wrote this code and it doesn't seem to work. It doesn't even turn on the LED after 5 seconds. Can you help me spot the mistake here?

unsigned long timebetween=5000;
unsigned long lastreceivedtime;
int value;
bool timerReady = false;

void setup() {
  pinMode (11,OUTPUT);

void loop() {
  unsigned long currentMillis = millis();
  if( Serial.available() >0){
    value = Serial.read();
  if ( value ==1 ){
    lastreceivedtime = currentMillis;
    timerReady = true;

  if(timerReady) {
    if((unsigned long)(currentMillis - lastreceivedtime) >= timebetween){
      digitalWrite(11, HIGH);
  • how do you know what value Serial.read() returns?
    – jsotola
    Commented Jan 1, 2020 at 4:46

1 Answer 1


I don't think anything in your code is going to work. First, you are asking the serial.Read to return an integer if it is working. You might want to change that to a Boolean.

Second, You are asking for a 1 and only a 1 to make your next if statement true. If the serial.Read is working the chance it will only return a one, I think is very low

Third, On the IF statement for setting timerReady. You will set that at a new number each time the program runs through, with the 90ms delay in the last IF statement, it looks like your timer will reset at about every 95-100ms

Fourth, I think your last 2 IF statements are wrong, I think you want

if(timerReady==true) {
    if((currentMillis - lastreceivedtime) >= timebetween){
      digitalWrite(11, HIGH);

If you do get this working you might need to set the Boolean back to false and move pin 11 to low at some point.

  • 1
    Thanks a lot! I modified some of the lines and it worked. Commented Jan 1, 2020 at 7:21
  • Why is it a problem to save the return value of Serial.read() in an int variable? That is actually the type, that gets returned by this function, so why using a boolean here?
    – chrisl
    Commented Jan 1, 2020 at 9:11
  • Because the only reason he is looking at the serial.Read is to see if it is there and working, he doesn't really care whats there, just that it is working. The serial.Read is being used as a light switch, on or off, TRUE or FALSE
    – Jeff A
    Commented Jan 1, 2020 at 14:10

Your Answer

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

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