TNG

YouTube Channel - TNG Robotics   Visit Our YouTube Channel

Teaser 1 - Robo Buddy's Robo-Boogie!


  Class 2.0 | Connect

In this class explore robotic sensors. Distance Detection, Soil Moisture and Temperature & Humidity.


1.  Connect WeMos to Computer using your Micro-USB Cable.




2.  Open uPyCraft IDE:





Step 1) Open uPyCraft and cancel both alerts, as we will not need these.

Alert 1 Alert 2


Step 2) Select your board type as 'esp8266' from the Tools menu.


You may need to:

Flash your WeMos with MicroPython.



Set your board type as esp8266.
Set your erase_flash to yes.
Set your com port, ie. COM8.

Firmware Choose:
Select Users and press choose.

Download and Use the (latest) Firmware Release of MicroPython.
Click Here for Download Page: Firmware ESP8266_GENERIC
Latest release: 'v1.24.1(2024-11-29).bin'

Step 3) Select usb Serial port as 'COM8' or similar from the Tools menu.



You should see '>>>' appear in the bottom textbox.
Step 4) Test if connected. Type 21*2 at the bottom of uPyCraft, and press Enter.

Your WeMos esp8266 microprocessor chip is performing this calculation to return: 42



  Class 2.1 | Soil Moisture

Learn how to detect Soil Moisture with our Digital Pins. For the first time we'll use Pulse Width Modulation PWM.


HEXLINK Circuit Diagram:

1.  Start by wiring your first LED circuit.

i.   Use a Red Wire to connect Digital Pin 2 to the LED's positive (+) long end.

ii.   The LED's negative (-) short end connects to your 220 Ω Resistor directly on the Breadboard.

iii.   The right side of the 220 Ω Resistor connects to GND (Ground) with a Black Wire.

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)
				

We begin by importing our Python modules and functions.

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


Select your board type as 'esp8266' from the Tools menu.




Select usb Serial port as 'COM8' or similar from the Tools menu.



You should see '>>>' appear in the bottom textbox. Test if connected. Type 21*2 at the bottom of uPyCraft, and press Enter. Your WeMos esp8266 microprocessor chip is performing this calculation to return: 42

If asked, you may need to:

Flash your WeMos with MicroPython.



Set your board type as esp8266.
Set your erase_flash to yes.
Set your com port, ie. COM8.

Firmware Choose:
Select Users and press choose.

Download and Use the (latest) Firmware Release of MicroPython.
Click Here for Download Page: Firmware ESP8266_GENERIC
Latest release: 'v1.24.1(2024-11-29).bin'


Q. How do I save my code so it will run everytime I reset the WeMos?

A. You can save the file to upload as either 'boot.py' which loads first, or 'main.py' which loads second. Both of these will automatically load on WeMos boot. All other filenames will not load on WeMos boot, however, are useful for testing, since they will only run once. This allows you to rewrite the code frequently without concern.
Q. How do I reset my WeMos?

A. There's a little button on the side you can press next to the micro-USB port.





  Class 2.2 | Detect Distance

Detect the distance to nearby objects, useful for obstacle avoidance.


HEXLINK Circuit Diagram:

1.  Diagram for wiring your ADC circuit.

i.   We can reuse our Black Wire (GND) here and even leave 1.1 LED setup for 1.3 Nightlight next part.

ii.   Connect the 10k Ω Resistor from your Black Wire to your Photoresistor, and Green Wire to Pin A0.

iii.   Connect the other side of your Photoresistor to 5V with a Red Wire.

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)
				

Import our Python modules and functions:

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.



  Class 2.3 | Temp + Humidity

Sensor the Temperature and Humidity of your environment.


HEXLINK Circuit Diagram:

1.  Diagram for wiring your Nightlight circuit.

i.   Use same wiring setup as 1.1 LED

ii.   Use same wiring setup as 1.2 Photoresistor

iii.   Note: Save a wire by using a common ground wire.

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)
				

Import our Python modules and functions:

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.



  Class 2.4 | Web Buttons

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.


HEXLINK Circuit Diagram:

How It Works

  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.

ssid = 'Your-WIFI'
password = 'Your-PASSWORD'


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())
				

Import our Python modules and functions:

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.

It sends a HTTP response to the client. 'HTTP/1.1 200 OK' Indicates the request was successful.
Content-Type: text/html declares the response contains HTML code.
'\r\n\r\n' Will separate headers from the body of the response.
'+ html' Sends the variable html, which contains our website code written above to be displayed in web browser.


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