In this section, let us take a look at the commonly used in-built C functions that are used for analog I/O. To begin with we will learn how analog input is measured by the Arduino sketch. An Arduino sketch uses the following function to obtain an analog reading from its analog pins:
analogRead(<pin-number>)
For example, if we want to read the analog signal value from analog pin A5, we must use the following function call:
int value; // declare integer variable
value = analogRead(A5); // read analog value
The above function will return an integer value between 0 and 1023, depending upon the voltage value on the pin. The number 0 to 1023 will be proportional to the voltage range of the Arduino Uno board i.e. 0 to 5 volts.
Next we will look at techniques to write analog signals on both analog as well as digital pins. Digital pins that are PWM capable can simulate the behavior of an analog signal, hence the analogWrite() function can be used on a PWM capable digital pins as well. We shall understand the concept of PWM in depth in the chapter on Actuators during Day 5.
For example, by using the following line of code we can send a full strength (100% duty cycle) signal.
analogWrite(5, 255); // 100% duty cycle signal
Sending such a signal ensures that whatever component is being driven by the pin starts running at full speed (motors) or glows at full intensity (LEDs).
Whereas, by using the following line of code we can send a half strength (50% duty cycle) signal.
analogWrite(5, 127); // 50% duty cycle signal
Sending such a signal ensures that whatever component is being driven by the pin starts running at half speed (motors) or glows at half intensity (LEDs).
While, by using the following line of code we can send a zero strength (0% duty cycle) signal.
analogWrite(5, 0); // 0% duty cycle signal
Sending such a signal ensures that whatever component is being driven by the pin stops.
For sending an analog signal via analog pin A5, we will use the following line of code:
analogWrite(A5, 200)
Whereas, for sending an analog signal via digital pin 5, we will use the following line of code:
analogWrite(5, 200)
The signal value can be specified as an integer between 0 and 255. Based on the integer value the pin will send an equivalent PWM signal.