The analogue inputs and outputs are used when the signal can take a range of values, unlike the digital signal that takes only two values (HIGH or LOW).
For measuring the analogue signal, microcontrollers have built-in analogue-to-digital converter (ADC) that returns the digital value of the voltage level. Usually, the binary number corresponds to the input voltage, not the value in Volts. The number of bits of the output value depends on the accuracy and internal construction of the converter and usually varies between 8 and 12.
analogRead()
The function analogRead() is used for analogue pins (A0, A1, A2, etc.) and reads the value on the analogue pin.
The syntax of a function is the following:
analogRead(pin);
The parameter pin is the pin's name whose value is read.
The return type of the function is the integer value. On the Arduino Uno boards, it ranges between 0 and 1023. The reading of each analogue input takes around 100 ms.
Unlike analogue input, the analogue output does not generate varying voltage directly on the pin. In general, it uses the technique known as (Pulse Width Modulation (PWM)) that generates a high/low square signal of stable frequency but varying duty cycle (ratio of active and passive periods of the signal). Details are described later in the book. Because the PMW signal can provide different average power to the external element, e.g. LED, it can be considered analogue output.
analogWrite()
The function analogWrite() is used to write an analogue value of the integer type as an output of the pin. An example of use is turning on/off the LED with various brightness levels or setting different speeds of the motors. The value written to the pin stays unchanged until the next value is written to the pin.
The syntax of a function is the following:
analogWrite(pin, value);
The parameter pin is the number of the pin.
The parameter value is the PWM signal value that can differ from 0 (off) to 255 (100% on).
This function does not have the return type.
The following example shows reading an analogue value from the A0 input of an Arduino Uno board and writing the analogue value to the output that can control the intensity of the LED.
#define LED_pin 3 //the pin number is chosen to support PWM generation void setup() { pinMode(LED_pin, OUTPUT); } int value; //variable that holds the result of analogue reading void loop() { value = analogRead(A0); //analogRead on Arduino Uno returns the value 0-1023 value = value >> 2; //it should be converted to the value 0-255 analogWrite(LED_pin, value); //writing converted value to PWM output }