官术网_书友最值得收藏!

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);             
}
  1. Copy the sketch and paste it in your Arduino IDE.
  2. Check to ensure that the ESP8266 board is connected.
  3. Select the board that you are using in Tools | menu (in this case it is the Adafruit HUZZAH ESP8266).
  4. 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.

主站蜘蛛池模板: 新余市| 米泉市| 鄂伦春自治旗| 蓬安县| 吴忠市| 沧州市| 太仓市| 农安县| 防城港市| 姜堰市| 庆云县| 灵石县| 汉沽区| 安龙县| 巫山县| 郓城县| 鹤岗市| 建瓯市| 贡嘎县| 汝阳县| 华坪县| 调兵山市| 正安县| 安泽县| 通许县| 枣强县| 彭山县| 特克斯县| 昌宁县| 金秀| 朝阳市| 邵武市| 合山市| 体育| 锦州市| 西乌珠穆沁旗| 泌阳县| 大洼县| 东海县| 利津县| 富源县|