Set your bad rate to 115200, and remove the delay command. That will run the loop as fast as it can and output to serial at the highest data rate supported.
jjspierx:
Set your bad rate to 115200, and remove the delay command. That will run the loop as fast as it can and output to serial at the highest data rate supported.
if i remove the delay, then how do i know what is the sample rate?
do i need using timers?
you can even set the baudrate to 230400 or 345600 or 500000 (check what matlab supports)
The analogread does max about 8000 per second (0.125 ms) in a tight loop. As you need 2 bytes to send its value you get the formula
sample rate = 1 / (0.000125 + timetosend2bytes)
at 115200 every byte (+start/stop bit) takes ~1 ms ==> 2bytes = 2 ms
rate = 1 / 0.002125 = 470 samples per second.
if you can use 345600 baud, 2 bytes take 0.666 ms so in total~ 0.0008 raising the sample rate to 1250/second.
However if the samples do not differ much you can send one signed byte that gives the delta to the previous value. Just send -126..+126.
[a value of 127 can be used to indicate that the next 2 bytes is a new reference value] @115200 baud : sample + 1 byte ==> 1.125 ==> ~880 samples per second. (OK sometimes you need more, so lets say ~800 bytes.
If samples are often the same you could even consider RunLengthEncoding
Other compression to think of:
As the analog read uses effectively 10 bits, you can pack 5 samples in 8 bytes.
That would give you a sample&send rate of 8.625 ms for 5 samples ==> 580 samples/sec @115200 baud (~1500 @345600)
You can also calculate backwards, how many samples per second do I need and calculate the max baudrate from that.
e.g. 200 samples per second
200 x 0.125 ms => 25 ms, gives me 975 msec to send 4400 bits (incl start/stop) => 4400/0.975 = 4513 ==> so 4800 baud should just fit.
But better use the blink without delay technique
(not tested but give it a try
int analogin = A2;
int samplesPerSecond = 100;
unsigned long delayBetweenSamples = 1000000UL/samplesPerSecond; // calculate in micros
unsigned long lastSample = 0;
void setup()
{
Serial.begin(115200);
}
void loop()
{
if (micros() - lastSample >= delayBetweenSamples)
{
lastSample = micros();
int valor = analogRead(analogin);
Serial.println(valor);
}
}
Note: in my calculations above I did'nt count in the CR LF which is used as separator between the values (3x as much data to send over serial) and you send teh values as text (factor 2). In total 6 bytes for 1 value ~6ms