In addition to digital input/output, Arduino boards also have analog input/output capabilities that allow them to interface with analog sensors and actuators. Here's an overview of how to use analog input/output with Arduino: 1. Analog input: Analog input pins on Arduino boards can be used to read the voltage level of analog sensors such as temperature, light, and sound sensors. To use an analog input pin, you first need to set it as an input using the pinMode() function. You can then read the voltage level using the analogRead() function, which returns a value between 0 and 1023 that corresponds to a voltage range of 0 to 5 volts. Here's an example code to read the voltage level of a potentiometer connected to an analog input pin:
int potPin = A0;
int ledPin = 9;
void setup() {
pinMode(potPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
int potValue = analogRead(potPin);
int brightness = map(potValue, 0, 1023, 0, 255);
analogWrite(ledPin, brightness);
}
2. Analog output: Analog output on Arduino boards is achieved using Pulse-Width Modulation (PWM), which allows you to simulate an analog voltage level by rapidly switching a digital signal on and off. Arduino boards have several pins that can be used for PWM output, indicated by the tilde symbol (
) next to the pin number. To use PWM output, you first need to set the pin as an output using the pinMode() function. You can then write an analog value to the pin using the analogWrite() function, which takes a value between 0 and 255.
Here’s an example code to control the brightness of an LED using PWM output:
int ledPin = 9; void setup() { pinMode(ledPin, OUTPUT); } void loop() { for (int brightness = 0; brightness <= 255; brightness++) { analogWrite(ledPin, brightness); delay(10); } for (int brightness = 255; brightness >= 0; brightness--) { analogWrite(ledPin, brightness); delay(10); } }
Overall, analog input/output is an important aspect of using Arduino boards, and enables a wide range of applications that involve interfacing with analog sensors and actuators.