User Input Features of The Fan: - Potentiometer For Speed Control
User Input Features of The Fan: - Potentiometer For Speed Control
1 and 3
1 and 4
2 and 3
1 and 3
1 and 4
2 and 3
• Normally open
❖ electrical contact is made when button is pressed
• Normally closed
❖ electrical contact is broken when button is pressed
• Internal spring returns button to its un-pressed state
Pull-up
resistor:
Pull-down
resistor:
void setup() {
pinMode( button_pin, INPUT);
Serial.begin(9600); // Button state is sent to host
}
void loop() {
int button;
button = digitalRead( button_pin );
if ( button == HIGH ) {
Serial.println("on"); Serial monitor shows
} else {
Serial.println("off"); a continuous stream
} of “on” or “off”
}
3. Interrupt Handler
4. All three programs use the same electrical circuit
void setup() {
int start_click = LOW; // Initial state: no click yet
pinMode( button_pin, INPUT);
Serial.begin(9600); while loop
continues as long
while ( !start_click ) {
start_click = digitalRead( button_pin ); as start_click is
Serial.println("Waiting for button press"); FALSE
}
}
Same loop() function
void loop() {
int button;
as in the preceding
sketch
button = digitalRead( button_pin );
if ( button == HIGH ) {
Serial.println("on");
} else {
Serial.println("off");
}
}
3. Interrupt Handler
❖ Most versatile
❖ Does not block execution
❖ Interrupt is used to change a flag that indicates state
❖ Regular code in loop function checks the sate of the flag
void setup() {
Serial.begin(9600);
attachInterrupt( button_interrupt, handle_click, RISING); // Register handler
}
void loop() {
if ( toggle_on ) {
Serial.println("on");
} else {
Serial.println("off");
}
}
void handle_click() {
last_interrupt_time = interrupt_time;
}
last_interrupt_time = interrupt_time;
}
void loop() {
if ( toggle_on ) { The loop() function only checks the
Serial.println("on");
} else { state of toggle_on. The value of
Serial.println("off"); toggle_on is set in the interrupt
} handler, handle_click.
}
void handle_click() {
void setup() {
Serial.begin(9600);
attachInterrupt( button_interrupt, handle_click, RISING); // Register handler
}
Value of a static variable is always
void loop() { retained
if ( toggle_on ) { Use long: the time value in
Serial.println("on");
} else { milliseconds can become
Serial.println("off"); large
} Clock time when current interrupt
}
occurs
void handle_click() { Ignore events that occur in less than
200 msec from each other. These
static unsigned long last_interrupt_time = 0; // Zero only at start
unsigned long interrupt_time = millis(); are likely
// Readtothe
be clock
mechanical bounces.
last_interrupt_time = interrupt_time;
Save current time as the new “last”
} time