Turtorial Examples for ESP8266-MicroPython
2020/3/9
Turtorial Examples for ESP8266-MicroPython
ESP8266
http://docs.micropython.org/en/latest/esp8266/quickref.html
LED Blink
from time import sleep
from machine import Pin
p0 = Pin(0, Pin.OUT, value=0) # external LED
blink = 0
while True:
p0.value(0 if blink == 0 else 1)
blink = ~blink
sleep(0.1)
Pin/GPIO
from machine import Pin
p4 = Pin(4, Pin.IN, Pin.PULL_UP) # enable internal pull-up resistor
p4.value() # 1 if open
p4.value() # 0 if GND
PWM
from time import sleep
from machine import Pin, PWM
pwm0 = PWM(Pin(0)) # create PWM object from a pin
pwm0.freq(1000) # set frequency
for p in range(100):
pwm0.duty(10*p)
sleep(0.05)
for p in range(100):
pwm0.duty(1000-10*p)
sleep(0.05)
pwm0.deinit() # turn off PWM on the pin
ADC
AnalogInは一つしか無い
(A0,0-1023)
from machine import Pin, ADC
from time import sleep
a0 = ADC(0) # create ADC object on ADC pin
while True:
print(a0.read()) # read value, 0-1024
sleep(0.1)
SPI
TFT_SD_test_ESP8266.py
# TFT Touch Shield(with SD)
# (does not support Touch)
# setup display module
import ili9341_ESP8266
color565 = ili9341_ESP8266.color565
from machine import Pin, SPI
spi = SPI(miso=Pin(12), mosi=Pin(13, Pin.OUT), sck=Pin(14, Pin.OUT))
#spi=SPI(1)
display = ili9341_ESP8266.ILI9341(spi, cs=Pin(4), dc=Pin(5), rst=Pin(15))
# setup SDCard module
import machine, sdcard, os
sd = sdcard.SDCard(spi, Pin(2))
os.mount(sd, '/sd')
# setup path
import sys
sys.path.append('/sd')
sys.path.append('/sd/lib')
# display test
display.fill(color565(0xff, 0x11, 0x22))
display.fill(color565(0xff, 0xff, 0xff))
display.fill(color565(0x00, 0x00, 0x00))
display.pixel(120, 160, color565(0xff,0,0))
display.pixel(121, 161, color565(0,0,0xff))
display.pixel(123, 163, color565(0,0xff,0))
display.text('Hello World!',0,0,color=color565(0,0xff,00))
display.text('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz{}()+*<>?_',100,200,color=color565(0,0,0xff))
display.fill_rectangle(100,150,20, 50, color565(0xff,0,0))
# SD Card test
display.fill(color565(0x00, 0x00, 0xff))
display.text(str(sys.path),0,0,color565(0xff,0xff,0xff),clear_eol=True)
display.text(str(os.listdir('/sd')),0,0,color565(0xff,0xff,0xff),clear_eol=True)
I2C
ESP8266_TMP102_test.py
# ESP8266
import utime
from machine import Pin, I2C
from tmp102 import Tmp102
i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000)
sensor = Tmp102(i2c, 0x48)
while True:
print('Temperature: {0:.1f}'.format(sensor.temperature))
utime.sleep(2)
RTC
from machine import RTC
rtc = RTC()
rtc.datetime((2020, 3, 9, 1, 8, 53, 0, 0)) # set a specific date and time
# The 8-tuple has the following format:
# (year, month, day, weekday, hours, minutes, seconds, subseconds)
# weekday is 1-7 for Monday through Sunday.
# subseconds counts down from 255 to 0
rtc.datetime() # get date and time
時刻合わせのサンプル:
ESP32_8266_clock.py
以下は自分の環境に合わせる:
ssid = 'your_ssid'
password = 'your_passwd'
# NIC setup
import network, socket
WIFI_SSID = "your_ssid"
WIFI_PASSWD = "your_passwd"
def wlan_connect(ssid='SSID', password='PASSWD'):
import network
wlan = network.WLAN(network.STA_IF)
if not wlan.active() or not wlan.isconnected():
wlan.active(True)
print('connecting to:', ssid)
wlan.connect(ssid, password)
while not wlan.isconnected():
pass
wlan_connect(ssid=WIFI_SSID, password=WIFI_PASSWD)
#==========================================
# ESP32_8266_clock.py
from machine import Pin, RTC
import network, urequests, utime
import ujson
rtc = RTC()
url_jst = "http://worldtimeapi.org/api/timezone/Asia/Tokyo" # see http://worldtimeapi.org/timezones
retry_delay = 5000 # interval time of retry after a failed Web query
response = urequests.get(url_jst)
# parse JSON
parsed = response.json()
#parsed=ujson.loads(res) # in case string
datetime_str = str(parsed["datetime"])
year = int(datetime_str[0:4])
month = int(datetime_str[5:7])
day = int(datetime_str[8:10])
hour = int(datetime_str[11:13])
minute = int(datetime_str[14:16])
second = int(datetime_str[17:19])
subsecond = int(round(int(datetime_str[20:26]) / 10000))
# update internal RTC
rtc.datetime((year, month, day, 0, hour, minute, second, subsecond))
# setup day of the week
daysOfTheWeek = "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
tm = utime.localtime(utime.mktime(utime.localtime()))
while True:
# generate formated date/time strings from internal RTC
date_str = "Date: {0:4d}/{1:02d}/{2:02d}".format(*rtc.datetime())+' ('+daysOfTheWeek[tm[6]]+')'
time_str = "Time: {4:02d}:{5:02d}:{6:02d}".format(*rtc.datetime())
print(date_str)
print(time_str)
print('-----------')
utime.sleep(1)
#=============================================
NeoPixel
# neopixel simple test
from machine import Pin
from neopixel import NeoPixel
pin = Pin(2, Pin.OUT) # D4 (Arduino Pin) @Grove Solet_D3
np = NeoPixel(pin, 8)
np[0] = (255, 255, 255)
np[1] = (255, 255, 0)
np[2] = (255, 0, 0)
np[3] = (0, 255, 255)
np[4] = (0, 255, 0)
np[5] = (0, 0, 255)
np[6] = (255, 255,0)
np[7] = (255, 0, 0)
np.write()
DHT
ESP8266_demo_DHT11.py
# ESP8266
from dht import DHT11
import machine
from time import sleep
d = DHT11(machine.Pin(14)) # D7 (Arduino Pin)
while True:
d.measure()
tempe=d.temperature()
humi=d.humidity()
print('tempe:'+str(tempe)+ ' humi:'+str(humi))
sleep(1)
Networking
以下は自分の環境に合わせる:
ssid = 'your_ssid'
password = 'your_passwd'
# NIC setup
import network, socket
WIFI_SSID = "your_ssid"
WIFI_PASSWD = "your_passwd"
def wlan_connect(ssid='SSID', password='PASSWD'):
import network
wlan = network.WLAN(network.STA_IF)
if not wlan.active() or not wlan.isconnected():
wlan.active(True)
print('connecting to:', ssid)
wlan.connect(ssid, password)
while not wlan.isconnected():
pass
wlan_connect(ssid=WIFI_SSID, password=WIFI_PASSWD)
Performace Test
performanceTestESP32.py
# Peformace Test for ESP32
from machine import RTC
rtc = RTC()
rtc.datetime((2020, 2, 9, 1, 12, 48, 0, 0))
# (year, month, day, weekday, hours, minutes, seconds, subseconds)
def performanceTest():
secs = rtc.datetime()[6]
endTime = secs + 10
count = 0
while rtc.datetime()[6] < endTime:
count += 1
print("Count: ", count)
performanceTest()
以上
| 固定リンク
「linux」カテゴリの記事
- platfomioを使ってnaitive(linux/windows)のプログラムをビルドする方法(2021.03.10)
- micro:bit Yotta開発ツール(linux版)(2021.01.09)
- PlatformIOをRaspberryPi4で動かしてみる(実験)(2020.10.20)
- headless RaspberryPiインストール方法(v2)(2020.10.20)
- wio-terminalのファームウェア・アップデートについて(linux版)(2020.10.15)
「MicroPython」カテゴリの記事
- microbit-v2にMicropythonをインストールする(2021.05.06)
- PicoボードのMicroPythonをVS_CodeのextensionのPico-Goでプログラミングする(2021.02.10)
- MicroPython/CircuitPython Performance Test(2021.02.07)
- PicoボードにMicropython/CircuitPythonをインストールする(2021.02.03)
- MicroPython(F767ZI) Network Samples(2021.01.03)
コメント