Reading from Analog port fixed frequency

Hi everyone!
I need to read from an Analog port at a fixed "low" frequency (125Hz-250Hz)... I don't need to read faster than that and report the data through Serial to a PC...
I know I can do the read using the analogRead() and also know I can set a pre-scalar but I don't know how to make the frequency adjustable. Another question I wanted to ask is, wouldn't it be better to a store a bunch of values in an array and then send the array through Serial Port?! I don't know if sending every value individually will crash at this speed.

Have a look at how millis() is used to manage timing without blocking in Several things at a time

...R

xykudyax:
Hi everyone!
I don't know if sending every value individually will crash at this speed.

analogRead() takes about 100 microseconds (0.0001 s) to read an analog input, so the maximum reading rate is about 10,000 times a second.

for good resolution between reads you may want to use micros() instead of millis().

since your data is two bytes, if you use a fast baud rate (i.e. 115200) you can probably keep up easily sending data packet real-time.

void loop(void)
{
  int newValue = analogRead(myPin);  // ~100 microseconds
  Serial.write(highByte(newValue)); // high order byte ~10 - 15 microseconds??
  Serial.write(lowByte(newValue));  // low order byte ~10 - 15 microseconds??
  Serial.write('\n'); // new line
  delayMicroseconds(adjustedValueToCompensateForFunctionTimesAbove);
}

Sending a newline after two bytes of binary would be a waste of 1/3 of the bandwidth. Since only 2 bits of the high byte are used you can use the upper 6 bits for synchronization:

void loop(void) {
  int newValue = analogRead(myPin);  // ~100 microseconds
  Serial.write(highByte(newValue) | 0xA8); // high order byte ~10 - 15 microseconds??
  Serial.write(lowByte(newValue));  // low order byte ~10 - 15 microseconds??
  delayMicroseconds(adjustedValueToCompensateForFunctionTimesAbove);
}

Then the PC can look at the top 6 bits and get a very good indication of high-byte vs low-byte and re-sync.

Read highByte.
If (highByte & 0xFC != 0xA8) read highByte again
Read lowByte.

Possibly better would be to put 5 bits in each byte and use the upper 3 bits to indicate if it is high-byte or low-byte.