import machine, os
from machine import Pin, ADC
def printBootInformation():
# Get operating system information
info = os.uname()
# Returns a list of 5 values
# 0: sysname
# 1: nodename
# 2: micropython version
# 3: micropython version and date
# 4: machine name
version = info[3]
speed = machine.freq() / 1000000
print("ESP32, micropython {}, frequency, {} MHz".format(version, speed))
print(" ")
print("Welcome to Serial console")
print("Use the help command to know what to do")
print(" ")
def parseCommand(command):
# Process led commands
# Format: led {on | off} { pin# }
if ("led" in command):
cmd_parts = command.split(" ")
if (len(cmd_parts) == 3 and cmd_parts[0] == "led"):
led_pin = int(cmd_parts[2])
led = Pin(led_pin, Pin.OUT)
if (cmd_parts[1] == "on"):
led.value(1)
return [True, "ok"]
elif (cmd_parts[1] == "off"):
led.value(0)
return [True, "ok"]
# Process adc commands
# Format: adc {read | voltage} { pin# }
elif ("adc" in command):
cmd_parts = command.split(" ")
if (len(cmd_parts) == 3 and cmd_parts[0] == "adc"):
adc_pin = int(cmd_parts[2])
adc = ADC(Pin(adc_pin))
if (cmd_parts[1] == "read"):
return [True, adc.read()]
elif (cmd_parts[1] == "voltage"):
raw_value = adc.read()
# Use formula: V = raw_value * 3.3V / 4096
voltage = raw_value * 3.3 / 4096
return [True, "{:.2f}V".format(voltage)]
# Process help command
elif ("help" in command):
# Just print a help
print("Available commands: led, adc")
print(" ")
print("led: Turns on or off an led on the provided pin")
print("Format: led { on | off } { pin } ")
print("Return: ok if success")
print(" ")
print("adc: Read the adc value in raw or voltage")
print("Format: adc { read | voltage } { pin } ")
print("Return: ADC raw value or volage value (in volts)")
return [True, " "]
# In any other cases, the command is invalid, return false
return [False]
# Program starts here
printBootInformation()
while True:
command = input("> ")
result = parseCommand(command)
if (not result[0]):
print("invalid command")
else:
print(result[1])