# MicroPython上手玩

在完成烧录MicroPython固件后，我们就可以使用它了。

### 1. 直接运行脚本

我们直接在解释器中输入python语句即可执行。

```python
# 示例代码：
print("Hello MicroPython")
```

<figure><img src="/files/XRpccuq4d7Op1gkIOWf7" alt=""><figcaption></figcaption></figure>

### 2. 使用.py文件运行程序

NyBoard WiFi模块使用了ESP8266的IO2与一个红色LED连接，用来指示连接状态。这个LED是可编程的。 写一个简单的`python blink`程序:

```python
from machine import Pin
import time

# GPIO LED IO2
def blink():
    
    led = machine.Pin(2, machine.Pin.OUT)     # Pin 2 ,Output mode
    
    while(True):			# loop
        led.on()			# light on LED
        time.sleep(1)		# delay 1s
        led.off()			# light off LED
        time.sleep(1)		# delay 1s

if __name__ == "__main__":
    blink()
```

<figure><img src="/files/hdeayhT2XQ0MEi2lcHhe" alt=""><figcaption></figcaption></figure>

按下工具栏上绿色的`开始运行`按钮，程序会通过串口发送到WiFi模块上， 由ESP8266内置的MicroPython解释器解释后运行。 因为案例程序是死循环，需要停止时，按下红色的`停止`键即可完成程序中断和复位。

### 3. 将.py文件下载到WiFi模块上&#x20;

我们点&#x51FB;**`View -> File`**&#x6253;开文件工具栏， Thonny左侧显示了文件。上部为本机的目录，下部为MicroPython设备中存储的文件。 默认情况下只有一个`boot.py`文件，这个文件请不要删除，是MicroPython设备的启动文件。

我们将刚刚的点灯程序保存为`blink.py`保存在本机后，右键点击文件，选&#x62E9;**`Upload to /`** :

<figure><img src="/files/HYPsfgxUi4EA3tBH6xAR" alt=""><figcaption></figcaption></figure>

在弹出窗口选&#x62E9;**`MicroPython device`**：

<figure><img src="/files/TKm1Ox01nmDCcJWAzLFn" alt=""><figcaption></figcaption></figure>

在设备上就有了一&#x4E2A;**`blink.py`**&#x7684;文件。这样文件就保存在设备上。

<figure><img src="/files/P0Uk7pY5QjcjXIvYxBt7" alt=""><figcaption></figcaption></figure>

### 4. 写一个python程序让机器人顺序执行动作

WiFi模块通过串口向NyBoard发送指令进行控制。我们只需要写一个简单的串口发送程序，向NyBoard发送一系列串口指令， 就可以让机器狗执行序列动作。

```python
from machine import UART
import time

uart = UART(0, baudrate=115200,timeout=5)

# walk
def walk(time_ms):
    print("walk")
    uart.write("kwkF")      # walk cmd
    time.sleep_ms(time_ms)  # keep time
    uart.write("d")         # stop
    time.sleep_ms(1500)
    
# backward
def back(time_ms):
    print("back")
    uart.write("kbk")
    time.sleep_ms(time_ms)
    uart.write("d")
    time.sleep_ms(1500)

# stop
def stop():
    uart.write("d")
    
def initConnection():
    connected = False
    while True:
        uart.write("d")
        for t in range(30):
            uos.dupterm(None, 1)        # disable REPL on UART(0), detach the REPL from UART0
            time.sleep_ms(5)            #delay is a must
            result = uart.read(1)
            uos.dupterm(uart, 1)        # enable REPL on UART(0), reattach REPL

            if result != None:
#                 uart.write(result)    # for debug
                if result == b"d":

                    connected = True
                    break
            time.sleep_ms(10)

        if connected:
            break

    uart.write("b22 4 24 4 26 4")
 

def actSeq():
    initConnection()
    time.sleep_ms(2000)
    walk(3000)
    back(3000)
    uart.write("m0 90")
    time.sleep_ms(3000)
    uart.write("i8 -20 9 -60")
    time.sleep_ms(2000)
    uart.write("b26 4 24 4 20 4")
    time.sleep_ms(1000)
    uart.write("d")
    uos.dupterm(None, 1)        # disable REPL on UART(0), detach the REPL from UART0

    
if __name__ == "__main__":
    actSeq()
    
```

当我们执行`actSeq()`函数时，就可以通过串口输出一系列指令。使用串口监视器我们可以进行调试。 使用串口监视器监控输出如下（为了方便阅读我使用了串口调试器的自动断帧，实际上是没有自动换行的）

<figure><img src="/files/05auEo1Epst9REMxDLBo" alt=""><figcaption></figcaption></figure>

### 5. 上电自动运行&#x20;

当我们调试完序列动作后，将WiFi模块拔下，插上NyBoard后，机器狗没有任何反应，因为`actSeq()`函数并没有运行。 我们希望上电自动运行程序，有以下2种方法：

1. 请将文件名更改成“main.py”并存到设备（这个是最简单的）
2. 修改`boot.py`启动文件


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.petoi.com/chinese/api/micropython-kong-zhi-qi/micropython-shang-shou-wan.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
