Search code examples
arduinoarduino-unoarduino-ide

How can I make the loop() execute exactly once in Arduino?


How can I prevent the code to print output twice? The loop() in Arduino is runnin twice despite using exit(0). How can I prevent that? While(1) also didn't work. Input has to be hardcoded. No input through serial is permitted.

#include<SoftwareSerial.h>

SoftwareSerial s(10,11);

int roll_num =123, roll[10], i=0, r, j; 
char x;

void setup()
{
       s.begin(9600); 
       Serial.begin(9600); //Opens serial port, sets data rate to 9600 bps.
       //Serial.println("Enter roll number");
       //int roll_num; 
       
}    

void loop()
{
       //if (Serial.available()>0)
       //{
           //x=Serial.read(); // Reads the incoming byte.
           //roll_num = x - '0';
           while (roll_num != 0) 
           {
                //Extracts the last digit of roll number
                r = roll_num % 10;
  
                //Puts the digit in roll[]
                roll[i] = r;
                i++;
  
                //Updates roll_num to roll_num/10 to extract next last digit
                roll_num = roll_num / 10;
           }

           for(j=i-1; j>=0; j--)
           {
                Serial.print("sent number: ");
                Serial.println(roll[j]);
                s.write(roll[j]); //Writes a binary digit of the roll number to the serial port.
           }
      //}
      delay(100);
      exit(0); 
      //while(1);
}

Output:

sent number: 1
sent number: 2
sent number: 3
sent number: 1
sent number: 2
sent number: 3

Solution

  • One way to execute the contents of loop() could be to wrap it in a conditional statement and create a global boolean that is offset at the end of the first loop.

    bool firstLoop = true;
    void loop()
    {
        if (firstLoop){
            doThisOnce();
            firstLoop = false;
        }
    }
    
    void doThisOnce()
    { 
        
    }