Introduction:
Today, let’s learn how to use Arduino serial communication and analog ports. We have introduced serial ports before. It can measure voltage 0-5V, and return corresponding 0-1023 value. Today, we will use Arduino analog to make a 0-5V voltmeter.
Note: in this experiment, there is no complex protective circuit. So please do not use more than 2 cells of AA batteries whose voltage must be 0~5V. Besides, do not use it to measure lithium battery or other power supply!
Hardware Required:
- Arduino Board *1
- USB Cable *1
- 1KΩ Resistor *1
- Breadboard *1
- Breadboard Jumper Wire*4
Connection for REV4:
Connection for Arduino Mega 2560 R3:
Sample Code:
float temp; // create a floating-point type variable temp as storage space for storing data void setup() { Serial.begin(9600); // use 9600 baud rate to have serial communication } void loop() { int V1 = analogRead(A0); // Read the voltage data from A0 port and store it in the newly created integer variables V1; measurement range of voltage from analog port is 0 to 5V; return value of 0-1023. float vol = V1*(5.0 / 1024.0); // We convert V1 value into actual voltage value and store it into floating-point variable vol if (vol == temp) // The judgment here is used to filter repeated data; only voltage value that is differ than the last one will be output. { temp = vol; // After comparison is completed, store the value in variable temp } else { Serial.print(vol); // Serial port outputs voltage value, in the same line Serial.println(" V"); // Serial port outputs character V, and begin a new line temp = vol; delay(1000); // Wait 1 second after the output is complete for controlling the data refresh rate. } }
Result:
Click and open the serial port monitor; use the red line to measure battery positive pole, black line for negative pole. Serial monitor will refresh the voltage at 1 time/second. It is normal if there is fluctuation between two voltage values because it is, after all, a low accuracy test.