|
| 1 | +#include <Adafruit_NeoPixel.h> |
| 2 | +#include "OPTIGATrustM.h" |
| 3 | + |
| 4 | +//--| User Config |----------------------------------------------- |
| 5 | +#define TRNG_FORMAT 2 // 0=raw, 1=CSV, 2=JSON |
| 6 | +#define TRNG_LENGTH 8 // random number length in bytes, 8 to 256 |
| 7 | +#define TRNG_RATE 100 // generate new number ever X ms |
| 8 | +#define BEAT_RATE 1000 // neopixel heart beat rate in ms, 0=none |
| 9 | +#define BEAT_COLOR 0xADAF00 // neopixel heart beat color |
| 10 | +//---------------------------------------------------------------- |
| 11 | + |
| 12 | +uint8_t trng[TRNG_LENGTH]; |
| 13 | +int current_time, last_trng, last_beat; |
| 14 | + |
| 15 | +Adafruit_NeoPixel neopixel(1, PIN_NEOPIXEL, NEO_GRB + NEO_KHZ800); |
| 16 | + |
| 17 | +void setup() |
| 18 | +{ |
| 19 | + Serial.begin(115200); // USB CDC doesn't really care about baud rate |
| 20 | + |
| 21 | + if (trustM.begin()) { |
| 22 | + Serial.println("Failed to initialize Trust M."); |
| 23 | + neoPanic(); |
| 24 | + } |
| 25 | + |
| 26 | + neopixel.begin(); |
| 27 | + neopixel.fill(0); |
| 28 | + neopixel.show(); |
| 29 | + |
| 30 | + last_trng = last_beat = millis(); |
| 31 | +} |
| 32 | + |
| 33 | +void loop() |
| 34 | +{ |
| 35 | + current_time = millis(); |
| 36 | + |
| 37 | + if (current_time - last_trng > TRNG_RATE) { |
| 38 | + trustM.getRandom(TRNG_LENGTH, trng); |
| 39 | + sendTRNG(); |
| 40 | + last_trng = current_time; |
| 41 | + } |
| 42 | + |
| 43 | + if ((BEAT_RATE) && (current_time - last_beat > BEAT_RATE)) { |
| 44 | + if (neopixel.getPixelColor(0)) { |
| 45 | + neopixel.fill(0); |
| 46 | + } else { |
| 47 | + neopixel.fill(BEAT_COLOR); |
| 48 | + } |
| 49 | + neopixel.show(); |
| 50 | + last_beat = current_time; |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +void sendTRNG() { |
| 55 | + if (TRNG_FORMAT) { |
| 56 | + // formatted string output (CSV, JSON) |
| 57 | + if (TRNG_FORMAT==2) Serial.print("{\"trng\": \""); |
| 58 | + for (uint16_t i=0; i<TRNG_LENGTH; i++) { |
| 59 | + Serial.print(trng[i]); |
| 60 | + if (i != TRNG_LENGTH - 1) Serial.print(", "); |
| 61 | + } |
| 62 | + if (TRNG_FORMAT==2) Serial.print("\"}"); |
| 63 | + Serial.println(); |
| 64 | + } else { |
| 65 | + // raw output (bytes) |
| 66 | + Serial.write(trng, TRNG_LENGTH); |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | + |
| 71 | +void neoPanic() { |
| 72 | + while (1) { |
| 73 | + neopixel.fill(0xFF0000); neopixel.show(); delay(100); |
| 74 | + neopixel.fill(0x000000); neopixel.show(); delay(100); |
| 75 | + } |
| 76 | +} |
0 commit comments