Arduino Uno code, Please explain what does this code do? unsigned long ms_runtime; int one_ms_timer; //define all timers...

80.2K

Verified Solution

Question

Programming

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;
}
}

Answer & Explanation Solved by verified expert
4.0 Ratings (715 Votes)
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 USERLEDOUTPUT is for output    See Answer
Get Answers to Unlimited Questions

Join us to gain access to millions of questions and expert answers. Enjoy exclusive benefits tailored just for you!

Membership Benefits:
  • Unlimited Question Access with detailed Answers
  • Zin AI - 3 Million Words
  • 10 Dall-E 3 Images
  • 20 Plot Generations
  • Conversation with Dialogue Memory
  • No Ads, Ever!
  • Access to Our Best AI Platform: Flex AI - Your personal assistant for all your inquiries!
Become a Member

Other questions asked by students