RNG90 serial output - Arduino Nano code
// Arduino nano ATmega328P (old bootloader)
// I2C A4 and A5
// switches on pins 10 and 9
#include <Wire.h>
unsigned char randomBytes[32];
boolean status =false;
char flip=0;
void printBytes(char sw) {
if (sw == 1) {
for (int i=0; i <32; i++) {
randomBytes[i] = randomBytes[i] / 43 + 1;
Serial.print(randomBytes[i]);
Serial.print(",");
}
} else if (sw == 2) {
for (int i=0; i <32; i++) {
Serial.print(randomBytes[i], HEX);
Serial.print(",");
}
} else if (sw == 3) {
for (int i=0; i <32; i++) {
Serial.print(randomBytes[i],BIN);
Serial.print(",");
}
} else {
for (int i=0; i <32; i++) {
Serial.print(randomBytes[i]);
Serial.print(",");
}
}
Serial.println();
}
void setup() {
String text="decimal...";
pinMode(10, INPUT_PULLUP);
pinMode(9, INPUT_PULLUP);
// flip == 0 32rnd 0-255
if (digitalRead(10) == 0) flip += 1; // 1 1-6
if (digitalRead(9) == 0) flip +=2; // 2 hex 3 binary
Wire.begin(0x40); // Initialize I2C communication
for (int i=0; i< 32; i++) {
randomBytes[i] = 0;
}
Wire.setClock(400000);
Serial.begin(9600); // Start serial communication for debugging
Serial.println();
if (flip == 3) text = "binary...";
else if (flip == 2) text = "hexadecimal...";
else if (flip == 1) text = "dice...";
Serial.print("Reading ");
Serial.println(text);
delay(2000);
}
void loop() {
Wire.beginTransmission(0x40); // Start communication with RNG90
if (status) {
Wire.write(0x40); // i2c address
}
Wire.write(0x03); // word address value
Wire.write(0x1b); // count (N+1) = 27
Wire.write(0x16); // Request the random number register
Wire.write(0x00); // 1st parameter
Wire.write(0x00); // 2nd parameter
Wire.write(0x00);
for (int k = 0; k < 20; k++) {
Wire.write(0x00); // 20 data bytes
}
Wire.write(0x7d); // crc
Wire.write(0xe0);
Wire.endTransmission();
Wire.requestFrom(0x40, 1); // Request 32 bytes (32-bites random number)
int i = 0;
while (Wire.available()) {
randomBytes[i] = Wire.read();
i++;
}
Wire.requestFrom(0x40, 32); // Request 32 bytes (32-bites random number)
i = 0;
while (Wire.available()) {
randomBytes[i] = Wire.read();
i++;
}
if (status) {
printBytes(flip);
status = false;
} else {
status = true;
}
delay(500); // Wait 1/2 second before reading the next number
}