I am trying to toggle an LED light with a button. It is supposed to turn the LED
ID: 3697734 • Letter: I
Question
I am trying to toggle an LED light with a button. It is supposed to turn the LED on if it is turned off, and turn the LED off if it is turned on.
I am using a Raspberry Pi and writing my code in C.
My LED output is at GPIO pin 17, and my button output is at GPIO pin 18.
This is the code I have so far:
int main (void) {
wiringpiSetupGpio();
pinMode(17, OUTPUT);
pinMode(18, INPUT);
int prevState, reading, curState = LOW;
for(;;) {
curState = digitalRead(18);
if (curSate == HIGH && prevState == LOW) {
if (reading == 1){
digitalwrite(17, LOW);
reading = 0;
}
else {
digitalwrite(17, HIGH);
reading = 1;
}
}
prevState = curState;
}
return0;
}
Explanation / Answer
I have written the c code for the raspberry pi. working code:
#include <wiringPi.h>
int main (void)
{
wiringPiSetup ();
pinMode (17, OUTPUT);
pinMode (18, INPUT);
digitalWrite (0, LOW);
int button_state = HIGH, reading = 0;
for(;;)
{
if(button_state == HIGH && digitalRead(1) == LOW)
{
button_state = LOW;
if(reading)
{
reading = 0;
digitalWrite(0, LOW);
}
else
{
reading = 1;
digitalWrite(0, HIGH);
}
}
else if(button_state == LOW && digitalRead(1) == HIGH)
{
button_state = HIGH;
)
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.