1 // sketch_06_EEPROM_example
5 const int lockPin = 13;
6 const byte codeSetMarkerValue = 123;
7 const int defaultCode = 1234;
10 boolean locked = true;
14 pinMode(lockPin, OUTPUT);
16 while (! Serial) {}; // Wait for Serial to start (Leonardo only)
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");
26 if (Serial.available())
28 char command = Serial.read();
33 else if (command == 'L')
37 else if (command == 'C')
41 Serial.println("Can only set new code when unlocked");
53 byte codeSetMarker = EEPROM.read(0);
54 if (codeSetMarker == codeSetMarkerValue)
56 code = readSecretCodeFromEEPROM();
64 int readSecretCodeFromEEPROM()
66 byte high = EEPROM.read(1);
67 byte low = EEPROM.read(2);
68 return (high << 8) + low;
71 void saveSecretCodeToEEPROM()
73 EEPROM.write(0, codeSetMarkerValue);
74 EEPROM.write(1, highByte(code));
75 EEPROM.write(2, lowByte(code));
80 if (code == Serial.parseInt())
86 Serial.println("Incorrect code");
93 Serial.println("LOCKED");
94 digitalWrite(lockPin, LOW);
100 Serial.println("UN-LOCKED");
101 digitalWrite(lockPin, HIGH);
106 code = Serial.parseInt();
107 saveSecretCodeToEEPROM();
108 Serial.print("Code Changed to:");
109 Serial.println(code);