Pin
ESP8266 and ESP32 use Pin in a same way.
#output mode
from machine import Pin #import Pin module
led=Pin(2,Pin.OUT) #Instantiate led,using GPIO2
led.value(0) #let led output low
led.value(1) #let led output high
#input mode
button=Pin(0,Pin.IN)
print(button.value())
Result: on-board LED light blinks.
ADC
ESP8266 and ESP32 use Pin in a same way.
#ADC function
from machine import ADC #import ADC module
#adc=ADC(Pin(36)) #ESP32 instantiate adc,ESP32's GPIO34 GPIO35 GPIO36 GPIO39 support ADC function
#adc=ADC(0) #ESP8266 instantiate adc,ESP8266's GPIO0 support ADC funciton,注意这里只需要传递0即可,not Pin(0)
print(adc.value()) #show adc value
DAC
ESP32 supports double 8 bit DAC, takes GPIO25 and GPIO26.
#DAC function
from machine import DAC #import Pin module,8bit DAC parameter range:0-255,output voltage range:0-3.3V
dac0=DAC(Pin(25))
dac1=DAC(Pin(26))
dac0.write(128) #output 1.75V voltage
dac1.write(64) #output 0.9V voltage
IIC
ESP8266 and ESP32 use Pin in a same way.
#IIC function
from machine import Pin,I2C
i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000)
value=bytearray(2)
value[0]=100
value[1]=200
i2c.scan() #扫描已经连接的i2c设备地址
i2c.writeto(62,value) #向62号地址写入100 200
i2c.writeto_mem(96,33,value)#向96号地址的33号寄存器写入100 200
SPI
ESP8266 and ESP32 use Pin in a same way.
from machine import Pin, SPI
# construct an SPI bus on the given pins
# polarity is the idle state of SCK
# phase=0 means sample on the first edge of SCK, phase=1 means the second
spi = SPI(baudrate=100000, polarity=1, phase=0, sck=Pin(0), mosi=Pin(2), miso=Pin(4))
spi.init(baudrate=200000) # set the baudrate
spi.read(10) # read 10 bytes on MISO
spi.read(10, 0xff) # read 10 bytes while outputing 0xff on MOSI
buf = bytearray(50) # create a buffer
spi.readinto(buf) # read into the given buffer (reads 50 bytes in this case)
spi.readinto(buf, 0xff) # read into the given buffer and output 0xff on MOSI
spi.write(b'12345') # write 5 bytes on MOSI
buf = bytearray(4) # create a buffer
spi.write_readinto(b'1234', buf) # write to MOSI and read from MISO into the buffer
spi.write_readinto(buf, buf) # write buf to MOSI and read MISO back into buf
PWM
ESP8266 and ESP32 use Pin in a same way.
from machine import Pin, PWM
pwm0 = PWM(Pin(0)) # create PWM object from a pin
pwm0.freq() # get current frequency
pwm0.freq(1000) # set frequency
pwm0.duty() # get current duty cycle
pwm0.duty(200) # set duty cycle
pwm0.deinit() # turn off PWM on the pin
pwm2 = PWM(Pin(2), freq=500, duty=512) # create and configure in one go
ESP8266 supports Timer and breathing light. (please refer to Basics of examples.)
Wi-Fi
ESP8266 and ESP32 use Wi-Fi in a same way.
import network
wlan = network.WLAN(network.STA_IF) # create station interface
wlan.active(True) # activate the interface
wlan.scan() # scan for access points
wlan.isconnected() # check if the station is connected to an AP
wlan.connect('yourSSID', 'password') # connect to an AP
wlan.ifconfig() # get the interface's IP/netmask/gw/DNS addresses