Reading analog signals
The ESP8266 has one analog pin that we can use to read analog signals. In this recipe, we will be looking at how to write a sketch that reads analog signals. This will enable us to read input from analog sensors.
Getting ready
Connect your ESP8266 board to your computer via a USB cable and set up your Arduino IDE (refer back to Chapter 1, Configuring the ESP8266). Once that is done, you can proceed to make the other connections.
In this recipe, we will need a breadboard and jumper wires in addition to the ESP8266 board. Mount the ESP8266 board onto the breadboard and then connect a jumper wire from the analog ADC pin to the GND pin. The connection should be as shown in the following diagram:
How to do it…
We will use the analogRead()
function to read the analog signal on the ADC pin and display the analog signal value on the serial monitor. This will be repeated every 1 second:
// LED pin int val = 0; void setup() { Serial.begin(9600); } void loop() { // read pin val = analogRead(A0); // display state of input pin Serial.println(val); delay(1000); }
- Copy the sketch and paste it in your Arduino IDE.
- Check to ensure that the ESP8266 board is connected.
- Select the board that you are using in Tools | menu (in this case it is the Adafruit HUZZAH ESP8266).
- Select the serial port your board is connected to from the Tools | Port menu and then upload the code.
When you open your serial monitor, you will notice that a zero is displayed every second.
How it works…
The program initializes a variable (val
) that will hold the value of the read analog signal. The serial communication baud rate is set at 9600 in the setup section of the sketch. In the loop section, the program reads the analog input on the ADC pin and stores the value in the val
variable, then displays the value stored in the val
variable on the serial monitor at 1 second intervals.
See also
Since you have mastered how to read digital and analog signals using the ESP8266, go the next chapter and learn how to control outputs with the ESP8266.