I have this code uploaded to an Arduino Uno which is connected to a gyroscope and storing the data on an SD card. The code is from the OEM.
The delay() function was set to 500 by default but this was changed to 10 in order to get an output frequency of 100Hz.
The millis() function was added to observe whether the 100Hz frequency was being maintained.
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
File myFile;
#define CTRL_REG1 0x20
#define CTRL_REG2 0x21
#define CTRL_REG3 0x22
#define CTRL_REG4 0x23
int Addr = 105; // I2C address of gyro
int x, y, z;
void setup(){
Wire.begin();
Serial.begin(9600);
Serial.print("Initializing SD card...");
if (!SD.begin(10)) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");
writeI2C(CTRL_REG1, 0x1F); // Turn on all axes, disable power down
writeI2C(CTRL_REG3, 0x08); // Enable control ready signal
writeI2C(CTRL_REG4, 0x80); // Set scale (500 deg/sec)
delay(100); // Wait to synchronize
}
void loop(){
myFile = SD.open("test.txt", FILE_WRITE);
getGyroValues(); // Get new values
// In following Dividing by 114 reduces noise
Serial.print(millis());
Serial.print(" Raw X:"); Serial.print(x / 114);
Serial.print(" Raw Y:"); Serial.print(y / 114);
Serial.print(" Raw Z:"); Serial.println(z / 114);
myFile.print(millis());
myFile.print(" Raw X:"); myFile.print(x / 114);
myFile.print(" Raw Y:"); myFile.print(y / 114);
myFile.print(" Raw Z:"); myFile.println(z / 114);
myFile.close();
delay(10); // Short delay between reads
}
void getGyroValues () {
byte MSB, LSB;
MSB = readI2C(0x29);
LSB = readI2C(0x28);
x = ((MSB << 8) | LSB);
MSB = readI2C(0x2B);
LSB = readI2C(0x2A);
y = ((MSB << 8) | LSB);
MSB = readI2C(0x2D);
LSB = readI2C(0x2C);
z = ((MSB << 8) | LSB);
}
int readI2C (byte regAddr) {
Wire.beginTransmission(Addr);
Wire.write(regAddr); // Register address to read
Wire.endTransmission(); // Terminate request
Wire.requestFrom(Addr, 1); // Read a byte
while(!Wire.available()) { }; // Wait for receipt
return(Wire.read()); // Get result
}
void writeI2C (byte regAddr, byte val) {
Wire.beginTransmission(Addr);
Wire.write(regAddr);
Wire.write(val);
Wire.endTransmission();
}
However, these are the first few values that were saved onto the "test.txt" file:
This shows a change in time of approximately 0.03s between values and therefore a frequency of 33.3Hz. Does anyone know why this is the case?
0.030s/loop()
.