I am trying to use my arduino as an ammeter to measure current over time and output using Serial.print() by measuring voltage across a resistor and using ohms law. I have a simple circuit consisting of a battery pack, small electric motor, and 3 ohm resistor (technically a rheostat set to lowest setting), all connected in series. I also have the arduino measuring voltage across the resistor with the A2 and A3 pins. It works perfectly well, ticking once per second and outputting a voltage of 0 when the battery pack is disconnected from everything else, but as soon as I connect it, it outputs once to 3 times more and then just stops. I know the code is still looping because the light still flickers once per second, but the serial seems to be broken. If I disconnect the battery after that it still does not output, but when I close the serial output window and open it again it starts again. What really confuses me is that it seems to need to be connected for a certain amount of time to break as just connecting then disconnecting quickly has no effect but holding the connection for a few seconds breaks it. My code is below. Please help!
A picture of the circuit: currently disconnected at the negative terminal of the battery (ignore the multimeter probes)
const float resolution = 5.0/1023;
const int resistance = 3;
double current[5];
int i = 0;
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(A2, INPUT);
pinMode(A3, INPUT);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
digitalWrite(LED_BUILTIN, LOW);
int time1 = millis();
double V1 = analogRead(A2);
double V2 = analogRead(A3);
double voltage = V2-V1;
voltage *= resolution;
current[i] = voltage/resistance;
int time2 = millis();
Serial.print("tick ");
while (time2-time1 < 1000)
{
time2 = millis();
}
i++;
if (i == 5)
{
i = 0;
double currentAverage = (current[0] + current[1] + current[2] + current[3] + current[4]) / 5;
Serial.print(currentAverage);
Serial.print("\n");
}
}
