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

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.

主站蜘蛛池模板: 固原市| 凯里市| 彭水| 吉首市| 驻马店市| 长沙市| 木兰县| 晋城| 贞丰县| 四会市| 永定县| 定西市| 乐业县| 祁门县| 望都县| 信宜市| 合作市| 惠州市| 汉中市| 泗洪县| 文成县| 蒙阴县| 墨江| 九江县| 周至县| 张家港市| 桃源县| 尉犁县| 西乌珠穆沁旗| 山丹县| 民丰县| 堆龙德庆县| 崇文区| 铜山县| 莱西市| 奎屯市| 当雄县| 叙永县| 永德县| 博乐市| 新乡市|