I guess I have to add my main goal: I want to make the sending as fast for the arduino as possible. No extra calculations should be necessary (if possible). And: the reason for these shifts seems to be the some time delay (slowness). I suspect it to be a slow matlab reading, since I saw fluent processing scripts in HIL reading. The errors have stopped however, since I turned the baude rate down. Only wrong numbers are the problem still.
May there be a possibility to loop around the fread and read just store the values after an added 'header'? So let's say a wrong ordering occures. Then I discard everything until the next 'a' char/byte and use the following 6 bytes to produce my 3 values. Then I wait for an 'a' again. For that I would have to loop fread(s,[1,1],'int8'); and search for the header.
Full arduino code:
// Program to send the gyro/accel data via serialport
// corresponding matlab programs: sensing.m and sensing_binary.m
// 2 security loops to guarantee a constant sampling time
// #define DEBUG
#include "GY86.h"
#include "Wire.h"
GY86 gy86;
int16_t ax, ay, az;
int16_t gx, gy, gz;
uint32_t currenttime = 0;
uint32_t starttime = 0;
uint32_t starttime2 = 0;
// #define OUTPUT_ACCEL_COUNTS
#define OUTPUT_GYRO_COUNTS
// #define OUTPUT_ACCEL_BINARY
// #define OUTPUT_GYRO_BINARY
void setup () {
Serial.begin(1152009600);
gy86.setup();
}
void loop () {
currenttime = millis();
if (currenttime-starttime > 9)
{
while (micros()-starttime2 < 9000) { }
starttime2 = micros();
// read raw accel/gyro measurements from device
gy86.getSensorValues(&ax, &ay, &az, &gx, &gy, &gz);
// testing constants
// gx = -29;
// gy = 245;
// gz = 17;
#ifdef OUTPUT_GYRO_COUNTS
Serial.print((int)gx); Serial.print(F("\t"));
Serial.print((int)gy); Serial.print(F("\t"));
Serial.print((int)gz); Serial.print(F("\t"));
#endif
#ifdef OUTPUT_ACCEL_COUNTS
Serial.print(ax); Serial.print(F("\t"));
Serial.print(ay); Serial.print(F("\t"));
Serial.println(az); Serial.print(F("\t"));
#endif
#if defined(OUTPUT_ACCEL_COUNTS) || defined(OUTPUT_GYRO_COUNTS)
Serial.print(F("\n"));
#endif
#ifdef OUTPUT_ACCEL_BINARY
Serial.write((uint8_t)(ax >> 8)); Serial.write((uint8_t)(ax & 0xFF));
Serial.write((uint8_t)(ay >> 8)); Serial.write((uint8_t)(ay & 0xFF));
Serial.write((uint8_t)(az >> 8)); Serial.write((uint8_t)(az & 0xFF));
#endif
#ifdef OUTPUT_GYRO_BINARY
Serial.write((uint8_t)(gx >> 8)); Serial.write((uint8_t)(gx & 0xFF));
Serial.write((uint8_t)(gy >> 8)); Serial.write((uint8_t)(gy & 0xFF));
Serial.write((uint8_t)(gz >> 8)); Serial.write((uint8_t)(gz & 0xFF));
#endif
starttime = currenttime;
}
}