/*
AnalogReadSerial
WOKWI-Simulation: https://wokwi.com/projects/360903822433974273
Discussion: https://forum.arduino.cc/t/millis-instead-of-delay-and-loop-instead-of-for-loop/1110044/2
Reads an analog input on pin 0, prints the result to the Serial Monitor.
reading is done very often. Additionally a variable is counted up very fast
incremented by 1 with each iteration of loop
printing the value to the serial monitor is done only once per second
the delay is realised WITHOUT function delay() with non-blocking timing
Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
This example code is in the public domain.
*/
unsigned long fastCounter = 0; // variable fastCounter does demonstrate the fast looping of function loop()
unsigned long countSeconds = 0;
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 115200 bits per second:
// make sure to adjust the serial monitor to 115200 baud
Serial.begin(115200);
Serial.println( F("Setup-Start") );
}
// the loop routine runs over and over again forever:
void loop() {
// increment variable fastCounter with every iteration of loop
// for demonstration of how fast loop is looping
fastCounter++;
doMeasuringPrintFromTimeToTime(); // call this function
}
void doMeasuringPrintFromTimeToTime() {
static unsigned long timeStamp; // attribute static makes the variable persistant
int sensorValue;
sensorValue = analogRead(A0); // read the input on analog pin 0:
// check if 1001 milliseconds have passed by since last measuring
if (millis() - timeStamp >= 1001) {
// when 1001 milliseconds REALLY have passed by
timeStamp = millis(); // store actual time as new timestamp
countSeconds++; // increment variable countSeconds
Serial.print( F("sec:") );
Serial.print(countSeconds);
Serial.print( F(" Value=") ); // print out the value you read:
Serial.print(sensorValue);
Serial.print( F(" counter counts up very fast=") );
Serial.println(fastCounter);
}
}