RNG90 microchip - Arduino Uno code


#include <Wire.h>
#include <SPI.h>
#include <SD.h>

unsigned char randomBytes[32];
byte status = 0;
const int chipSelect = 4;

void setup() {
  Wire.begin(0x40);             // Initialize I2C communication
  
  for (int i=0; i< 32; i++) {
    randomBytes[i] = 0;
  }
  Wire.setClock(100000);   // was 400K 

  Serial.begin(9600);       // Start serial communication for debugging
  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
      Serial.println("Card failed, full stop...");
      while (1);
  }
  Serial.println("Card initialized.");
  Serial.println("Reading random numbers from RNG90...");
  delay(2000);
}

void loop() {
  int i=0;
  File dataFile = SD.open("random.txt", FILE_WRITE); 

  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 i = 0; i < 20; i++) {
   Wire.write(0x00);  // 20 data bytes
  }
  Wire.write(0x7d); // crc
  Wire.write(0xe0);
  Wire.endTransmission();
 
  
  Wire.requestFrom(0x40, 32);    // Request 32 bytes (32-bites random number)
  i = 0;
  while (Wire.available()) {
      randomBytes[i] = Wire.read();
      if (status) {
        // if the file is available, write to it:
        if (dataFile) {
            dataFile.print(randomBytes[i]);
            dataFile.print(",");
        }        
      }
      i++;
  }  //while
    
  if (status) { 
     dataFile.println(); 
     dataFile.close();
     status = 0;
  } else {
    status = 1;
  }
  delay(1000);  // Wait 1 second before reading the next number
}