GPIOs as input or output.

Code tips and tricks for beginners
Post Reply
User avatar
Fernando Perez
Posts: 378
Joined: Mon Feb 15, 2021 10:09 pm
Location: Santander (Spain)
Has thanked: 195 times
Been thanked: 267 times

GPIOs as input or output.

Post by Fernando Perez »

Small subroutine to establish the ESP8266 GPIOs as inputs or outputs in a single line.
It will also work in the first 32 GPIOs of an ESP32 since GPIOs 6 to 11 are not available in this microcontroller either.

Code: [Local Link Removed for Guests]

' ========================
' DECLARE SUB port(config)
' ========================
' Sets the ESP8266 GPIO as input or output: 1=output, 0=input
' most significant bit is GPIO16 (MSb); GPIO0 is LSb
' GPIO6 to GPIO11 are reserved, and therefore omitted in the config value.

port &B11111001111 ' GPIO 4 and 5 INPUT; rest OUTPUT


' -----------------------------
SUB port(config)
LOCAL gpio
  config =((config\64)*4032) + config  ' Insert zeros for GPIO 6 to 11
  for gpio = 0 to 16
    if (gpio<6) OR (gpio>11) then  ' skipping GPIO reserved
      if (config and (1 << gpio)) <> 0 then pin.mode gpio,output else pin.mode gpio,input ' [,pullup]
  next gpio 
Post Reply