]> git.piffa.net Git - arduino/blob - books/ArduinoNextSteps-master/ArduinoNextSteps/sketch_06_06_EEPROM_example/sketch_06_06_EEPROM_example.ino
first commit
[arduino] / books / ArduinoNextSteps-master / ArduinoNextSteps / sketch_06_06_EEPROM_example / sketch_06_06_EEPROM_example.ino
1 // sketch_06_EEPROM_example
2
3 #include <EEPROM.h>
4
5 const int lockPin = 13;
6 const byte codeSetMarkerValue = 123;
7 const int defaultCode = 1234;
8
9 int code;
10 boolean locked = true;
11
12 void setup()
13 {
14   pinMode(lockPin, OUTPUT);
15   Serial.begin(9600);
16   while (! Serial) {}; // Wait for Serial to start (Leonardo only)
17   lock();
18   Serial.println("Enter the command U followed by code to unlock");
19   Serial.println("and L to lock again.");
20   Serial.println("Use the command C followed by a new code to change the code");
21   initializeCode();
22 }
23
24 void loop()
25 {
26   if (Serial.available())
27   {
28     char command = Serial.read();
29     if (command == 'U')
30     {
31       attemptUnlock();
32     }
33     else if (command == 'L')
34     {
35       lock();
36     }
37     else if (command == 'C')
38     {
39       if (locked)
40       {
41         Serial.println("Can only set new code when unlocked");
42       }
43       else
44       {
45         changeCode();
46       }
47     }
48   }
49 }
50
51 void initializeCode()
52 {
53   byte codeSetMarker = EEPROM.read(0);
54   if (codeSetMarker == codeSetMarkerValue)
55   {
56     code = readSecretCodeFromEEPROM();
57   }
58   else
59   {
60     code = defaultCode;
61   }
62 }
63
64 int readSecretCodeFromEEPROM()
65 {
66   byte high = EEPROM.read(1);
67   byte low = EEPROM.read(2);
68   return (high << 8) + low;
69 }
70
71 void saveSecretCodeToEEPROM()
72 {
73   EEPROM.write(0, codeSetMarkerValue);
74   EEPROM.write(1, highByte(code));
75   EEPROM.write(2, lowByte(code));
76 }
77
78 void attemptUnlock()
79 {
80   if (code == Serial.parseInt())
81   {
82     unlock();
83   }
84   else
85   {
86     Serial.println("Incorrect code");
87   }
88 }
89
90 void lock()
91 {
92   locked = true;
93   Serial.println("LOCKED");
94   digitalWrite(lockPin, LOW);
95 }
96
97 void unlock()
98 {
99   locked = false;
100   Serial.println("UN-LOCKED");
101   digitalWrite(lockPin, HIGH);
102 }
103
104 void changeCode()
105 {
106   code = Serial.parseInt();
107   saveSecretCodeToEEPROM();
108   Serial.print("Code Changed to:");
109   Serial.println(code);
110 }