0

I am using Arduino UNO and a bluetooth module. I have used an if condition so that Serial.println() happens only once but it keeps on printing. Please help. Below is the code.

//Begin CODE
char str;
String fnal;
int i;

void setup()
{
  Serial.begin(9600);
  fnal="";
  i=0;
}

void loop()
{
  i++;
  if(i<2)
  {
    Serial.print('#');
    Serial.print('1');
    delay(10);
  }
}

According to this code # and 1 should be printed only once but in serial monitor the printing continues infinitely.

  • It works as expected for me, and the code looks OK. If it doesn't work for you, try printing out the value of i (Serial.println(i);) and see if you can work out what's going wrong. – Mark Smith Dec 14 '16 at 21:40
  • 1
    In setup add a Serial.print, eg. Serial.println ("Starting"); to see if the board is resetting for some reason. – Nick Gammon Dec 14 '16 at 21:42
  • Try changing the i++; with i+=1; – dhimaspw Dec 15 '16 at 3:48
  • The idiom i++; alters the value of i. The two forms you posted are identical in function. If you do a = i++; then a is the value of i before adding 1 to it. However 1 is added to i, whether or not you store the result. Alternatively a = ++i; makes a have the value of i after adding 1 to i. – Nick Gammon Dec 15 '16 at 4:57
1

It is definitely an overflow issue.

You declared i as int which ranges from -32768 to 32767. I wrote this code as an experiment:

void loop() {
  unsigned long now = millis();
  i++;
  if(i==0){
    Serial.println(now);
  }
}

The result is i overflows every 264 ms, so if(i<2) will be true many times per second.

A simple solution is to put i++; inside the if instead, like this:

void loop()
{
  if(i<2)
  {
    i++;
    Serial.print('#');
    Serial.print('1');
    delay(10);
  }
}

i will stop incrementing when the value is 2. No more overflow.

1

If you had put a Serial.print inside loop you would have seen the problem. Debugging displays are very helpful. Like this:

void loop()
{
  i++;
  Serial.println (i);   // <---- debugging
  if(i<2)
  {
    Serial.print('#');
    Serial.print('1');
    delay(10);
  }
}

Since you are adding 1 to i each time around the loop, how long do you think it will go before i overflows? It will go up and up, get to 32767 and then become -32768, and then count back to 0. During that time it will be less than 2, and it will do the printing of "#1".

  • I'll try that out Nick...I think that might have been the actual problem..I'll use a boolean variable maybe..thanks man! – Sparsha Saha Dec 15 '16 at 6:54

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.