In: Computer Science
Arduino Uno code, Please explain what does this code do?
unsigned long ms_runtime;
int one_ms_timer;
//define all timers as unsigned variables
unsigned long timer1 = 0; // timer1 increments every 100ms =
0.1s
const int USER_LED_OUTPUT = 13;
const int USER_BUTTON_INPUT = 2;
void setup()
{ // initialize the digital pin as an output.
pinMode(USER_LED_OUTPUT, OUTPUT);
pinMode(USER_BUTTON_INPUT, INPUT);
Serial.begin(9600);
}
void loop()
{ // run loop forever
static int state, old_state,counter;
timers();
// logic for state change
if(state == 0)
{ if(digitalRead(USER_BUTTON_INPUT) == 1)
{ if(timer1 > 5)
state = 1;
}
else
timer1 = 0;
}
else if(state == 1)
{ if(digitalRead(USER_BUTTON_INPUT) == 0)
{ if(timer1 > 5)
state = 0;
}
else
timer1 = 0;
}
// execute commands based on state
if (state == 1)
digitalWrite(USER_LED_OUTPUT, HIGH);
else if (state == 0)
digitalWrite(USER_LED_OUTPUT, LOW);
// monitor and print changed of state
if(old_state != state)
{ counter++;
Serial.print("counter = ");
Serial.println(counter);
old_state = state;
}
}
void timers(void)
{
int i;
if(millis() > (ms_runtime + 1))
{ ms_runtime = ms_runtime + 1;
one_ms_timer++;
}
else if( ms_runtime > millis())
ms_runtime = millis();
if(one_ms_timer > 99)
{ timer1++;
one_ms_timer = 0;
}
}
The code is implemented as follows:
the timers() function returns the is basically for marking time in 100 ms.
in the setup() function we basically write all the defined pin modes like USER_LED_OUTPUT is for output and USER_BUTTON_INPUT is for input .
void loop is the part of the code where main functionality occurs. If the state is zero and user gives high input in the pin then if the timer is greater than zero i.e time passed is greater than 500 ms then value of state is set to 1 and the code gets into else if condition , but if input was not passed by the user then the timer1 is retained as zero.
In the elseif case the similar condition occurs , if user doesn't pass the input as low , then timer1 is retained to zero else state is made zero.
Then if the state is 1 then output in led is HIGH else led shows LOW.
Then finally the output is printed on the screen on the basis of the value of state. If value of state differs from that of the initial value , then counter is increased and its value is being printed and now old state is made equal to new state. It shows the number of time value of state changes in our experiment.