"""
Edge-to-cloud communication
This embedded program is an example on how to communicate to the cloud from edge using external WiFi module.
The program is written for the Raspberry Pi Pico.
External WiFi module "ESP-01" is then expected to be connected to the Pico pins 0(tx) and 1(rx) for UART communication.
Pico then talks to the ESP-01 with AT Commands.
Program routine consists of
1. Initial phase
1. Setting up environment variables
2. Initialise the UART bus
3. Setting up WiFi device MAC address and hostname
4. Connecting WiFi device to WiFi AP(Access Point) for internet connection
2. Main loop
1. Collect potentiometer data
2. Send data(potentiometer + device_id) to the API in cloud
3. Receives response and prints response in console
3. Sleep 30 seconds
Author: Karri Miettinen
License: MIT
"""
import machine
import time
from wifiesp import WifiEsp
class Configs:
DEVICE_ID: str
"""Custom device identifier"""
BASE_URL: str
"""Base url to the API in the internet"""
POLL_RATE: int
"""Interval to send the data to the API in the internet"""
WIFI_UART_CHANNEL: int = 0
"""Pico has 2 UART peripherals (0 and 1)"""
WIFI_TX_PIN: int = 0
"""GPIO Pin for UART transmit(tx). Available GPIO Pins: 0, 4, 12, 17"""
WIFI_RX_PIN: int = 1
"""GPIO Pin for UART receive(rx). Available GPIO Pins: 1, 5, 9, 16"""
WIFI_MAC: str
"""
Media Access Control address. Used to recognize device in networks.
Address typically expressed in six pairs of hexadecimals e.g., "01:23:45:67:89:ab"
Hexadecimal characters range "0-f" (2^16 => 16 options).
See "private" area from https://standards-oui.ieee.org/oui/oui.txt
"""
WIFI_HOST: str
"""Wifi device hostname"""
WIFI_UART_BAUD_RATE: int = 115200
"""Baudrate = Clock rate(almost same). Typical baud rates: 110, 300, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 115200, 230400, 460800, 921600, 1000000"""
WIFI_SSID: str
"""WiFi network name - (Service Set IDentifier)"""
WIFI_PASS: str = ""
"""WiFi password"""
DEBUG: bool = False
"""Debug flag for console messages"""
TEST_MODULE: bool = False
"""Test wifi-module alone"""
CONF = Configs()
CONF.DEBUG = True
CONF.DEVICE_ID = "8266"
CONF.POLL_RATE = 30
CONF.BASE_URL = "https://httpbin.org"
CONF.WIFI_UART_CHANNEL = 1 # 0
CONF.WIFI_UART_BAUD_RATE = 115200
CONF.WIFI_TX_PIN = 4 # 0
CONF.WIFI_RX_PIN = 5 # 1
CONF.WIFI_MAC = "00:00:6C:00:00:01"
CONF.WIFI_HOST = "beginner"
CONF.WIFI_SSID = "Wokwi-GUEST"
CONF.WIFI_PASS = ""
CONF.TEST_MODULE = True
POT = machine.ADC(26)
"""Potentiometer for measuring analog data"""
CONVERSION_FACTOR = 3.3/65535
"""Convert 16-bit value to voltage scale 0 V - 3.3 V"""
LED = machine.Pin(17, machine.Pin.OUT)
"""Led indicator"""
def dmsg(data: str | bytes) -> None:
if CONF.DEBUG == True:
if isinstance(data, str):
print(data)
elif isinstance(data, bytes):
print(data.decode())
return None
def initialPhase() -> WifiEsp:
# uart: int = 0,
# baud: int = 115200,
# txPin: int = 0,
# rxPin: int = 1,
# debug: bool = False
dmsg(f'[UART] - channel={CONF.WIFI_UART_CHANNEL} baud={CONF.WIFI_UART_BAUD_RATE} txPin={CONF.WIFI_TX_PIN} rxPin={CONF.WIFI_RX_PIN} debug={CONF.DEBUG}')
wifi_conn = WifiEsp(
uart=CONF.WIFI_UART_CHANNEL,
baud=CONF.WIFI_UART_BAUD_RATE,
txPin=CONF.WIFI_TX_PIN,
rxPin=CONF.WIFI_RX_PIN,
debug=CONF.DEBUG
)
"""
UART is required to communicate with the ESP8266
UART related Pico hardware settings, see Pico pinout.
baudrate = 115200 => see ESP8266 documentation
packet 8N1 => 8 data bits, No parity bit, 1 stop bit => ESP8266 documentation
rxbuf size of receiving buffer
Routine starts
"""
# wifi_conn.testESP() # test Pico to ESP connection
# wifi_conn.checkESPVersion() # check ESP Version
# wifi_conn.listCmds() # list all available commands
# wifi_conn.availableRAM() # get available RAM
# wifi_conn.querySysRAM() # query sysRAM status
# wifi_conn.querySysFLASH() # query sysFLASH
# wifi_conn.listFiles() # list files in root directory, does not work
# wifi_conn.queryWiFiMode()
# wifi_conn.setWiFiMode(mode=0)
# wifi_conn.queryWiFiMode()
# wifi_conn.queryWiFiStatus()
print(f"Setting up WiFi module MAC address: {CONF.WIFI_MAC}")
wifi_conn.setMAC(CONF.WIFI_MAC) # set the ESP mac
wifi_conn.queryMAC() # query the ESP mac
wifi_conn.setHostname(hostname=CONF.WIFI_HOST) # set the ESP hostname
wifi_conn.queryHostname() # query EPS hostname
# wifi_conn.queryMAC() # query the ESP mac
# wifi_conn.queryAPList(ssid=WIFI.SSID)
wifi_conn.connectAP(ssid=CONF.WIFI_SSID, pwd=CONF.WIFI_PASS)
# wifi_conn.queryNetworkDetails()
wifi_conn.queryWiFiStatus()
return wifi_conn
def main() -> None:
time.sleep(1) # Sleep 1 second to make sure console is ready
print("Program starting.")
wifi_conn = initialPhase()
while CONF.TEST_MODULE == False:
LED.on()
raw = POT.read_u16()
volts = raw * CONVERSION_FACTOR
print('Raw: {}'.format(raw), 'Voltage: {:.1f}V'.format(volts))
query_params = f'dev_id={CONF.DEVICE_ID}&pot={str(raw)}'
"""
Data goes in format:'dev_id=abcd&pot=1234'
"""
# which one is more valuable, raw data or preprocessed?
request_url = f'{CONF.BASE_URL}/get?{query_params}'
# wifi_conn.httpGET(see parameters...)
response_text = wifi_conn.getRequest(request_url)
print(f'response: {response_text}')
time.sleep_ms(200) # sleep to keep the LED active for longer
LED.off()
time.sleep(CONF.POLL_RATE)
print("Program ending.")
return None
main()
Loading
esp-01
esp-01