40 likes | 108 Views
Practice writing code to detect closed switches on Arduino's PORTD pins and control an LED on PB0 when a switch is closed. Includes pseudocode, setup, and loop instructions.
E N D
Warmup – 16FEB2012 Arduino This one is for practice. I have paper if you need it. PB0 Suppose there are eight, single-pole, single-throw (SPST) switches connected between the PORTD pins on the Arduino and ground. Write code (pseudocodefirst) to test and see if any one of the switches is closed. If any one of the switches is closed, turn on an LED on PB0. PD7 Poles: the number of separate circuits that can be controlled by the switch Throws: the number of separate connections that can be made by the movable switch element PD0 Single-pole/single-throw (SPST) Single-pole/double-throw (SPDT) Throws Pole Throw Pole Double-pole/double-throw (DPDT) Double-pole/single-throw (DPST)
#include “me106.h” #define LED PIN_D8 // PB0 #define ON HIGH #define OFF LOW #define N_COUNT 1 void setup() { for (inti = 0; i <= 7; i++) { pinMode(i, INPUT); digitalWrite(i, HIGH); } pinMode(LED, OUTPUT); } void loop() { byte n_low = 0; for (inti = 0; i <= 7; i++) { if ( digitalRead(i) == LOW) { n_low++; } } If ( n_low >= N_COUNT ) { digitalWrite( LED, ON); n_low = 0; } else { digitalWrite( LED, OFF); n_low= 0; } } Solution – Arduino Style Arduino Pseudocode PB0 Setup pins: PD0 – PD7 make INPUTS Turn on pullup resistors for PD0-PD7 Setup pin PB0 as OUTPUT Loop forever for all eight pins (PD0-PD7) if pin i is LOW increment n_low counter end if end for loop if n_low value >= n_count Turn on LED reset n_low counter else Turn off LED reset n_low counter end if PD7 PD0
Solution – PORT Style Arduino Pseudocode PB0 #include “me106.h” #define LED PIN_D8 // PB0 void setup() { DDRD = 0x00; PORTD | = 0xFF; DDRB | = ( 1 << 0 ); PORTB & = ( ~ (1 << 0 ) ); } void loop() { intcurrent_state = PIND; if ( ( ~ current_state) & 0xFF ) ) { PORTB | = ( 1 << 0 ); } else { PORTB &= ~( 1 << 0 ); } } Setup pins: PD0 – PD7 make INPUTS Setup pin PB0 as OUTPUT Loop forever get current state of PD0-PD7 if any of bits are zero turn on LED else Turn off LED end if PD7 PD0
Add blinking LED Arduino PB0 Suppose there are eight, single-pole, single-throw (SPST) switches connected between the PORTD pins on the Arduino and ground. Write code (pseudocodefirst) to test and see if any one of the switches is closed. If any one of the switches is closed, blink an LED on PB0 at a rate of 1 Hz. PD7 PD0