Question: Write a program in C to modify the state of LED1 and LED2 depending upon whether SW1 or SW2 is pressed. At program startup, LED1
Write a program in C to modify the state of LED1 and LED2 depending upon whether SW1 or SW2 is pressed. At program startup, LED1 should be on and LED2 should be off. As long as SW1 is pressed, both LEDs should be turned on and as long as SW2 is pressed, LED1 and LED2 should blink at 4Hz alternately.
Summary: LED1 LED2
No Switch Pressed (LED1-On, LED2-Off)
SW1 Pressed (LED1-On, LED2-On)
SW2 Pressed (LED1-4Hz, LED2-4Hz) (alternately)
After Releasing SW1/SW2 (LED1-Off, LED2-Off)
I need help implementing SW2. I have the code for SW1 and blinking LEDs working, but I need to somehow implement pressing SW2 in my blinking code.
#include
#define S1 P2IN&BIT1 #define REDLED 0x01 // Mask for BIT0 = 0000_0001b #define GREENLED 0x80 // Mask for BIT7 = 1000_0000b
void main(void) // SW1 { WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer P1DIR |= REDLED; // Set P1.0 to output direction P4DIR |= GREENLED; // Set P4.7 to output direction P1OUT &= ~REDLED; // LED1 is OFF P4OUT &= ~GREENLED; // LED2 is OFF P2DIR &= ~BIT1; // Set P2.1 as input for S1 input P2REN |= BIT1; // Enable the pull-up resistor at P2.1 P2OUT |= BIT1; // Required for proper IO unsigned int i = 0; while(1) // Infinite loop { if ((S1) == 0) // If S1 is pressed { for (i = 2000; i > 0; i--); // Debounce ~20 ms if ((S1) == 0) // If S1 is pressed { P1OUT |= REDLED; // Turn LED1 on P4OUT |= GREENLED; // Turn LED2 on } while ((S1) == 0); // Hang-on as long as S1 pressed } else { P1OUT &= ~REDLED; // Turn LED1 off P4OUT &= ~GREENLED; // Turn LED2 off } } }
void main(void) // blinking LEDS { WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer P1DIR |= REDLED; // Set P1.0 to output direction P4DIR |= GREENLED; // Set P4.7 to output direction P1OUT &= ~REDLED; // LED1 is OFF P4OUT |= GREENLED; // LED2 is ON P1DIR &= ~BIT1; // Set P2.1 as input for S1 input P1REN |= BIT1; // Enable the pull-up resistor at P2.1 P1OUT |= BIT1; // Required for proper IO unsigned int i = 0; while(1) // Infinite loop { for (i = 0; i < 40000; i++); // Delay 0.1ms // 0.5s on, 0.5s off => 1/(0.25s) = 4Hz P1OUT ^= REDLED; // Toggle LED1 P4OUT ^= GREENLED; // Toggle LED2 } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
