Digital signals are in the form of 0’s and 1’s, and the ESP8266 has 17 GPIO pins but we can only use only 11 of them because the rest are connected to FLASH and cannot be used. Still wondering why? then please read the Getting Started with ESP8266 WiFi Transceiver
Introduction
In our everyday life we turn ON and OFF numerous devices. Generally if we had to count it would be a big number ranging from 900~2000. Just count the number of times you have turned ON your phone screen and then turned it OFF.
Digital signals have 2 states : ON and OFF. These two states are going to be used on our ESP8266. So we are going to take digital input from a push button and give digital output from a LED as we start off with the ESP8266 NodeMCU.
Working Principle of the OUTPUT and INPUT pins
You will have to set a GPIO pin to INPUT for the switch and another GPIO pin to OUTPUT for the LED. Remember that we are going to use the Arduino IDE.
pinMode(GPIO,INPUT);
digitalRead(GPIO);
pinMode( ) : this function assigns the pin as INPUT or OUTPUT for the ESP8266.
digitalRead( ) : this function read the GPIO pin state, whether it HIGH or LOW.
pinMode(GPIO,OUTPUT);
digitalWrite(GPIO,STATE);
pinMode( ) : this function assigns the pin as INPUT or OUTPUT for the ESP8266.
digitalWrite( ) : this functions allow to set the STATE of the pin : HIGH or LOW.
ESP8266 – Input and Output Project
To demonstrate the use of input and output on the ESP8266. We are going to turn on a LED when we press a pushbutton.
Components required
- ESP8266
- LED x 1
- Pushbutton x 1
- 220Ω Resistor x 1
- 10kΩ Resistor x 1
- Breadboard
- Jumper Wires
Circuit Diagram
We are going to connect the circuit and then upload the code. In most cases when you master the ESP8266, the best practice would be connecting the circuit after uploading the code. (unless you are working on development purposes)
Code
/*Read more at electronicssimpliifed.in
This programs illustrates the use of digital input and output using the NodeMCU ESP8266*/
// Define Pin Numbers for Connections
const int pushButton = 4; // pushbutton pin
const int ledPin = 5; // LED pin
int buttonState = 0; // The status of the pushbutton will be store in button state : HIGH or LOW
void setup() {
pinMode(pushButton, INPUT); // initialize the pushbutton pin as an input
pinMode(ledPin, OUTPUT); // initialize the LED pin as an output
Serial.begin(115200);
}
void loop() {
buttonState = digitalRead(pushButton); // read the state of the pushbutton value and check the value (HIGH or LOW)
// if it is, the buttonState is HIGH
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH); // turn LED on
Serial.println("LED is ON");
} else {
digitalWrite(ledPin, LOW); // turn LED off
Serial.println("LED is OFF")
}
}
Conclusion
The LED will be turned ON when you press the push Button. You can control can control many devices with this logic.