Interrupts:
The processor responds to important events. Interrupts interrupt whatever the processor is doing and executes code designer to react to external stimulus.
The processor responds to important events. Interrupts interrupt whatever the processor is doing and executes code designer to react to external stimulus.
EEPROM (Electrically Erasable Programmable Read-Only Memory):
Solid state computer memory. Permanent storage similar to a hard drive in computers. Can be read, erased and re-written electronically.
| Microcontroller | EEPROM |
| ATmega328 (Arduino Uno, Nano, Mini) | 1024 bytes |
| ATmega168 (Arduino Nano) | 512 bytes |
| ATmega2560 (Arduino Mega) | 4096 bytes |
Remembers the last state of a variable/remembers how many times an appliance was activated.
Ex Scenario. LAMP (on) connected to Arduino -- Arduino loses power -- When power is back on, LAMP stays off (does not keep it's last change).
Solution: Save LAMP state in EEPROM and add condition to sketch to check whether the state of the lamp corresponds to the previous state.
Schematic:
1x Arduino Uno
1x LED
1x Resistor
1x Button
1x 1k Resistor
1x Breadboard
5x Jumpers
1x LED
1x Resistor
1x Button
1x 1k Resistor
1x Breadboard
5x Jumpers
Code:#include <EEPROM.h> const int buttonPin = 8; // pushbutton pin const int ledPin = 4; // LED pin int ledState; // variable to hold the led state int buttonState; // the current reading from the input pin int lastButtonState = LOW; // the previous reading from the input pin // the following variables are long's because the time, measured in miliseconds, // will quickly become a bigger number than can be stored in an int. long lastDebounceTime = 0; // the last time the output pin was toggled long debounceDelay = 50; // the debounce time; increase if the output flickers void setup() { pinMode(buttonPin, INPUT); pinMode(ledPin, OUTPUT); digitalWrite(ledPin, ledState); Serial.begin (9600); checkLedState(); } void loop() { int reading = digitalRead(buttonPin); if(reading != lastButtonState) { lastDebounceTime = millis(); } if((millis() - lastDebounceTime) > debounceDelay) { if(reading != buttonState) { buttonState = reading; if(buttonState == HIGH) { ledState = !ledState; } } } digitalWrite(ledPin, ledState); EEPROM.update(0, ledState); lastButtonState = reading; } void checkLedState() { Serial.println("LED status after restart: "); ledState = EEPROM.read(0); if(ledState == 1) { Serial.println ("ON"); digitalWrite(ledPin, HIGH); } if(ledState == 0) { Serial.println ("OFF"); digitalWrite(ledPin, LOW); } }

No comments:
Post a Comment