I am using the Arduino Uno to observe the duration of a voltage change. I am sampling the voltage every 10 milliseconds by using delay(10) and I am getting duration by using millis() to obtain the time at voltage changes. With this, I expect to see durations in increments of 10 milliseconds, but I am getting values in between. When the duration of the voltage change is small (<100), I am getting values like 31, 41, 51, and rarely values like 29 and 49 or 62 and 72. When the duration is several hundreds of milliseconds, the values can have anything in the ones place.
Could this be due to the fact that the code is taking some time to run or rounding errors? or is there something with the millis() or delay() functions that I am missing?
P.S. don't bother telling me to change my code; I'm just curious as to why I'm getting these intermediate values ( sorry, a lot of people on here just criticize and don't help )
Here's my code (I am running arduino output 10 through a voltage splitter which comes back to A0)
int touchCountA = 0;
int touchCountB = 0;
#include <SPI.h>
#include <SD.h>
File myFile;
void setup() {
// Set A0 as analog input
pinMode(A0, INPUT);
// Set 10 as digital output for SD reader
pinMode(10, OUTPUT);
// Starts the SD reader from pin 4
SD.begin(4);
// Starts Serial communications(with computer if connected)
Serial.begin(9600);
//Open(or create if non-existent) dat.txt
myFile = SD.open("dat.txt", FILE_WRITE);
// Prints this line whenever power is turned on
myFile.println("TchA,TchB,Time,Dur");
myFile.close();
//for LEDs
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
}
void loop() {
int voltage = analogRead(A0);
// Serial.println(voltage);
// Voltage splits if Lick Spout A
if(voltage >= 300 && voltage <= 380){
long touchTime = millis();
while(voltage >= 300 && voltage <= 380){
digitalWrite(7, HIGH);
delay(10);
voltage = analogRead(A0);
// Serial.println(voltage);
}
digitalWrite(7, LOW);
touchCountA++;
long finalTime = millis();
myFile = SD.open("dat.txt", FILE_WRITE);
myFile.print(touchCountA);
myFile.print(",0,");
myFile.print(touchTime);
myFile.print(",");
myFile.println(finalTime - touchTime);
myFile.close();
Serial.print(touchCountA);
Serial.print(",0,");
Serial.print(touchTime);
Serial.print(",");
Serial.println(finalTime - touchTime);
}
// Full 3.3V read when Lick Spout B
if(voltage >= 666){
long touchTime = millis();
while(voltage >= 666){
digitalWrite(8, HIGH);
delay(10);
voltage = analogRead(A0);
// Serial.println(voltage);
}
digitalWrite(8, LOW);
long finalTime = millis();
touchCountB++;
myFile = SD.open("dat.txt", FILE_WRITE);
myFile.print("0,");
myFile.print(touchCountB);
myFile.print(",");
myFile.print(touchTime);
myFile.print(",");
myFile.println(finalTime - touchTime);
myFile.close();
Serial.print("0,");
Serial.print(touchCountB);
Serial.print(",");
Serial.print(touchTime);
Serial.print(",");
Serial.println(finalTime - touchTime);
}
delay(10);
}