Programming the ESP32 in MicroPython
Second Edition
We have decided not to make the programs available as a download because this is not the point of the book - the programs are not finished production code but something you should type in and study.
The best solution is to provide the source code of the programs in a form that can be copied and pasted into Thonny or Pycharm project.
The only downside is that you have to create a project to paste the code into.
To do this follow the instructions in the book.
All of the programs below were copy and pasted from working programs in the IDE. They have been formatted using the built in formatter and hence are not identical in layout to the programs in the book. This is to make copy and pasting them easier. The programs in the book are formatted to be easy to read on the page.
If anything you consider important is missing or if you have any requests or comments contact:
This email address is being protected from spambots. You need JavaScript enabled to view it.
Page 46
from machine import Pin
import time
pin = Pin(2, Pin.OUT)
while True:
pin.value(1)
time.sleep(1)
pin.value(0)
time.sleep(1)
Page 48
from machine import Pin
import time
def toggle(pin):
temp = pin.value()
temp = not temp
pin.value(temp)
pin = Pin(2,Pin.OUT)
while True:
toggle(pin)
time.sleep(1)
Page 50
from machine import Pin
pin = Pin(2, Pin.OUT)
while True:
pin.value(1)
pin.value(0)
Page 51
from machine import Pin
def flash():
pin = Pin(2, Pin.OUT)
while True:
pin.value(1)
pin.value(0)
flash()
Page 51
from machine import Pin
@micropython.native
def flash():
pin = Pin(2, Pin.OUT)
while True:
pin.value(1)
pin.value(0)
flash()
Page 52
from machine import Pin
import time
pin = Pin(2, Pin.OUT)
while True:
pin.value(1)
time.sleep(0.5)
pin.value(0)
time.sleep(0.5)
Page 53
from machine import Pin
import time
pin = Pin(2, Pin.OUT)
while True:
pin.value(1)
time.sleep_us(10)
pin.value(0)
time.sleep_us(10)
Page 53
from machine import Pin
import time
pin = Pin(2, Pin.OUT)
n = 10
while True:
for i in range(n):
pass
pin.value(1)
for i in range(n):
pass
pin.value(0)
Page 54
from machine import Pin
import time
pin = Pin(2, Pin.OUT)
n = 5
while True:
t = time.ticks_add(time.ticks_us(), 1000)
pin.value(1)
for i in range(n):
pass
while time.ticks_us() < t:
pass
pin.value(0)
Page 56
import time
from time import sleep
import esp32
from machine import Pin
import machine
pin = Pin(2,Pin.OUT,value=0)
buf = bytearray(b"\x55\x55")
print(buf)
machine.bitstream(pin,0,(80,90,100,110),buf)
Page 58
import esp32
from machine import Pin
import machine
pin=Pin(2,Pin.OUT,value=0)
rmt=esp32.RMT(0,pin=pin)
rmt.write_pulses((1000,400,200,300,200,300),1)
Page 59
from machine import Pin
pin1 = Pin(2, Pin.OUT)
pin2 = Pin(4, Pin.OUT)
while True:
pin1.value(1)
pin2.value(0)
pin1.value(0)
pin2.value(1)
Page 61
The address used in machine.mem32 is for the ESP32 for the ESP32 S3 and Nano ESP32 change this to 0x60004004.
from machine import Pin
import machine
def gpio_set(value, mask):
machine.mem32[0x3FF44004] = machine.mem32[0x3FF44004] & ~mask | value & mask
pin = Pin(2, Pin.OUT)
pin = Pin(4, Pin.OUT)
value1 = 1 << 2 | 0 << 4
value2 = 0 << 2 | 1 << 4
mask = 1 << 2 | 1 << 4
while True:
gpio_set(value1, mask)
gpio_set(value2, mask)
Page 87
from machine import Pin
import time
pinIn = Pin(4, Pin.IN,Pin.PULL_UP)
pinLED = Pin(2, Pin.OUT)
while True:
if pinIn.value():
pinLED.on()
else:
pinLED.off()
time.sleep(0.5)
Page 88
from machine import Pin
import time
pinIn = Pin(4, Pin.IN,Pin.PULL_DOWN)
pinLED = Pin(2, Pin.OUT)
while True:
while pinIn.value()==0:
pass
while pinIn.value()==1:
pass
pinLED.on()
time.sleep_ms(1)
pinLED.off()
Page 89
from machine import Pin
import time
pinIn = Pin(4, Pin.IN,Pin.PULL_DOWN)
pinLED = Pin(2, Pin.OUT)
while True:
while pinIn.value() == 0:
pass
t = time.ticks_ms()
time.sleep_ms(1)
while pinIn.value() == 1:
pass
t = time.ticks_diff(time.ticks_ms(),t)
if t<2000:
pinLED.on()
time.sleep(1)
pinLED.off()
else:
for i in range(10):
pinLED.on()
time.sleep_ms(100)
pinLED.off()
time.sleep_ms(100)
Page 90
from machine import Pin
import time
pinIn = Pin(4, Pin.IN)
while True:
while pinIn.value()==1:
pass
while pinIn.value()==0:
pass
t=time.ticks_us()
while pinIn.value()==1:
pass
t=time.ticks_diff(time.ticks_us(),t)
print(t)
time.sleep(1)
Page 91
import time
import machine
pinIn = machine.Pin(4, machine.Pin.IN)
while True:
t = machine.time_pulse_us(pinIn, 1)
print(t)
time.sleep(1)
Page 91
import time
import machine
pinIn = machine.Pin(4, machine.Pin.IN)
while True:
while pinIn.value() == 1:
pass
t = machine.time_pulse_us(pinIn, 1)
print(t)
time.sleep(1)
Page 94
from machine import Pin
import time
pinIn = Pin(4, Pin.IN)
s = 0
count = 0
while True:
I = pinIn.value()
t = time.ticks_add(time.ticks_us(),1000*100)
if s == 0: #button not pushed
if i:
s = 1
count=count+1
print("Button Push ",count)
elif s == 1: #button pushed
if not i:
s = 0
else:
s = 0
while time.ticks_us()<t:
pass
Page 96
from machine import Pin
import time
pinIn = Pin(4, Pin.IN)
s = 0
while True:
I = pinIn.value()
t = time.ticks_add(time.ticks_us(),1000*100)
if s == 0: #button not pushed
if i:
s = 1
tpush = t
elif s == 1: #button pushed
if not i:
s = 0
if time.ticks_diff(t, tpush) > 2000000:
print("Button held \n\r")
else:
print("Button pushed \n\r")
else:
s = 0
while time.ticks_us()<t:
pass
Page 97
from machine import Pin
import time
pinIn = Pin(4, Pin.IN)
pinLED1 = Pin(1, Pin.OUT)
pinLED2 = Pin(2, Pin.OUT)
pinLED3 = Pin(3, Pin.OUT)
pinLED1.on()
pinLED2.off()
pinLED3.off()
s = 0
buttonState = pinIn.value()
while True:
buttonNow = pinIn.value()
edge = buttonState-buttonNow
buttonState = buttonNow
t = time.ticks_add(time.ticks_us(), 1000*100)
if s == 0:
if edge == 1:
s = 1
pinLED1.off()
pinLED2.on()
pinLED3.off()
elif s == 1:
if edge == 1:
s = 2
pinLED1.off()
pinLED2.off()
pinLED3.on()
elif s == 2:
if edge == 1:
s = 0
pinLED1.on()
pinLED2.off()
pinLED3.off()
else:
s = 0
while time.ticks_us() < t:
pass
from machine import Pin
def HelloIRQ1(pin):
print("IRQ1")
def HelloIRQ2(pin):
print("IRQ2")
pin1=Pin(4,Pin.IN,Pin.PULL_DOWN)
pin2=Pin(5,Pin.IN,Pin.PULL_DOWN)
pin1.irq(HelloIRQ1,Pin.IRQ_RISING)
pin2.irq(HelloIRQ2,Pin.IRQ_RISING)
Page 105
import time
from machine import Pin
t = 0
def myHandler(pin):
global t
temp = time.ticks_us()
print(time.ticks_diff(temp,t))
t = temp
time.sleep(1.5)
return
pin = Pin(4, Pin.IN, Pin.PULL_DOWN)
pin.irq(myHandler, Pin.IRQ_FALLING)
Page 105
import time
from machine import Pin
t = 0
def myHandler(pin):
global t
pin.irq(None, Pin.IRQ_FALLING)
temp = time.ticks_us()
print(time.ticks_diff(temp,t))
t = temp
time.sleep(1.5)
pin.irq(myHandler, Pin.IRQ_FALLING)
return
pin = Pin(4, Pin.IN, Pin.PULL_DOWN)
pin.irq(myHandler, Pin.IRQ_FALLING)
Page 108
import time
from machine import Pin
data = bytearray(b'\xf0\xf1\xf2')
def myHandler(pin):
global data
for i in range(3):
data[i]=0
pin = Pin(4, Pin.IN, Pin.PULL_DOWN)
pin.irq(myHandler, Pin.IRQ_RISING)
while True:
for i in range(3):
data[i] = 255
if data[0]!=data[1] or data[1]!=data[2] or data[2]!=data[0]:
print(data)
Page 109
from machine import Pin
data=bytearray(b'\xf0\xf1\xf2')
def myHandler(pin):
global data
for i in range(3):
data[i] = 0
print(data)
pin = Pin(4, Pin.IN, Pin.PULL_DOWN)
pin.irq(myHandler, Pin.IRQ_RISING)
while True:
pin.irq(None, Pin.IRQ_RISING)
for i in range(3):
data[i] = 255
if data[0]!=data[1] or data[1]!=data[2] or data[2]!=data[0]:
print(data)
pin.irq(myHandler, Pin.IRQ_RISING)
Page 110
import time
from time import sleep
from machine import Pin
pin=Pin(4,Pin.IN,Pin.PULL_DOWN)
event=0
def rise(pin):
global event
event=1
def fall(pin):
global event
event=2
while True:
pin.irq(rise, Pin.IRQ_RISING)
while not(event==1):
pass
t=time.ticks_us()
pin.irq(fall, Pin.IRQ_FALLING)
while not(event==2):
pass
t=time.ticks_diff(time.ticks_us(),t)
print(t)
sleep(1)
Page 116
from machine import Pin, PWM
pwm1 = PWM(Pin(4),freq=250)
pwm2 = PWM(Pin(2),freq=250)
pwm1.duty_u16(65535//2)
pwm2.duty_u16(65535//4)
Page 117
import time
from machine import Pin, PWM
pwm1 = PWM(Pin(4),freq = 50)
while True:
pwm1.duty_u16(65535//2)
time.sleep_ms(19)
pwm1.duty_u16(65535//4)
time.sleep_ms(19)
Page 118
import esp32
from machine import Pin
import machine
pin=Pin(4,Pin.OUT,value=0)
rmt=esp32.RMT(0,pin=pin)
t=20000000 # pulse repetition in us
d=[10,20,30,40,50] #duty cycles in percent
times=[]
for p in d:
times.append(int(t*p/100))
times.append(int((t*(100-p)/100)))
rmt.loop(True)
rmt.write_pulses(times,1)
Page 119
import time
from machine import Pin, PWM
pwm1 = PWM(Pin(4),freq = 20000000)
pwm1.duty_u16(65535//4*2 +2)
Page 121
from machine import Pin, PWM
import array
import math
wave = array.array('H', [0]*256)
for i in range(256):
wave[i] = int(65535//2 + (math.sin(i * 2.0 * 3.14159 / 256.0) * 65535//2))
pwm1 = PWM(Pin(4),freq=300000)
print(pwm1)
while(True):
for i in range(256):
pwm1.duty_u16(wave[i])
print(pwm_get_wrap(0))
while(True):
for i in range(256):
pwm16.duty_u16(wave[i])
Page 123
from machine import Pin, PWM
from time import sleep_ms
pwm1 = PWM(Pin(4),freq=2000)
while True:
for d in range(0,65535,655):
pwm1.duty_u16(d)
sleep_ms(50)
Page 124
from utime import sleep_ms
from machine import Pin, PWM
pwm1 = PWM(Pin(4),freq=2000)
while True:
for b in range(0,100):
pwm1.duty_u16(int(65535*b*b*b/1000000))
sleep_ms(50)
Page 135
from machine import Pin, PWM
from time import sleep
class Motor:
def __init__(self, pinNo):
self.pwm1 = PWM(Pin(pinNo), freq=2000, duty_u16=0)
self.gpio = pinNo
self._on = False
self.speed=0
def setSpeed(self,s):
self._on=True
self.speed=s
self.pwm1.duty_u16(int(65535*s/100))
def off(self):
self._on=False
self.pwm1.duty_u16(0)
def on(self):
self._on=True
self.pwm1.duty_u16(int(65535*self.speed/100))
motor=Motor(4)
sleep(1)
motor.setSpeed(50)
sleep(1)
motor.off()
sleep(1)
motor.setSpeed(90)
sleep(1)
motor.off()
Page 139
from machine import Pin, PWM
from time import sleep
class Motor:
def __init__(self, pinNo):
self.pwm1 = PWM(Pin(pinNo), freq=2000, duty_u16=0)
self.gpio = pinNo
self._on = False
self.speed=0
def setSpeed(self,s):
self._on=True
self.speed=s
self.pwm1.duty_u16(int(65535*s/100))
def off(self):
self._on=False
self.pwm1.duty_u16(0)
def on(self):
self._on=True
self.pwm1.duty_u16(int(65535*self.speed/100))
class BiMotor(Motor):
def __init__(self, pinNo1,pinNo2):
super().__init__(pinNo1)
self.forward = True
self.pwm2 = PWM(Pin(pinNo2),freq=2000,duty_u16=0)
def setForward(self, forward):
if self.forward == forward:
return
self.pwm1.duty_u16(0)
self.pwm1, self.pwm2 = self.pwm2, self.pwm1
self.forward = forward
self.pwm1.duty_u16(int(65535 * self.speed / 100))
motor = BiMotor(2,4)
sleep(1)
motor.setSpeed(50)
sleep(1)
motor.setForward(False)
sleep(1)
motor.setSpeed(90)
sleep(1)
motor.setForward(True)
motor.off()
Page 143
from machine import Pin, PWM
from time import sleep
class Servo:
def __init__(self, pinNo):
self.pwm = PWM(Pin(pinNo),freq=50,duty_u16= int(65535*2.5/100))
def setPosition(self, p):
self.position = p
self.pwm.duty_u16(int(65535*p/1000 + 65535*2.5/100))
def off(self):
self.pwm.deinit()
servo=Servo(4)
sleep(1)
servo.setPosition(100.0)
sleep(1)
servo.setPosition(50.0)
sleep(1)
servo.setPosition(0)
sleep(1)
servo.off()
Page 150
from machine import Pin, mem32
from time import sleep_ms
class StepperBi4():
def __init__(self, pinA):
self.phase = 0
self.pinA = pinA
self.gpios = tuple([Pin(pinA, Pin.OUT),
Pin(pinA + 1, Pin.OUT),
Pin(pinA + 2, Pin.OUT),
Pin(pinA + 3, Pin.OUT)])
self.gpios[0].on()
self.gpioMask = 0xF << self.pinA
self.halfstepSeq = [0x1, 0x5, 0x4, 0x6, 0x2, 0xA, 0x8, 0x9]
# [ B- B -A A
# [0, 0, 0, 1],
# [0, 1, 0, 1],
# [0, 1, 0, 0],
# [0, 1, 1, 0],
# [0, 0, 1, 0],
# [1, 0, 1, 0],
# [1, 0, 0, 0],
# [1, 0, 0, 1]
# ]
# change 0x3FF44004 to 0x60004004 for an S3
def _gpio_set(self,value, mask):
mem32[0x3FF44004] = mem32[0x3FF44004] & ~mask |
value & mask
def setPhase(self, phase):
value = self.halfstepSeq[phase] << self.pinA
self._gpio_set(value, self.gpioMask)
self.phase = phase
def stepForward(self):
self.phase = (self.phase + 1) % 8
self.setPhase(self.phase)
def stepReverse(self):
self.phase = (self.phase - 1) % 8
self.setPhase(self.phase)
step = StepperBi4(16)
step.setPhase(0)
while True:
step.stepForward()
sleep_ms(1)
Page 154
from machine import Pin, mem32, Timer
from machine import Timer
from time import sleep_ms
class StepperBi4():
def __init__(self, pinA):
self.phase = 0
self.pinA = pinA
self.gpios = tuple([Pin(pinA, Pin.OUT),
Pin(pinA + 1, Pin.OUT),
Pin(pinA + 2, Pin.OUT),
Pin(pinA + 3, Pin.OUT)])
self.gpios[0].on()
self.gpioMask = 0xF << self.pinA
self.halfstepSeq = [0x1, 0x5, 0x4, 0x6, 0x2, 0xA, 0x8, 0x9]
self.forward = True
self.speed = 0
self.timer = None
# [ B- B -A A
# [0, 0, 0, 1],
# [0, 1, 0, 1],
# [0, 1, 0, 0],
# [0, 1, 1, 0],
# [0, 0, 1, 0],
# [1, 0, 1, 0],
# [1, 0, 0, 0],
# [1, 0, 0, 1]
# ]
# change 0x3FF44004 to 0x60004004 for an S3
def _gpio_set(self,value, mask):
mem32[0x3FF44004] = mem32[0x3FF44004] & ~mask | value & mask
def setPhase(self, phase):
value = self.halfstepSeq[phase] << self.pinA
self._gpio_set(value, self.gpioMask)
self.phase = phase
def stepForward(self):
self.phase = (self.phase + 1) % 8
self.setPhase(self.phase)
def stepReverse(self):
self.phase = (self.phase - 1) % 8
self.setPhase(self.phase)
def rotate(self, forward, speed):
self.forward = forward
self.speed = speed
if speed == 0:
self.timer.deinit()
self.timer = None
return
if self.timer == None:
self.timer = Timer(0)
self.timer.init(freq=speed, mode=Timer.PERIODIC,callback=self.doRotate)
def doRotate(self,timer):
if self.forward:
self.stepForward()
else:
self.stepReverse()
step = StepperBi4(16)
step.setPhase(0)
while True:
step.rotate(True,100)
sleep_ms(500)
step.rotate(True,0)
sleep_ms(500)
Page 164
from machine import Pin, SPI
spi=SPI(1,sck=Pin(14),miso=Pin(12),mosi=Pin(13))
spi.init(baudrate=500_000,bits=8, polarity=0,phase=0,firstbit=SPI.MSB )
read = bytearray(3)
write = bytearray([0xAA,0xAA,0xAA])
spi.write_readinto(write,read)
print(read,write)
spi.deinit()
Page 172
from utime import sleep_ms
from machine import Pin, SPI
spi=SPI(1,sck=Pin(14),miso=Pin(12),mosi=Pin(13))
spi.init(baudrate=500_000, bits=8, polarity=0, phase=0,firstbit=SPI.MSB)
CS = Pin(4, Pin.OUT)
CS.on()
sleep_ms(1)
CS.off()
write=bytearray([0x01, 0x80, 0x00])
read=bytearray(3)
spi.write_readinto(write,read)
CS.on()
data = (read[1] & 0x03) << 8 | read[2]
volts = data * 3.3 / 1023.0
print(volts)
spi.deinit()
Page 173
from utime import sleep_ms
from machine import Pin, SPI
class spiADC:
def __init__(self,spi,sckNo,misoNo,mosiNo,CSNo):
self.spi = SPI(spi, sck=Pin(sckNo), miso=Pin(misoNo), mosi=Pin(mosiNo))
self.spi.init(baudrate=500_000, bits=8, polarity=0,phase=0, firstbit=SPI.MSB)
self.CS = Pin(CSNo, Pin.OUT)
self.CS.on()
sleep_ms(1)
def read(self,chan):
write=bytearray([0x01, (0x08 | chan) << 4 , 0x00])
self.CS.off()
read=bytearray(3)
self.spi.write_readinto(write,read)
self.CS.on()
data = (read[1] & 0x03) << 8 | read[2]
volts = data * 3.3 / 1023.0
return volts
adc=spiADC(1,14,12,13,4)
volts=adc.read(1)
print(volts)
Page 180
from machine import ADC,Pin
adc = ADC(Pin(32)) #Use GPIO5 for S3
print(adc.read())
print(adc.read_u16())
print(adc.read_uv()/1000000)
Page 182
from machine import ADC,Pin
import time
adc = ADC(Pin(32),atten=ADC.ATTN_11DB)#change to 5 for the EPS32 S3
t = time.ticks_us()
for i in range(10000):
pass
print(time.ticks_diff(time.ticks_us(), t)/10000)
t = time.ticks_us()
for i in range(10000):
m=adc.read()
print(time.ticks_diff(time.ticks_us(), t)/10000)
t = time.ticks_us()
for i in range(10000):
m=adc.read_u16()
print(time.ticks_diff(time.ticks_us(), t)/10000)
t = time.ticks_us()
for i in range(10000):
m=adc.read_uv()
print(time.ticks_diff(time.ticks_us(), t)/10000)
Page 184 Only works on ESP32
from machine import Pin, DAC
import math
dac1 = DAC(Pin(26))
wave = []
for i in range(0,255):
wave.append(int(127*math.sin(2*math.pi/256*i))+128)
while(True):
for i in range(0,255):
dac1.write(wave[i])
Page 185 Only works on ESP32
from machine import Pin, DAC, mem32
from time import sleep
def _gpio_get(adr):
return mem32[adr]
def _gpio_set( adr,value, mask):
mem32[adr] = mem32[adr] & ~mask | value & mask
def enableSin(chan,f):
if chan<1 or chan>2:
return
setFreq(chan, f)
setPhase(chan,0x2)
#enable tone
_gpio_set(0x3FF48898, 0x10000, 0x10000)
#select channel
if chan==1:
_gpio_set(0x3FF4889c, 1<<24,0x1<<24)
else:
_gpio_set(0x3FF4889c, 1<<25, 0x1 <<25)
#set pad
pad=0x3FF48484+4*(chan-1)
_gpio_set(pad, 0x20200, 0x23A00)
def setFreq(chan,f):
if chan<1 or chan>2:
return
step=int(f*65536/8000000) & 0xFFFF
_gpio_set(0x3FF48898, step, 0x000FF)
def setPhase(chan,p):
_gpio_set(0x3FF4889c, p << (20 + 2 * (chan – 1)),0x03 << (20 + 2 * (chan - 1)))
def setScale(chan,s):
_gpio_set(0x3FF4889c, s << (16 + 2 * (chan – 1)),0x03 << (16 + 2 * (chan - 1)))
def setOff(chan,off):
_gpio_set(0x3FF4889c, off << (8 * (chan – 1)), 0xFF << (8 * (chan - 1)))
dac1 = DAC(Pin(26))
enableSin(2,30000)
setScale(2,0x0)
setOff(2,0x0)
while(True):
sleep(0.001)
setPhase(2,0x3)
sleep(.001)
setPhase(2, 0x2)
Note: If you have problems running any of these programs check the pullup resistors first and the USB power second.
The hardware I2C often works when the software I2C fails because of pullup or USB power problems.
Page 201
from machine import Pin,I2C
i2c0 = I2C(0,scl=Pin(13),sda=Pin(12),freq=100000)
buf = bytearray([0xE7])
i2c0.writeto( 0x40, buf, True)
read= i2c0.readfrom(0x40, 1, True)
print("User Register =",read)
Page 203
from machine import Pin,I2C
i2c0 = I2C(0,scl=Pin(13),sda=Pin(12),freq=100000)
buf = bytearray([0xE3])
i2c0.writeto( 0x40, buf, True)
read = i2c0.readfrom(0x40, 3, True)
msb = read[0]
lsb = read[1]
check = read[2]
print("msb lsb checksum =", msb, lsb, check)
Page 203
from machine import Pin,SoftI2C
i2c0 = SoftI2C(scl=Pin(13),sda=Pin(12),freq=100000)
buf = bytearray([0xE3])
i2c0.writeto( 0x40, buf, False)
read= i2c0.readfrom(0x40, 3, True)
msb = read[0]
lsb = read[1]
check = read[2]
print("msb lsb checksum =", msb, lsb, check)
Page 205
from machine import Pin,I2C
i2c0=I2C(0,scl=Pin(13),sda=Pin(12),freq=100000)
buf = bytearray([0xF3])
i2c0.writeto( 0x40, buf, True)
while True:
try:
read= i2c0.readfrom(0x40, 3, False)
break
except:
continue
msb = read[0]
lsb = read[1]
check = read[2]
print("msb lsb checksum =", msb, lsb, check)
Page 205
from machine import Pin,SoftI2C
from time import sleep_ms
i2c0 = SoftI2C(scl=Pin(18),sda=Pin(19),freq=100000)
buf = bytearray([0xF3])
i2c0.writeto( 0x40, buf, False)
while True:
sleep_ms(5)
try:
read = i2c0.readfrom(0x40, 3, True)
break
except:
continue
msb = read[0]
lsb = read[1]
check = read[2]
print("msb lsb checksum =", msb, lsb, check)
Page 206
from machine import Pin,I2C
def crcCheck(msb, lsb,check):
data32 = (msb << 16)|(lsb <<8)| check
divisor = 0x988000
for i in range(16):
if data32 & 1<<(23 - i):
data32 ^= divisor
divisor>>= 1
return data32
i2c0=I2C(0,scl=Pin(13),sda=Pin(12),freq=100000)
buf = bytearray([0xF3])
i2c0.writeto( 0x40, buf, False)
while True:
try:
read= i2c0.readfrom(0x40, 3, True)
break
except:
continue
msb = read[0]
lsb = read[1]
check = read[2]
print("msb lsb checksum =", msb, lsb, check)
data16= (msb << 8) | (lsb & 0xFC)
temp = (-46.85 +(175.72 * data16 /(1<<16)))
print("Temperature C ", temp)
print("Checksum=",crcCheck(msb,lsb,check))
buf = bytearray([0xF5])
i2c0.writeto( 0x40, buf, True)
read=bytearray(3)
while True:
try:
i2c0.readfrom_into(0x40,read, True)
break
except:
continue
msb = read[0]
lsb = read[1]
check = read[2]
print("msb lsb checksum =", msb, lsb, check)
data16 = (msb << 8) | (lsb & 0xFC)
hum = -6 + (125.0 * data16) / 65536
print("Humidity ", hum)
print("Checksum=",crcCheck(msb,lsb,check))
Page 212
import dht
from machine import Pin
from time import sleep
dht = dht.DHT22(Pin(2))
while True:
dht.measure()
temp = dht.temperature()
print(temp,"C")
hum = dht.humidity()
print(hum,"%")
sleep(1)
Page 217
from machine import Pin
from utime import sleep_ms
DHT = Pin(2,mode=Pin.OUT,value=1)
sleep_ms(1)
DHT.off()
sleep_ms(1)
DHT.init(mode=Pin.IN)
Page 221
from machine import Pin,time_pulse_us
from utime import sleep_ms
class DHT22():
def __init__(self,gpio):
self.pin = Pin(gpio, mode=Pin.IN)
self.checksum = 0
self.temperature = 0
self.humidity=0
sleep_ms(1)
@micropython.native
def getReading(self):
data = 0
checksum = 0
DHT=self.pin
DHT.init(mode=Pin.OUT,value=0)
sleep_ms(1)
DHT.init(mode=Pin.IN)
t = time_pulse_us(DHT, 0, 1000)
t = time_pulse_us(DHT, 1, 1000)
for i in range(32):
t = time_pulse_us(DHT, 1, 1000)
data = data << 1
data = data | (t > 50)
for i in range(8):
t = time_pulse_us(DHT, 1, 1000)
checksum = checksum << 1
checksum = checksum |(t > 50)
byte1 = (data >> 24 & 0xFF)
byte2 = (data >> 16 & 0xFF)
byte3 = (data >> 8 & 0xFF)
byte4 = (data & 0xFF)
self.checksum =(checksum ==(byte1+byte2+byte3+byte4)&0xFF)
self.humidity = ((byte1 <<8)| byte2) / 10.0
neg = byte3 & 0x80
byte3 = byte3 & 0x7F
self.temperature = (byte3 << 8 | byte4) / 10.0
if neg > 0:
self.temperature = -self.temperature
dht = DHT22(2)
dht.getReading()
print("Checksum",dht.checksum)
print("Humidity= ", dht.humidity)
print("Temperature=", dht.temperature)
Page 227
from machine import Pin
import onewire,ds18x20
ow = onewire.OneWire(Pin(2))
presence=ow.reset()
if presence:
print("Device present")
else:
print("No device")
ds = ds18x20.DS18X20(ow)
roms = ds.scan()
t = ds.read_temp(roms[0])
print(t)
Page 234
from machine import Pin
import onewire
class DS18B20:
def __init__(self,pin):
self.ow = onewire.OneWire(Pin(pin))
def __convert(self):
self.ow.write([0xCC,0x44])
for i in range(500):
sleep_ms(10)
if self.ow.readbit() == 1:
j = i
break
return j
def getTemp(self):
if not self.ow.reset:
return -1000
if self.__convert()==500:
return -3000
self.ow.reset()
self.ow.write([0xCC,0xBE])
data = bytearray(9)
self.ow.readinto(data)
if self.ow.crc8(data)!=0:
return -2000
t1 = data[0]
t2 = data[1]
temp1 = (t2 << 8 | t1)
if t2 & 0x80:
temp1=temp1 | 0xFFFF0000
return temp1/16
dS18B20=DS18B20(2)
print(dS18B20.getTemp())
Page 243
from machine import UART,Pin
uart = UART(1,baudrate=9600,bits=8,parity=None,rx=12,tx=13)
SendData = bytearray("Hello World \n","utf-8")
uart.write(SendData)
RecData = uart.read()
print(RecData)
Page 246
from machine import UART,Pin, Timer
from utime import sleep_ms,sleep, time_ns
uart = UART(1,baudrate=9600,bits=8,parity=None,rx=12,tx=13,txbuf=256,rxbuf=16*1024)
test="A"*252
s = time_ns()
uart.write(test)
print((time_ns()-s)/1000000)
Page 246
from machine import UART,Pin, Timer
from utime import sleep_ms,sleep, time_ns
uart = UART(1,baudrate=9600,bits=8,parity=None, rx=12,tx=13, txbuf=16*1024,rxbuf=512)
test="A"*1000
s = time_ns()
uart.write(test)
print((time_ns()-s)/1000000)
sleep_ms(4000)
RecData = uart.read()
print(RecData)
Page 247
from machine import UART,Pin, Timer
from utime import sleep_ms,sleep, time_ns
uart = UART(1,baudrate=9600,bits=8,parity=None,rx=13,tx=12, txbuf=4*1024,rxbuf=512)
test = ""
for i in range(280):
test=test + str(i)+","
print(test)
print(len(test))
s = time_ns()
uart.write(test)
print((time_ns()-s)/1000000)
sleep_ms(4000)
RecData = uart.read()
print(RecData)
print(len(RecData))
Page 251
from machine import UART,Pin
from utime import sleep_ms, time_ns
uart = UART(1,baudrate=9600,bits=8,parity=None, rx=12,tx=13,rts=4,cts=5, timeout=0,timeout_char=0,txbuf=2000,rxbuf=256,flow=UART.RTS|UART.CTS)
test = "A"*1000
s = time_ns()
uart.write(test)
print((time_ns()-s)/1000000)
RecData = bytes()
while len(RecData)<1000:
sleep_ms(500)
if uart.any():
RecData = RecData + uart.read()
print(RecData)
print(len(RecData))
return -1
return 0
def writeByte(uart,byte):
buf=[]
for i in range(8):
if byte & 1 == 1:
buf.append(0xFF)
else:
buf.append(0x00)
byte = byte >> 1
uart.write(bytes(buf))
sleep_ms(10)
byte=uart.read(8)
def readByte(uart):
byte = bytes([0xFF]*8)
uart.write(byte)
sleep_ms(10)
byte = uart.read(8)
result=0
for b in byte:
result=result>>1
if b==0xFF:
result=result|0x80
return result
Page 256
uart = UART(1,baudrate=115200,bits=8,parity=None,rx=12,tx=13 )
print(presence(uart))
presence(uart)
writeByte(uart, 0xCC)
writeByte(uart, 0x44)
sleep_ms(1000)
presence(uart)
writeByte(uart, 0xCC)
writeByte(uart, 0xBE)
data=[]
for i in range(9):
data.append(readByte(uart))
t1 = data[0]
t2 = data[1]
temp1 = (t2 << 8 | t1)
if t2 & 0x80:
temp1=temp1 | 0xFFFF0000
temp=temp1/16
print(temp)
Page 257
import network
from machine import Pin, Timer
from time import sleep_ms
def setup(country, ssid, key):
network.country(country)
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
LED = Pin(2, Pin.OUT)
LED.on()
timeout = 20000
wifi.connect(ssid,key)
timer = Timer(1)
timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))
s = network.STAT_IDLE
while timeout>0:
print("connecting",s)
s = wifi.status()
if s != network.STAT_CONNECTING:
break
sleep_ms(100)
timeout = timeout-100
if(s==network.STAT_GOT_IP):
timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))
else:
timer.deinit()
LED.on()
return wifi
Page 265
from http.server import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def sendResponse(self, cmd):
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
self.send_response(200)
self.end_headers()
response = BytesIO()
response.write(b'This is a '+bytes(cmd, 'utf-8')+ b' request. ')
response.write(b'Received: ')
response.write(body)
self.wfile.write(response.getvalue())
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b'Hello, world!')
def do_HEAD(self):
self.send_response(200)
self.end_headers()
def do_POST(self):
self.sendResponse("POST")
def do_PUT(self):
self.sendResponse("PUT")
def do_DELETE(self):
self.sendResponse("DELETE")
def do_PATCH(self):
self.sendResponse("PATCH")
httpd = HTTPServer(('', 8080), SimpleHTTPRequestHandler)
httpd.serve_forever()
Page 268
import network
from machine import Pin, Timer
from time import sleep_ms
import urequests
def setup(country, ssid, key):
network.country(country)
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
LED = Pin(2, Pin.OUT)
LED.on()
timeout = 20000
wifi.connect(ssid,key)
timer = Timer(1)
timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))
s = network.STAT_IDLE
while timeout>0:
print("connecting",s)
s = wifi.status()
if s != network.STAT_CONNECTING:
break
sleep_ms(100)
timeout = timeout-100
if(s==network.STAT_GOT_IP):
timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))
else:
timer.deinit()
LED.on()
return wifi
wifi=setup(country, ssid, key)
print("Connected")
r = urequests.get("https://www.example.com")
print(r.content)
r.close()
Page 268
import network
from machine import Pin, Timer
from time import sleep_ms
import urequests
def setup(country, ssid, key):
network.country(country)
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
LED = Pin(2, Pin.OUT)
LED.on()
timeout = 20000
wifi.connect(ssid,key)
timer = Timer(1)
timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))
s = network.STAT_IDLE
while timeout>0:
print("connecting",s)
s = wifi.status()
if s != network.STAT_CONNECTING:
break
sleep_ms(100)
timeout = timeout-100
if(s==network.STAT_GOT_IP):
timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))
else:
timer.deinit()
LED.on()
return wifi
wifi=setup(country, ssid, key)
print("Connected")
url="http://192.168.253.72:8080"
r = urequests.get(url)
print(r.content)
r.close()
buf= b'Hello World'
r=urequests.post(url,data=buf)
print(r.content)
r.close()
r=urequests.put(url,data=buf)
print(r.content)
r.close()
r=urequests.patch(url,data=buf)
print(r.content)
r.close()
r=urequests.head(url)
print(r.content)
print(r.headers)
r.close()
r=urequests.delete(url,data=buf)
print(r.content)
r.close()
Page 270
import network
from machine import Pin, Timer
from time import sleep_ms
import urequests
import onewire
import ds18x20
def setup(country, ssid, key):
network.country(country)
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
LED = Pin(2, Pin.OUT)
LED.on()
timeout = 20000
wifi.connect(ssid,key)
timer = Timer(1)
timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))
s = network.STAT_IDLE
while timeout>0:
print("connecting",s)
s = wifi.status()
if s != network.STAT_CONNECTING:
break
sleep_ms(100)
timeout = timeout-100
if(s==network.STAT_GOT_IP):
timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))
else:
timer.deinit()
LED.on()
return wifi
wifi=setup(country, ssid, key)
print("Connected")
url = "http://192.168.253.72:8080"
ow = onewire.OneWire(Pin(22))
presence = ow.reset()
if presence:
print("Device present")
else:
print("No device")
DS = ds18x20.DS18X20(ow)
roms = DS.scan()
while True:
DS.convert_temp()
temp = DS.read_temp(roms[0])
buf = str(temp).encode("utf-8")
try:
r = urequests.put(url, data=buf)
r.close()
except:
print("Server Not Online")
sleep_ms(500)
Page 271
from http.server import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def log_message(self,*args, **kwargs):
pass
def do_PUT(self):
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
bodyString= body.decode(encoding="utf-8")
temp=float(bodyString)
print(temp)
self.send_response(200)
self.end_headers()
httpd = HTTPServer(('', 8080), SimpleHTTPRequestHandler)
httpd.serve_forever()
Page 280
import network
import socket
from machine import Pin, Timer
from time import sleep_ms
def setup(country, ssid, key):
network.country(country)
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
LED = Pin(2, Pin.OUT)
LED.on()
timeout = 20000
wifi.connect(ssid,key)
timer = Timer(1)
timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))
s = network.STAT_IDLE
while timeout>0:
print("connecting",s)
s = wifi.status()
if s != network.STAT_CONNECTING:
break
sleep_ms(100)
timeout = timeout-100
if(s==network.STAT_GOT_IP):
timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))
else:
timer.deinit()
LED.on()
return wifi
wifi=setup(country, ssid, key)
print("Connected")
url = "http://192.168.253.72:8080"
ai = socket.getaddrinfo("www.example.com", 80,socket.AF_INET)
addr = ai[0][-1]
s = socket.socket(socket.AF_INET)
s.connect(addr)
request = b"GET /index.html HTTP/1.1\r\nHost:example.org\r\n\r\n"
s.send(request)
print(s.recv(512))
Page 281
import network
import socket
import ssl
from machine import Pin, Timer
from time import sleep_ms
def setup(country, ssid, key):
network.country(country)
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
LED = Pin(2, Pin.OUT)
LED.on()
timeout = 20000
wifi.connect(ssid,key)
timer = Timer(1)
timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))
s = network.STAT_IDLE
while timeout>0:
print("connecting",s)
s = wifi.status()
if s != network.STAT_CONNECTING:
break
sleep_ms(100)
timeout = timeout-100
if(s==network.STAT_GOT_IP):
timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))
else:
timer.deinit()
LED.on()
return wifi
wifi=setup(country, ssid, key)
print("Connected")
ai = socket.getaddrinfo("example.com", 443,socket.AF_INET)
addr = ai[0][-1]
s = socket.socket(socket.AF_INET)
s.connect(addr)
sslSock=ssl.wrap_socket(s)
request = b"GET / HTTP/1.1\r\nHost:example.com\r\n\r\n"
sslSock.write(request)
print(sslSock.read(1024))
Page 285 Note DS1820 is connected to GPIO4
import network
import socket
from time import sleep_ms
from machine import Pin, Timer
import onewire
import ds18x20
def setup(country, ssid, key):
network.country(country)
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
LED = Pin(2, Pin.OUT)
LED.on()
timeout = 20000
wifi.connect(ssid,key)
timer = Timer(1)
timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))
s = network.STAT_IDLE
while timeout>0:
print("connecting",s)
s = wifi.status()
if s != network.STAT_CONNECTING:
break
sleep_ms(100)
timeout = timeout-100
if(s==network.STAT_GOT_IP):
timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))
else:
timer.deinit()
LED.on()
return wifi
wifi = setup("country", "ssid", "key")
ow = onewire.OneWire(Pin(4))
presence = ow.reset()
if presence:
print("Device present")
else:
print("No device")
DS = ds18x20.DS18X20(ow)
roms = DS.scan()
template = """<!DOCTYPE html>
<html>
<head> <title>Temperature</title> </head>
<body> <h1>Current Temperature</h1>
Hello ESP32 Server World <br/>
The Temperature is: <!--#temp--><br/>
</body>
</html>
"""
addr = socket.getaddrinfo('192.168.253.24', 8080)[0][-1]
print(addr)
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(0)
while True:
cl, addr = s.accept()
print('client connected from', addr)
print(cl.recv(512))
DS.convert_temp()
temp = DS.read_temp(roms[0])
html=template.replace("<!--#temp-->",str(temp))
headers = ("HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Server:ESP32\r\n"
f"Content-Length:{len(html)}\r\n\r\n"
)
buf = headers.encode("utf-8")+html.encode("utf-8")
cl.send(buf)
cl.close()
s.close()
Page 287
import binascii
with open("iopress.key", 'rb') as f:
lines = f.readlines()
lines = b"".join(lines[1:-1])
key = binascii.a2b_base64(lines)
print("key=", key)
with open("iopress.crt", 'rb') as f:
lines = f.readlines()
lines = b"".join(lines[1:-1])
cert = binascii.a2b_base64(lines)
print()
print("cert=", cert)
Page 288
Note DS1820 is connected to GPIO4
import network
import socket
from time import sleep_ms
from machine import Pin, Timer
import onewire
import ds18x20
import ssl
def setup(country, ssid, key):
network.country(country)
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
LED = Pin(2, Pin.OUT)
LED.on()
timeout = 20000
wifi.connect(ssid,key)
timer = Timer(1)
timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))
s = network.STAT_IDLE
while timeout>0:
print("connecting",s)
s = wifi.status()
if s != network.STAT_CONNECTING:
break
sleep_ms(100)
timeout = timeout-100
if(s==network.STAT_GOT_IP):
timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))
else:
timer.deinit()
LED.on()
return wifi
wifi=setup(country, ssid, key)
print("Connected")
print(wifi.ifconfig())
key=b'0\x82\x04\xbf\ . . .xabp\xd1'
cert=b'0\x82\x03k0\ . . .\x98\x8a'
ow = onewire.OneWire(Pin(4))
presence = ow.reset()
if presence:
print("Device present")
else:
print("No device")
DS = ds18x20.DS18X20(ow)
roms = DS.scan()
template = """<!DOCTYPE html>
<html>
<head> <title>Temperature</title> </head>
<body> <h1>Current Temperature</h1>
Hello ESP32 Server World <br/>
The Temperature is: <!--#temp--><br/>
</body>
</html>
"""
addr = socket.getaddrinfo('0.0.0.0', 443)[0][-1]
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(5)
while True:
cl, addr = s.accept()
print('client connected from', addr)
client_s =None
try:
client_s = ssl.wrap_socket(cl, server_side=True,
key=key, cert=cert)
while True:
h = client_s.readline()
if h == b"" or h == b"\r\n":
break
print(h.decode(), end="")
DS.convert_temp()
temp = DS.read_temp(roms[0])
html=template.replace("<!--#temp-->",str(temp))
headers = ("HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Server:ESP32\r\n"
f"Content-Length:{len(html)}\r\n\r\n"
)
buf = headers.encode("utf-8")+html.encode("utf-8")
client_s.write(buf)
client_s.close()
except Exception as e:
print("exception ",e)
s.close()
Page 308
import uasyncio
from machine import Pin
async def blink(led, period_ms):
while True:
led.on()
await uasyncio.sleep_ms(5)
led.off()
await uasyncio.sleep_ms(period_ms)
async def main(led1, led2):
uasyncio.create_task(blink(led1, 700))
uasyncio.create_task(blink(led2, 400))
await uasyncio.sleep_ms(10_000)
uasyncio.run(main(Pin(2,Pin.OUT), Pin(4,Pin.OUT)))
Page 309
import uasyncio
from machine import Pin
from time import sleep_ms
async def blink(led, period_ms):
while True:
led.on()
await uasyncio.sleep_ms(5)
led.off()
await uasyncio.sleep_ms(period_ms)
async def timewaste():
while True:
sleep_ms(10)
await uasyncio.sleep_ms(0)
async def main(led1, led2):
uasyncio.create_task(blink(led1, 700))
uasyncio.create_task(blink(led2, 400))
uasyncio.create_task(timewaste())
await uasyncio.sleep_ms(10_000)
uasyncio.run(main(Pin(2,Pin.OUT), Pin(4,Pin.OUT)))
Page 311
import uasyncio
from time import sleep_ms
from machine import Pin, Timer
import network
def setup(country, ssid, key):
network.country(country)
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
LED = Pin(2, Pin.OUT)
LED.on()
timeout = 20000
wifi.connect(ssid,key)
timer = Timer(1)
timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))
s = network.STAT_IDLE
while timeout>0:
print("connecting",s)
s = wifi.status()
if s != network.STAT_CONNECTING:
break
sleep_ms(100)
timeout = timeout-100
if(s==network.STAT_GOT_IP):
timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))
else:
timer.deinit()
LED.on()
return wifi
async def main():
reader,writer= await uasyncio.open_connection("www.example.com",80)
request = b"GET /index.html HTTP/1.1\r\nHost:example.org\r\n\r\n"
writer.write(request)
await writer.drain()
print(await reader.read(512))
reader.close()
wifi=setup(country, ssid, key)
print("Connected")
print(wifi.ifconfig())
uasyncio.run(main())
Page 314
Note DS1820 is connected to GPIO4
import uasyncio
import network
from machine import Pin, Timer
from time import sleep_ms
import onewire
import ds18x20
def setup(country, ssid, key):
network.country(country)
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
LED = Pin(2, Pin.OUT)
LED.on()
timeout = 20000
wifi.connect(ssid,key)
timer = Timer(1)
timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))
s = network.STAT_IDLE
while timeout>0:
print("connecting",s)
s = wifi.status()
if s != network.STAT_CONNECTING:
break
sleep_ms(100)
timeout = timeout-100
if(s==network.STAT_GOT_IP):
timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))
else:
timer.deinit()
LED.on()
return wifi
wifi=setup(country, ssid, key)
print("Connected")
print(wifi.ifconfig())
ow = onewire.OneWire(Pin(4))
presence = ow.reset()
if presence:
print("Device present")
else:
print("No device")
DS = ds18x20.DS18X20(ow)
roms = DS.scan()
template = """<!DOCTYPE html>
<html>
<head> <title>Temperature</title> </head>
<body> <h1>Current Temperature</h1>
Hello ESP32 Server World <br/>
The Temperature is: <!--#temp--><br/>
</body>
</html>
"""
async def serve_client(reader,writer):
print("client")
print(await reader.read(512))
DS.convert_temp()
temp = DS.read_temp(roms[0])
html=template.replace("<!--#temp-->",str(temp))
headers = ("HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Server:ESP32\r\n"
f"Content-Length:{len(html)}\r\n\r\n"
)
buf = headers.encode("utf-8")+html.encode("utf-8")
writer.write(buf)
await writer.drain()
writer.close()
await writer.wait_closed()
async def main():
await uasyncio.start_server(serve_client, '192.168.253.24', 80,backlog=5)
while True:
print("heartbeat")
await uasyncio.sleep(1)
uasyncio.run(main())
Page 319
from machine import mem32,Pin
from time import sleep_ms
led = Pin(2,mode=Pin.OUT)
GPIOSet = 0x60004008 #Change to 0x3FF44008 for the ESP32
GPIOClear = 0x6000400C #Change to 0x3FF4400C for the ESP32
mask = 1<<2
while True:
mem32[GPIOSet] = mask
sleep_ms(500)
mem32[GPIOClear] = mask
sleep_ms(500)
Page 319
from machine import mem32,Pin
from time import sleep_ms
@micropython.native
def blink():
GPIOSet = 0x60004008 #Change to 0x3FF44008 for the ESP32
GPIOClear = 0x6000400C #Change to 0x3FF4400C for the ESP32
mask = 1<<2
while True:
mem32[GPIOSet] = mask
mem32[GPIOClear] = mask
led = Pin(2,mode=Pin.OUT)
blink()
Page 323
from machine import Pin
import machine
def gpio_setgroup(value, mask):
machine.mem32[0x60004004] = machine.mem32[0x60004004] & ~mask | value & mask
#Change to 0x3FF44004 for the ESP32
pin = Pin(2, Pin.OUT)
pin = Pin(4, Pin.OUT)
value1 = 1 << 2 | 0 << 4
value2 = 0 << 2 | 1 << 4
mask = 1 << 2 | 1 << 4
while True:
gpio_setgroup(value1, mask)
gpio_setgroup(value2, mask)
Page 326 ESP32 only
from machine import Pin, DAC, mem32
from time import sleep
def _reg_get(adr):
return mem32[adr]
def _reg_set( adr,value, mask):
mem32[adr] = mem32[adr] & ~mask | value & mask
def enableSin(chan,f):
if chan<1 or chan>2:
return
setFreq(chan, f)
setPhase(chan,0x2)
#enable tone
_reg_set(0x3FF48898, 0x10000, 0x10000)
#select caannel
if chan==1:
_reg_set(0x3FF4889c, 1<<24,0x1<<24)
else:
_reg_set(0x3FF4889c, 1<<25, 0x1 <<25)
def setFreq(chan,f):
if chan<1 or chan>2:
return
step = int(f*65536/8000000) & 0xFFFF
_reg_set(0x3FF48898, step, 0x000FF)
def setPhase(chan,p):
_reg_set(0x3FF4889c, p << (20 + 2 * (chan – 1)), 0x03 << (20 + 2 * (chan - 1)))
def setScale(chan,s):
_reg_set(0x3FF4889c, s << (16 + 2 * (chan - 1)),0x03 << (16 + 2 * (chan - 1)))
def setOff(chan,off):
_reg_set(0x3FF4889c, off << (8 * (chan - 1)),0xFF << (8 * (chan - 1)))
dac1 = DAC(Pin(26))
enableSin(2,30000)
setScale(2,0x0)
setOff(2,0x0)
while(True):
sleep(0.001)
setPhase(2,0x3)
sleep(.001)
setPhase(2, 0x2)
Page 328
import ntptime
from machine import RTC
import network
from machine import Pin, Timer
from time import sleep_ms
def setup(country, ssid, key):
network.country(country)
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.disconnect()
LED = Pin(2, Pin.OUT)
LED.on()
timeout = 20000
wifi.connect(ssid,key)
timer = Timer(1)
timer.init(period=200, mode=Timer.PERIODIC,callback=lambda t:LED.value(not LED.value()))
s = network.STAT_IDLE
while timeout>0:
print("connecting",s)
s = wifi.status()
if s != network.STAT_CONNECTING:
break
sleep_ms(100)
timeout = timeout-100
if(s==network.STAT_GOT_IP):
timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:LED.value(not LED.value()))
else:
timer.deinit()
LED.on()
return wifi
wifi=setup("UK", "dlink3","hawkhawk")
print("Connected")
print(wifi.ifconfig())
ntptime.host="pool.ntp.org"
ntptime.timeout=1000
try:
ntptime.settime()
except Exception:
print("NTP server not available")
pass
rtc = RTC()
print(rtc.datetime())
Page 330
from machine import lightsleep
from time import sleep
for i in range(10):
print("starting sleep",i)
lightsleep(1000)
print ("back from sleep",i)
Page 331 What you see as the output of this depends on the IDE you are using
from machine import deepsleep
from time import sleep
for i in range(10):
print("starting sleep",i)
sleep(2)
print('I am going to sleep')
deepsleep(1000)
Page 331
What you see as the output of this depends on the IDE you are using
from machine import deepsleep, RTC
from time import sleep
sleep(3)
rtc = RTC()
if len(rtc.memory())==0:
start=0
else:
start = int.from_bytes(rtc.memory(),"big")
for i in range(start,start+10):
print(i)
print("starting sleep")
rtc.memory((i+1).to_bytes(4,"big"))
deepsleep(1000)
Page 333
What you see as the output of this depends on the IDE you are using
from machine import lightsleep,Pin
import esp32
wakePin = Pin(2,Pin.IN,pull=None)
esp32.wake_on_ext0(wakePin,esp32.WAKEUP_ANY_HIGH)
for i in range(10):
print("starting sleep",i)
lightsleep()
print ("back from sleep",i)
Page 335
What you see as the output of this depends on the IDE you are using
from machine import WDT
from time import sleep
sleep(4)
print("starting")
wdt = WDT(timeout=4000)
wdt.feed()
while True:
sleep(0.1)
print("still running")
pass
Page 336
What you see as the output of this depends on the IDE you are using
from machine import deepsleep
from time import sleep
from esp32 import NVS
sleep(3)
start = 0
nvsState = NVS("state")
try:
start = nvsState.get_i32("start")
except OSError:
pass
for i in range(start,start+10):
print(i)
print("starting sleep")
nvsState.set_i32("start",i+1)
nvsState.commit()
deepsleep(1000)
Page 344
import machine
import os
sd =machine.SDCard(slot=2, sck=18, miso=4, mosi=14, cs=5, freq=400)
print(sd)
os.mount(sd, "/sd")
f = open('/sd/Hello.txt', 'w')
f.write('Hello World')
f.close()
print(os.listdir('/sd'))
f = open('/sd/Hello.txt', 'r')
s=f.read()
f.close()
print(s)