Loading...
Searching...
No Matches
AnalogBurst.ino

Captures 500 samples of A0 at 20000 samples per second with analogReadBurst(), plots them in the Serial Plotter and prints the rate, lowest, highest and mean. The hardware takes the samples at evenly spaced times, so the plot shows the true waveform.

Wiring
A wire from D2 to A0: the sketch plays a 500 Hz test tone on D2. Or a signal generator on A0 (0-3.3 V), and remove the tone() line.
Output
Tools → Serial Plotter at 115200 baud: a square wave, then a line such as
Rate 20000 Hz, lowest 3, highest 4093, mean 2049
Notes
Highest rates: A0-A2 500000 samples/s, A3-A5 300000 samples/s. Change PIN, RATE_HZ and SAMPLES at the top of the sketch.
// Captures a waveform: 500 samples at a fixed rate, taken by the hardware at
// evenly spaced times, then plotted in the Serial Plotter (Tools > Serial
// Plotter, 115200 baud). Prints the sample rate, lowest, highest and mean too.
//
// Try it with a signal generator, or with tone(2, 500) and a wire from D2 to
// A0 (D2 is 0-3.3 V, so use A0-A2 for it, not A3-A5).
//
// Highest rates: A0-A2 500000 samples/s, A3-A5 300000 samples/s.
const pin_size_t PIN = A0;
const uint32_t RATE_HZ = 20000; // samples per second
const size_t SAMPLES = 500;
uint16_t samples[SAMPLES];
void setup() {
Serial.begin(115200);
while (!Serial) {}
tone(2, 500); // test signal on D2; remove if you use your own
}
void loop() {
const uint32_t rate = analogReadBurst(PIN, samples, SAMPLES, RATE_HZ);
if (rate == 0) {
Serial.println("Burst refused: check PIN and RATE_HZ");
delay(2000);
return;
}
uint16_t lowest = 4095;
uint16_t highest = 0;
uint32_t sum = 0;
for (size_t i = 0; i < SAMPLES; i++) {
if (samples[i] < lowest) lowest = samples[i];
if (samples[i] > highest) highest = samples[i];
sum += samples[i];
Serial.print("Signal:");
Serial.println(samples[i]);
}
Serial.print("Rate ");
Serial.print(rate);
Serial.print(" Hz, lowest ");
Serial.print(lowest);
Serial.print(", highest ");
Serial.print(highest);
Serial.print(", mean ");
Serial.println(sum / SAMPLES);
delay(2000);
}
SerialUSBClass Serial
USB serial port, the one the Serial Monitor uses.
void tone(uint8_t _pin, unsigned int frequency, unsigned long duration=0)
Plays a square wave (50 % duty) on a pin, for a buzzer or speaker.
void analogReadResolution(int bits)
Sets the number of bits analogRead() returns, for every analog pin.
uint32_t analogReadBurst(pin_size_t pin, uint16_t *buffer, size_t count, uint32_t sample_rate_hz)
Samples one analog pin at a fixed rate into an array, and waits until it is full.
void loop(void)
Written by the sketch: runs over and over after setup(), on core 0.
void setup(void)
Written by the sketch: runs once after reset, on core 0.
void delay(unsigned long)
Waits a number of milliseconds.
uint8_t pin_size_t
Type for Arduino pin numbers (uint8_t).
Definition Common.h:112