Hello,
I'm using a Arduino Nano (ATmega328P) to connect a GY-61 ADXL335, trying to measure the acceleration of my vibration system. Since the vibration frequency is about 100Hz, I need the data output from serial can be at least 1000 data/s. However, I can only get around 250 data/s using the following code.
const int xInput= A1;
const int yInput= A2;
const int zInput= A3;
int Raw0=357;
int Raw3G=357+70*3;
int Rawn3G=357-70*3;
const int sampleSize = 1;
int ReadAxis(int axisPin)
{
long reading=0;
analogRead(axisPin);
delay(1);
for(int i=0; i< sampleSize;i++)
{
reading += analogRead(axisPin);
}
return reading/sampleSize;
}
void setup()
{
Serial.begin(500000);
}
void loop()
{
int xRaw = ReadAxis(xInput);
long xScaled = map(xRaw, Rawn3G, Raw3G, -3000,3000);
float xAccel = xScaled/1000.0;
Serial.print(xAccel,3);
Serial.println(" ");
delay(2);
}
Well, to start with, with a 2ms delay plus the code execution time, you'd be hard pressed to get the loop to run at 1 ms. just sayin'...
more to come
Add to that, your loop does things it doesn't need to. Strip it to the minimum to optimize execution time, see how fast that runs, then start adding frills like map() and float scaling.
Make your Serial call singular by doing it all in one call:
Serial.println(xAccel,3);
Fix ReadAxis() - another ms delay() in there???
So we have 3ms of pure delay, plus code execution time, and we want 1ms speed?
That should help. Let us know how that goes. I'm not in the habit of fixing code, but fix what I've suggested so far, and we'll go from there.
Sorry that I delete the comments in the code. The ReadAxis() is used to eliminate the noise of the reading from GY-61 ADXL335, so orignally the sample size is 10, which means the output should be the average of 10 readings.
This is actually I'm testing the output performance. Under the condition of theoretically 3ms delay, only about 250~260 data/s. No matter how I reduce the number of delay time, the output frequency does not change.
Many thanks! I'll keep working on my code. Will try to output the raw data first.
Many thanks for the reply. I'm sorry that I didn't make a clear description. This is the testing code to test the diffrence between theoretical and real output frequency. Under this condition, the output frequency can't reach its theoretical maximum rate, which is 333 data/s, no matter how I decrease the delay or increase the baud rate.
Thank you all for the suggestion. I'll try the fix now.