0
0
AutocadHow-ToBeginner · 3 min read

How to Use analogRead in Arduino: Syntax and Example

Use analogRead(pin) in Arduino to read the voltage level on an analog pin as a number between 0 and 1023. This function returns the sensor value which you can use in your program to measure things like light or temperature.
📐

Syntax

The analogRead() function reads the voltage on an analog pin and returns a value from 0 to 1023. The parameter pin is the analog input pin number you want to read from.

  • pin: The analog pin number (e.g., A0, A1, etc.)
  • return value: Integer between 0 (0 volts) and 1023 (5 volts on most boards)
arduino
int sensorValue = analogRead(A0);
💻

Example

This example reads the value from analog pin A0 and prints it to the Serial Monitor every second. It shows how to use analogRead() inside the loop() function.

arduino
void setup() {
  Serial.begin(9600); // Start serial communication
}

void loop() {
  int sensorValue = analogRead(A0); // Read analog input
  Serial.println(sensorValue);     // Print the value
  delay(1000);                     // Wait 1 second
}
Output
512 523 510 ... (values vary depending on sensor input)
⚠️

Common Pitfalls

  • Using a digital pin number instead of an analog pin (e.g., using 0 instead of A0).
  • Not initializing serial communication before printing results.
  • Expecting voltage values directly instead of raw sensor values (0-1023).
  • Forgetting that the analog input range depends on the board's reference voltage (usually 5V or 3.3V).
arduino
/* Wrong: Using digital pin number */
int sensorValue = analogRead(0); // This reads analog pin A0, but can be confusing

/* Right: Use explicit analog pin */
int sensorValue = analogRead(A0);
📊

Quick Reference

Remember these key points when using analogRead():

  • Use A0, A1, etc. for analog pins.
  • Returns a value from 0 to 1023 representing voltage from 0V to 5V (or 3.3V).
  • Call inside loop() to read continuously.
  • Use Serial.begin() before printing values.

Key Takeaways

Use analogRead(pin) to get a value between 0 and 1023 from an analog pin.
Always specify analog pins as A0, A1, etc., not just numbers.
Initialize serial communication with Serial.begin() before printing values.
The returned value maps voltage from 0V to the board's reference voltage (usually 5V).
Read analog values inside the loop() function for continuous updates.