In this class explore robotic sensors. Distance Detection, Soil Moisture and Temperature & Humidity.
2. Open uPyCraft IDE:
Learn how to detect Soil Moisture with our Digital Pins. For the first time we'll use Pulse Width Modulation PWM.
1. Start by wiring your first LED circuit.
2. In uPyCraft, open a new file and add this code.
from machine import Pin
from time import sleep
led = Pin(2, Pin.OUT)
while True:
led.value(not led.value())
sleep(1)
from machine import Pin
from time import sleep
We import the function Pin from machine module, and import the function sleep from time module.
led = Pin(2, Pin.OUT)
Next, we create an 'led' variable and assign our LED to Pin 2. Pin.OUT configures the pin as an output to provide 3.3V to our LED. Python coding requires you to capitalize properly, so that capital 'P' in 'Pin' matters. Typing 'pin' would return an error.
while True:
led.value(not led.value())
sleep(1)
While the following statements are true, we then toggle the LED state using a logical not statement to flip 'on/off'. Then, the following code sleep(1) provides a 1 second delay between each LED on/off state change.
Before Upload (1) Save your code. (2) Set board to esp8266. (3) Set usb Serial port.
FAQs
Detect the distance to nearby objects, useful for obstacle avoidance.
1. Diagram for wiring your ADC circuit.
2. In uPyCraft, open a new file and add this code.
from machine import Pin, time_pulse_us
import time
trig = Pin(0, Pin.OUT)
echo = Pin(2, Pin.IN)
def measure_distance():
trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)
pulse = time_pulse_us(echo, 1, 30000) # Measure pulse duration
return pulse / 58 if pulse > 0 else None # Convert to cm
while True:
dist = measure_distance()
print("Distance: {:.1f} cm".format(dist) if dist else "Out of range")
time.sleep(1)
from machine import Pin, time_pulse_us
import time
We import the function Pin from machine module, and import the function sleep from time module.
trig = Pin(0, Pin.OUT)
echo = Pin(2, Pin.IN)
This is our Pin setup for the Distance Sensor.
def measure_distance():
trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)
pulse = time_pulse_us(echo, 1, 30000) # Measure pulse duration
return pulse / 58 if pulse > 0 else None # Convert to cm
This creates a 'photoresistor' variable and assigns our ADC pin. On ESP8266, ADC is always pin 0 (A0). We'll use this ADC to read our Photoresistor light sensor based on its variable resistance.
while True:
dist = measure_distance()
print("Distance: {:.1f} cm".format(dist) if dist else "Out of range")
time.sleep(1)
While the following statements are true, we then read the ADC pin to get our light level. Then, we print this value to the output, and sleep(0.5) provides a half second (0.5 s) delay between each photoresistor value reading.
Before Upload (1) Save your code. (2) Set board to esp8266. (3) Set usb Serial port.
Sensor the Temperature and Humidity of your environment.
1. Diagram for wiring your Nightlight circuit.
2. In uPyCraft, open a new file and add this code.
from machine import ADC, Pin
from time import sleep
photoresistor = ADC(0)
led = Pin(2, Pin.OUT)
LIMIT = 300
while True:
light = photoresistor.read()
if light < LIMIT:
led.on()
else:
led.off()
print("Light Level:", light)
sleep(0.2)
from machine import Pin
from time import sleep
We import the function Pin from machine module, and import the function sleep from time module.
photoresistor = ADC(0)
led = Pin(2, Pin.OUT)
LIMIT = 300
Initialize ADC for the photoresistor on (A0) pin. We use this to read our Photoresistor value and use it to toggle an LED on/off depending on how dark the room is. We create a variable 'led' and assign our LED on Pin(2). Pin.OUT makes this an output pin to provide 3.3V to our LED. We set our LIMIT that will determine at what light level we turn the LED on/off.
while True:
light = photoresistor.read()
if light < LIMIT:
led.on()
else:
led.off()
print("Light Level:", light)
sleep(0.2)
While the following statements are true, read light level from photoresistor (0-1023). If the light level is above our LIMIT, then turn the LED off in a bright environment. If the light level is less than our LIMIT, then turn the LED on in a dark environment. Print the light level value to the terminal, then sleep(0.2) provides a 0.2 second delay between each code cycle.
Before Upload (1) Save your code. (2) Set board to esp8266. (3) Set usb Serial port.
This code creates an IoT application to control an LED over Wi-Fi.
The WeMos operates on 2.4 GHz Wi-Fi networks. It does not support 5 GHz Wi-Fi networks. Thankfully, most Smartphones can setup a 2.4 GHz Wi-Fi Hotspot these days, which works as long as you connect your WeMos and Smartphone to the same Hotspot.
1. WeMos connects to a 2.4 GHz Wi-Fi network.
2. WeMos turns into a web server host on port 80.
3. When a web browser (that must be on the same Wi-Fi network) goes to the IP address, then the WeMos returns a HTML website. You can then toggle the LED simply by visiting a website.
4. Clicking a button on this website sends a request (/on or /off) to the server.
5. The server reads the request, toggles the LED, and updates the web browser.
Update the Wi-Fi setup code with your Wi-Fi details before uploading to the WeMos.
import network
import socket
from machine import Pin, time_pulse_us
import time
# Wi-Fi credentials
SSID = "YourSSID"
PASS = "YourPassword"
# Pin setup
trig = Pin(0, Pin.OUT)
echo = Pin(2, Pin.IN)
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASS)
while not wlan.isconnected():
time.sleep(1)
return wlan.ifconfig()[0]
def measure_distance():
trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)
pulse = time_pulse_us(echo, 1, 30000)
return pulse / 58 if pulse > 0 else None
def start_server(ip):
s = socket.socket()
s.bind((ip, 80))
s.listen(1)
print("Server running at http://{}".format(ip))
while True:
cl, _ = s.accept()
dist = measure_distance()
html = f"""
<html><head><meta http-equiv="refresh" content="0.5"></head>
<body><h1>Distance: {dist:.1f} cm</h1></body></html>
"""
cl.send("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n" + html)
cl.close()
start_server(connect_wifi())
from machine import Pin
import network
import socket
We continue using our Pin function, and for the first time we'll use network and socket. Network is used to connect to Wi-Fi. Socket is used to make a web connection to toggle our LED from a website.
# LED setup
led = Pin(2, Pin.OUT)
Connect our LED on Pin(2) and Pin.OUT allows it to become a 3.3V output pin.
# Wi-Fi setup
ssid = 'Your-WIFI'
password = 'Your-PASSWORD'
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
pass
print('Wi-Fi connected, see website at:', wlan.ifconfig()[0])
Replace 'Your-WIFI' with your Wi-Fi network name, remember it must be a 2.4GHz Wi-Fi. Replace 'Your-PASSWORD' with your Wi-Fi password. Visit the IP address printed to your terminal, and this will allow you to toggle your LED web buttons.
# HTML website code
html = """
<!DOCTYPE html>
<html>
<body style='text-align:center;'>
<h1>Toggle LED</h1>
<form action='/on'><button>Turn ON</button></form>
<form action='/off'><button>Turn OFF</button></form>
</body>
</html>
"""
This declares our website as HTML, a web coding language. We then make buttons to toggle our LED within the body tag. The form tag allows us to send data to our WeMos when submitted by pressing a button.
# Start web server
server = socket.socket()
server.bind(('', 80))
server.listen(1)
print('Server running...')
Our next Python code starts a basic web server using the socket module. It's setup with default settings for address family: AF_INET (IPv4) and socket type: SOCK_STREAM (TCP connection).
# Handle web requests
while True:
conn, _ = server.accept()
request = conn.recv(1024).decode()
led.on() if '/on' in request else led.off() if '/off' in request else None
conn.send("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n" + html)
conn.close()
This code waits for a client connection to the server. When a client connects, conn.recv(1024) reads up to 1024 bytes from the client connection, while .decode() converts the received bytes into a string. The request controls the LED. If the URL contains /on, the LED is turned on: led.on(). If the URL contains /off, the LED is turned off: led.off(), else None.
Before Upload (1) Save your code. (2) Set board to esp8266. (3) Set usb Serial port.
Hey!
We think you are pretty cool.
Interests
Robots Fun Education Games Friends Events 3D Prints Code Design Art workshops