Wednesday, May 10, 2017

Control GPIO (external IO pins) of NodeMCU (ESP8266) with ESP8266 core for Arduino


With ESP8266 core for Arduino, we can load and run the build-in basic example of "Blink" on NodeMCU to toggle the on board LED. We can also employ the same methods to control other io pin, or GPIO.



Connection:



There are many version of ESP8266, the printed mark on PCB may not the io number of ESP8266 MCU, you have to check it for your board. This example run on NodeMCU with marking and CPU pin assignment:
NodeMCU IO index vs ESP8266 pin
IO index  ESP8266 pin
    0     [*] GPIO16  
    1     GPIO5 
    2     GPIO4 
    3     GPIO0 
    4     GPIO2 
    5     GPIO14  
    6     GPIO12
    7     GPIO13
    8     GPIO15
    9     GPIO3
    10    GPIO1
    11    GPIO9
    12    GPIO10
[*] D0(GPIO16) can only be used as gpio read/write. 
No support for open-drain/interrupt/pwm/i2c/ow.
https://nodemcu.readthedocs.io/en/master/en/modules/gpio/

If you run on NodeMCU and select board of NodeMCU 1.0, you can use D1~D10 to access the pins. Refer to pins_arduino.h. Both D1 and 5 refer to the same pin.



If you run on other module, and select other board, may be the compile will report error of  'D1' was not declared in this scope. You have to specify the io# of the MCU, 5 in this case.


NodeMCU_Blink.ino
/*
NodeMCU IO index vs ESP8266 pin
IO index  ESP8266 pin
    0     [*] GPIO16  
    1     GPIO5 
    2     GPIO4 
    3     GPIO0 
    4     GPIO2 
    5     GPIO14  
    6     GPIO12
    7     GPIO13
    8     GPIO15
    9     GPIO3
    10    GPIO1
    11    GPIO9
    12    GPIO10
[*] D0(GPIO16) can only be used as gpio read/write. 
No support for open-drain/interrupt/pwm/i2c/ow.
https://nodemcu.readthedocs.io/en/master/en/modules/gpio/
 */

/*
 * For NodeMCU (8266) both D1 and 5 refer to the same pin
 * For others, such as "Generic ESP8266 Module", it will
 * report error of: 'D1' was not declared in this scope.
 */
const int io5 = 5;

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pins as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  //pinMode(D1, OUTPUT);
  pinMode(io5, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  //digitalWrite(D1, HIGH);
  digitalWrite(io5, HIGH);
  delay(500);
  //digitalWrite(D1, LOW);
  digitalWrite(io5, LOW);
  delay(500);
  digitalWrite(LED_BUILTIN, LOW);
  //digitalWrite(D1, HIGH);
  digitalWrite(io5, HIGH);
  delay(500);
  //digitalWrite(D1, LOW);
  digitalWrite(io5, LOW);
  delay(500);
}

Next:
Control GPIOs of NodeMCU (ESP8266) with ESP8266 core for Arduino, to read Buttons and write LEDs

No comments:

Post a Comment