📜  Arduino AnalogRead()(1)

📅  最后修改于: 2023-12-03 14:39:19.629000             🧑  作者: Mango

Arduino AnalogRead()

The analogRead() function in Arduino is used to read analog input values from analog pins. It reads the voltage applied to the pin and converts it into a digital value ranging from 0 to 1023. This function is commonly used to interface with sensors, potentiometers, and other analog devices.

Syntax

The syntax of the analogRead() function is:

int analogRead(uint8_t pin);
  • analogRead() - The function to read analog input.
  • pin - The analog pin number (0 to 5 on most Arduino boards).
Return Value

The analogRead() function returns an integer value which represents the read voltage level. The value ranges from 0 to 1023, where 0 represents 0 volts and 1023 represents the reference voltage (typically 5V on most Arduino boards).

Usage

Here is an example of using the analogRead() function:

int sensorPin = A0; // Analog input pin
int sensorValue = 0; // Variable to store the sensor value

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

void loop() {
  sensorValue = analogRead(sensorPin); // Read the analog input

  Serial.print("Analog Value: ");
  Serial.println(sensorValue); // Print the sensor value

  delay(1000); // Delay for 1 second
}

In this example, we are reading the analog value from pin A0 and storing it in the sensorValue variable. We then print the value to the serial monitor using the Serial.print() and Serial.println() functions. The delay() function is used to pause the program execution for 1 second before the next reading.

Note: The Serial.begin() function is necessary to enable communication with the computer through the serial port. The baud rate should match the baud rate defined in the serial monitor window.

Markdown code block
Here is an example of using the `analogRead()` function:

```arduino
int sensorPin = A0; // Analog input pin
int sensorValue = 0; // Variable to store the sensor value

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

void loop() {
  sensorValue = analogRead(sensorPin); // Read the analog input

  Serial.print("Analog Value: ");
  Serial.println(sensorValue); // Print the sensor value

  delay(1000); // Delay for 1 second
}