diff --git a/examples/ECCX08Counter/ECCX08Counter.ino b/examples/ECCX08Counter/ECCX08Counter.ino new file mode 100644 index 0000000..319543b --- /dev/null +++ b/examples/ECCX08Counter/ECCX08Counter.ino @@ -0,0 +1,43 @@ +/* + ECCX08 Counter + + This sketch uses the ECC508 or ECC608 to increment a monotonic + counter at each startup + + Circuit: + - Any board with ECC508 or ECC608 on board + +*/ + +#include + +const int keyId = 5; +long counter = -1; + +void setup() { + Serial.begin(9600); + while (!Serial); + + if (!ECCX08.begin()) { + Serial.println("Failed to communicate with ECC508/ECC608!"); + while (1); + } + + if (!ECCX08.incrementCounter(keyId, counter)) { + Serial.println("Failed to increment counter"); + while (1); + } +} + +void loop() { + if (!ECCX08.readCounter(keyId, counter)) { + Serial.println("Failed to read counter"); + while (1); + } + + Serial.print("Counter value = "); + Serial.println(counter); + + delay(1000); +} + diff --git a/src/ECCX08.cpp b/src/ECCX08.cpp index 0164343..502497b 100644 --- a/src/ECCX08.cpp +++ b/src/ECCX08.cpp @@ -548,6 +548,80 @@ int ECCX08Class::nonce(const byte data[]) return challenge(data); } +int ECCX08Class::incrementCounter(int counterId, long& counter) +{ + if (counterId < 0 || counterId > 1) { + return 0; + } + + if (!wakeup()) { + return 0; + } + + if (!sendCommand(0x24, 1, counterId)) { + return 0; + } + + delay(20); + + if (!receiveResponse(&counter, sizeof(counter))) { + return 0; + } + + delay(1); + idle(); + + return 1; +} + +long ECCX08Class::incrementCounter(int counterId) +{ + long counter; // the counter can go up to 2,097,151 + + if(!incrementCounter(counterId, counter)) { + return -1; + } + + return counter; +} + +int ECCX08Class::readCounter(int counterId, long& counter) +{ + if (counterId < 0 || counterId > 1) { + return 0; + } + + if (!wakeup()) { + return 0; + } + + if (!sendCommand(0x24, 0, counterId)) { + return 0; + } + + delay(20); + + if (!receiveResponse(&counter, sizeof(counter))) { + return 0; + } + + delay(1); + idle(); + + return 1; +} + +long ECCX08Class::readCounter(int counterId) +{ + long counter; // the counter can go up to 2,097,151 + + if(!readCounter(counterId, counter)) { + return -1; + } + + return counter; +} + int ECCX08Class::wakeup() { _wire->setClock(_wakeupFrequency); @@ -892,4 +966,4 @@ uint16_t ECCX08Class::crc16(const byte data[], size_t length) ECCX08Class ECCX08(CRYPTO_WIRE, 0x60); #else ECCX08Class ECCX08(Wire, 0x60); -#endif \ No newline at end of file +#endif diff --git a/src/ECCX08.h b/src/ECCX08.h index 54fdc3a..c2f21e1 100644 --- a/src/ECCX08.h +++ b/src/ECCX08.h @@ -66,6 +66,11 @@ class ECCX08Class int nonce(const byte data[]); + int incrementCounter(int counterId, long& counter); + long incrementCounter(int counterId); + int readCounter(int counterId, long& counter); + long readCounter(int counterId); + private: int wakeup(); int sleep();