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

Reading digital signals

One of the uses of the ESP8266's GPIO pins is to read digital signals. This allows you to control your project using input devices and also to monitor sensor data. In this recipe, we will look at how to read digital signals using GPIO pins.

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 few extra components. They include:

  • Breadboard
  • Jumper wires

Mount the ESP8266 board onto the breadboard and then connect a jumper wire from pin 5 to the GND pin. The connection should be as shown in the following figure:

How to do it…

We will configure pin 5 as an input, then read it using the digitalRead() function and display the state of the input signal on the serial monitor. This will be repeated every 1 second:

// LED pin
int inputPin = 5;
int val = 0;

void setup() {
  Serial.begin(9600);
  pinMode(inputPin, INPUT);
}

void loop() {
  
  // read pin
  val = digitalRead(inputPin);
 
  // display state of input pin  
  Serial.println(val);                              
  delay(1000);             
}

Refer the following steps:

  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 | Board 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, a zero will be displayed after one second and another after two seconds, and so on and so forth.

How it works…

The program initializes two variables at the beginning. The first variable (inputPin) is the GPIO pin number and the second variable (val) will hold the state of the GPIO pin. The serial communication baud rate is set at 9600 and GPIO 5 is configured as an input pin in the setup section of the sketch. In the loop section, the program reads the digital input on pin 5 and stores the value in the val variable, then displays the value stored in the val variable on the serial monitor. There is a delay of 1 second after that.

There's more…

If you have successfully completed that exercise, you can spice things up by connecting GPIO 5 to the 3.3V pin instead of the GND pin, then checking the serial monitor. You should see 1s listed on the serial monitor instead of 0s, since the input signal on pin 5 is high.

See also

Having successfully learned how to read digital signals, you can now proceed to the next recipe, where we will advance to Reading analog signals.

主站蜘蛛池模板: 久治县| 奉节县| 呼和浩特市| 曲阜市| 嘉义县| 清远市| 赞皇县| 吉隆县| 普宁市| 连江县| 三都| 夏河县| 保德县| 沾益县| 保德县| 鹰潭市| 南涧| 巨野县| 永登县| 双辽市| 瑞金市| 浑源县| 英德市| 吉隆县| 甘德县| 昌平区| 曲阳县| 东阳市| 建湖县| 五指山市| 精河县| 仪陇县| 浪卡子县| 田阳县| 尼勒克县| 襄垣县| 新沂市| 昌邑市| 新蔡县| 获嘉县| 桐乡市|