Programming the ESP32 in MicroPython
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 44
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 46
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(6, 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
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 83
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 84
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 85
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 86
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 87
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 87
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 90
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 92
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 93
from machine import Pin
import time
pinIn = Pin(4, Pin.IN)
pinLED1 = Pin(2, Pin.OUT)
pinLED2 = Pin(16, Pin.OUT)
pinLED3 = Pin(17, 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
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 101
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 101
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 104
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 105
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 106
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 114
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 117
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 119
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 120
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 131
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 136
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(16,17)
sleep(1)
motor.setSpeed(50)
sleep(1)
motor.setForward(False)
sleep(1)
motor.setSpeed(90)
sleep(1)
motor.setForward(True)
motor.off()
Page 139
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 146
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, 0x3, 0x2, 0x6, 0x4, 0xC, 0x8, 0x9]
# [
# [0,0,0,1],
# [0,0,1,1],
# [0,0,1,0],
# [0,1,1,0],
# [0,1,0,0],
# [1,1,0,0],
# [1,0,0,0],
# [1,0,0,1]
# ]
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 151
from machine import Pin, mem32, 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, 0x3, 0x2, 0x6, 0x4, 0xC, 0x8, 0x9]
self.timer = None
self.forward = True
# [
# [0,0,0,1],
# [0,0,1,1],
# [0,0,1,0],
# [0,1,1,0],
# [0,1,0,0],
# [1,1,0,0],
# [1,0,0,0],
# [1,0,0,1]
# ]
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 doRotate(self, timer):
if self.forward:
self.stepForward()
else:
self.stepReverse()
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)
step=StepperBi4(16)
step.setPhase(0)
while True:
step.rotate(True,100)
sleep_ms(500)
step.rotate(True,0)
sleep_ms(500)
Page 160
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 168
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(15, 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 169
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,15)
volts=adc.read(1)
print(volts)
Page 173
from machine import mem32
def getVCal():
VC=(mem32[0x3FF5_A010]>>8)& 0x1F
if(VC & 0x10 ):
VC=-(VC & 0x0F)
return 1100+VC*7
print(getVCal())
Page 177
from machine import ADC,Pin
import time
adc = ADC(Pin(32),atten=ADC.ATTN_11DB)
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 178
import esp32
import time
while(True):
m = esp32.hall_sensor()+esp32.hall_sensor()+esp32.hall_sensor()+esp32.hall_sensor()
m = m/4
print(m)
time.sleep(0.5)
Page 181
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 181
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)
Page 197
from machine import Pin,I2C
i2c0 = I2C(0,scl=Pin(18),sda=Pin(19),freq=100000)
buf = bytearray([0xE7])
i2c0.writeto( 0x40, buf, True)
read= i2c0.readfrom(0x40, 1, True)
print("User Register =",read)
Page 199
from machine import Pin,I2C
i2c0 = I2C(0,scl=Pin(18),sda=Pin(19),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 200
from machine import Pin,SoftI2C
i2c0 = SoftI2C(scl=Pin(18),sda=Pin(19),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 201
from machine import Pin,I2C
i2c0=I2C(0,scl=Pin(18),sda=Pin(19),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 202
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(18),sda=Pin(19),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(23))
while True:
dht.measure()
temp = dht.temperature()
print(temp,"C")
hum = dht.humidity()
print(hum,"%")
sleep(1)
Page 213
from machine import Pin
from utime import sleep_ms
DHT = Pin(23,mode=Pin.OUT,value=1)
sleep_ms(1)
DHT.off()
sleep_ms(1)
DHT.init(mode=Pin.IN)
Page 217
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(23)
dht.getReading()
print("Checksum",dht.checksum)
print("Humidity= ", dht.humidity)
print("Temperature=", dht.temperature)
Page 223
from machine import Pin
import onewire,ds18x20
ow = onewire.OneWire(Pin(23))
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 230
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(23)
print(dS18B20.getTemp())
Page 239
from machine import UART,Pin
uart = UART(1,baudrate=9600,bits=8,parity=None,rx=23,tx=22)
SendData = bytearray("Hello World \n","utf-8")
uart.write(SendData)
RecData = uart.read()
print(RecData)
Page 242
from machine import UART,Pin, Timer
from utime import sleep_ms,sleep, time_ns
uart = UART(1,baudrate=9600,bits=8,parity=None,rx=23,tx=22,txbuf=256,rxbuf=16*1024)
test="A"*252
s = time_ns()
uart.write(test)
print((time_ns()-s)/1000000)
Page 242
from machine import UART,Pin, Timer
from utime import sleep_ms,sleep, time_ns
uart = UART(1,baudrate=9600,bits=8,parity=None, rx=23,tx=22, 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 243
from machine import UART,Pin, Timer
from utime import sleep_ms,sleep, time_ns
uart = UART(1,baudrate=9600,bits=8,parity=None,rx=23,tx=22, 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 247
from machine import UART,Pin
from utime import sleep_ms, time_ns
uart = UART(1,baudrate=9600,bits=8,parity=None, rx=23,tx=22,rts=21,cts=19, 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))
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 261
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 264
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 265
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 266
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 267
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 276
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 277
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 281
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(22))
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 283
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 284
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(22))
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 304
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(22,Pin.OUT), Pin(23,Pin.OUT)))
Page 305
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(22,Pin.OUT), Pin(23,Pin.OUT)))
Page 307
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 310
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(22))
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 315
from machine import mem32,Pin
from time import sleep_ms
led = Pin(2,mode=Pin.OUT)
GPIOSet = 0x3FF44008
GPIOClear = 0x3FF4400C
mask = 1<<2
while True:
mem32[GPIOSet] = mask
sleep_ms(500)
mem32[GPIOClear] = mask
sleep_ms(500)
Page 315
from machine import mem32,Pin
from time import sleep_ms
@micropython.native
def blink():
GPIOSet = 0x3FF44008
GPIOClear = 0x3FF4400C
mask = 1<<2
while True:
mem32[GPIOSet] = mask
mem32[GPIOClear] = mask
led = Pin(2,mode=Pin.OUT)
blink()
Page 318
from machine import Pin
import machine
def gpio_setgroup(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_setgroup(value1, mask)
gpio_setgroup(value2, mask)
Page 323
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 324
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(country, ssid, key)
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 326
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 327
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 327
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 329
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 331
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
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)