Micropython Code Explanation: Concurrent Processing, Browsing, and Servo Control

The provided code is designed for controlling a robot, integrating network connections, web page provisioning, and servo motor control. Specifically, it utilizes a Pico microcontroller.

The code can be divided into several major blocks as follows:

Import Statements

import network            # Network library
import socket             # Socket library
from time import sleep    # Sleep library
from picozero import pico_temp_sensor, pico_led   # GPIO library
import machine
from machine import Pin, PWM
import utime
import time
import _thread
import gc
gc.enable()

This section imports the necessary libraries. Libraries such as network and socket are for network connections, while machine and picozero are used for GPIO pin control. The code also utilizes _thread for multithreading and gc for memory management.

Network Configuration and Web Page

# Network setting
ssid = 'SSID'       
password = 'PASSWORD'

def connect():
    ...

def open_socket(ip):
    ...

def webpage():
    ...

Here, functions are defined for connecting to Wi-Fi, obtaining an IP address, opening a socket, and defining the HTML for a web page that controls the robot.

Main Server Process

try:
    ip = connect()
    connection = open_socket(ip)
    html = webpage()
except (KeyboardInterrupt, OSError) as e:
    machine.reset()

Attempts to connect to Wi-Fi, open a socket, and load the web page. The device is reset in case of errors.

Servo Motor Configuration

servo = []
servo.append(PWM(Pin(2))) #Front Right Leg
...

This block sets up GPIO pins for servo motors and prepares them for control using PWM signals.

Multithreading Processing

def core0(params, servo):
    ...
    
def core1(params, servo):
    ...
    
_thread.start_new_thread(core1, (params, servo))
core0(params, servo)

Functions core0 and core1 handle different tasks: core0 processes network requests, and core1 controls servo motors. The code uses _thread.start_new_thread to run core1 in a new thread while core0 runs in the main thread.

Server Response and Servo Motor Control

In the core0 function, a state variable is updated based on HTTP requests from the client to control the robot’s actions. In contrast, the core1 function contains logic for actually moving the servo motors based on the state variable.

This code is an example of an application that combines network functionality with physical device control. It employs multithreading to handle network processing and device control simultaneously.

コメント

タイトルとURLをコピーしました