【得捷Follow me第3期】+ 自定分任务(Ros X ESP32-C3)
[复制链接]
本帖最后由 夷则玖 于 2023-12-17 23:36 编辑
第一部分:
视频地址:视频
第二部分:
任务1:使用MicroPython系统
任务介绍:使用Thonny ide可以极其方便地安装MicroPython系统、安装官方库和编辑代码等等
功能展示:
安装好Thonny之后,打开Thonny,用c to usb线连接Seeed XIAO Esp32-C3和电脑
然后在Thonny右下角选择Configure interpreter
然后选择"MicroPython(Esp32-C3)" >>> "USB JTAG/serial debug..." >>>"安装或更新MicroPython(Esptool)"
接着在弹出窗口选择"USB JTAG/serial debug..." >>> "Esp32-C3" >>>"eapressif · Esp32-C3">>>选择版本
最后单击“安装”,这样就安装好MicroPython了。
说明:若下载缓慢,由于众所周知的原因,需科学上网。
心得建议:Micro是个非常易于使用的语言,有丰富的配套资源以及库,在以后的开发中利用其可以省时省力
任务2:驱动扩展板上的OLED屏幕
任务3:控制蜂鸣器播放音乐
任务介绍:这里将任务二三合并一起完成会更有趣。驱动屏幕显示文字和图形同时播放音乐。“Little star”是一首旋律极为简单的歌适合用蜂鸣器播放,同时用屏幕显示歌词并闪烁星星
主要代码:
导入库,random用于随机星星的尺寸以及位置,math用于计算星星关键点的坐标,ssd1306用于驱动屏幕,machine需要在micropython环境导入。
import machine
import time
from machine import Pin, SoftI2C
import ssd1306
import math
import random
屏幕参数设置
#Pin assignment
i2c = SoftI2C(scl=Pin(7), sda=Pin(6)) # Adjust the Pin numbers based on your connections
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.fill(0) # Clear the screen
蜂鸣器参数设置,从官方例程中可以获得这些音符对应的频率
# Buzzer settings
buzzer_pin = machine.Pin(5, machine.Pin.OUT)
buzzer = machine.PWM(buzzer_pin)
#buzzer.freq(1047)
# Defining frequency of each music note
NOTE_C4 = 262
NOTE_D4 = 294
NOTE_E4 = 330
NOTE_F4 = 349
NOTE_G4 = 392
NOTE_A4 = 440
NOTE_B4 = 494
NOTE_C5 = 523
NOTE_D5 = 587
NOTE_E5 = 659
NOTE_F5 = 698
NOTE_G5 = 784
NOTE_A5 = 880
NOTE_B5 = 988
编辑小星星的音符以及时值
# Music notes of the song, 0 is a rest/pulse
notes = [
NOTE_C5,NOTE_C5,NOTE_G5,NOTE_G5,NOTE_A5,NOTE_A5,NOTE_G5,0,
NOTE_F5,NOTE_F5,NOTE_E5,NOTE_E5,NOTE_D5,NOTE_D5,NOTE_C5,0,
NOTE_G5,NOTE_G5,NOTE_F5,NOTE_F5,NOTE_E5,NOTE_E5,NOTE_D5,0,
NOTE_G5,NOTE_G5,NOTE_F5,NOTE_F5,NOTE_E5,NOTE_E5,NOTE_D5,0,
NOTE_C5,NOTE_C5,NOTE_G5,NOTE_G5,NOTE_A5,NOTE_A5,NOTE_G5,0,
NOTE_F5,NOTE_F5,NOTE_E5,NOTE_E5,NOTE_D5,NOTE_D5,NOTE_C5,0
]
# Durations (in ms) of each music note of the song
# Quarter Note is 250 ms when songSpeed = 1.0
durations = [
250,250,250,250,250,250,500,0,
250,250,250,250,250,250,500,0,
250,250,250,250,250,250,500,0,
250,250,250,250,250,250,500,0,
250,250,250,250,250,250,500,0,
250,250,250,250,250,250,500,0
]
编辑“Little Star”台词
lyrics = [
"Twinkle","twinkle","little","star",
"how i","wonder","what you","are",
"up a","-bove the","world so","high",
"like a","diamond","in the","sky",
"Twinkle","twinkle","little","star",
"how i","wonder","what you","are"
]
定义画星星函数
def draw_star(x,y,size):
angle = 72
outer_points = []
inner_points = []
for i in range(5):
outer_points.append((x + size * math.cos(math.radians(i * angle)), y + size * math.sin(math.radians(i * angle))))
inner_points.append((x + size / 2 * math.cos(math.radians(i * angle + angle / 2)), y + size / 2 * math.sin(math.radians(i * angle + angle / 2))))
for i in range(5):
oled.line(math.floor(outer_points[i][0]), math.floor(outer_points[i][1]), math.floor(inner_points[i][0]), math.floor(inner_points[i][1]),1)
oled.line(math.floor(inner_points[i][0]), math.floor(inner_points[i][1]), math.floor(outer_points[(i+1)%5][0]), math.floor(outer_points[(i+1)%5][1]),1)
定义播放歌曲函数
def play_song():
total_notes = len(notes)
for i in range(total_notes):
current_note = notes[i]
wait = durations[i]*2
lyric = lyrics[math.floor(i/2)]
oled.fill(0) # Clear the screen
oled.text(lyric, 20, 30)
if current_note != 0:
buzzer.freq(current_note) # Set frequency of the note
buzzer.duty(10) # Set duty cycle for sound
else:
buzzer.duty(0) # Turn off the sound
draw_star(random.randint(0,127),random.randint(0,63),random.randint(10,20))
oled.show() # Show the text
time.sleep_ms(wait-100)
buzzer.duty(0) # Turn off the sound
time.sleep_ms(100)
最后是主函数
while True:
# Play the song
play_song()
功能展示:
说明:使用这个程序实现了一边听小星星,一边看星星闪烁,还能看小星星英文歌词学英语
心得建议:要是屏幕是彩屏再大一些就好了
任务4:连接WiFi网络
任务5:使用外部传感器
任务介绍:将任务四五合并为一个任务完成,能获取室内外温度和湿度,更完善了桌面小助手
主要代码:
导入必要的库,便于从api获取信息
import time
from machine import Pin, SoftI2C
import ssd1306
import math
import ahtx0
import network
import urequests
import ujson
然后是相关配置,根据官方例程修改,然后获取一个天气api
# ESP8266 Pin assignment
i2c = SoftI2C(scl=Pin(7), sda=Pin(6)) # Adjust the Pin numbers based on your connections
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
sensor = ahtx0.AHT10(i2c)
station = network.WLAN(network.STA_IF)
station.active(True)
# Network settings
wifi_ssid = "你的WiFi名称"
wifi_password = "WiFi密码"
url = "https://api.seniverse.com/v3/weather/now.json?key=你的key&location=changsha&language=en&unit=c"
print("Scanning for WiFi networks, please wait...")
authmodes = ['Open', 'WEP', 'WPA-PSK' 'WPA2-PSK4', 'WPA/WPA2-PSK']
for (ssid, bssid, channel, RSSI, authmode, hidden) in station.scan():
print("* {:s}".format(ssid))
print(" - Channel: {}".format(channel))
print(" - RSSI: {}".format(RSSI))
print(" - BSSID: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}".format(*bssid))
print()
# Continually try to connect to WiFi access point
while not station.isconnected():
# Try to connect to WiFi access point
print("Connecting...")
station.connect(wifi_ssid, wifi_password)
time.sleep(10)
# Display connection details
print("Connected!")
print("My IP Address:", station.ifconfig()[0])
最后是主函数,隔十秒重新获取室外温度
while True:
# Perform HTTP GET request on a non-SSL web
response = urequests.get(url)
# Check if the request was successful
if response.status_code == 200:
# Parse the JSON response
data = ujson.loads(response.text)
temp = data["results"][0]["now"]["temperature"]
# Clear the OLED display
oled.fill(0)
# Display the New York date and time on separate lines
oled.text("R T :%0.2fC" % sensor.temperature, 0, 10)
oled.text("A T : %0.2fC" % float(temp), 0, 20)
oled.text("Humi:%0.2f%%" % sensor.relative_humidity, 0, 30)
oled.text("City:ChangSha" , 0, 40)
oled.show() # Show the text
else:
oled.text("Failed to get the time for Changsha",0,0)
# Update the display
oled.show()
time.sleep(10)
功能展示:
心得建议:第一次玩api,获取信息并显示出来,太酷啦
任务6:将esp32作为一个ros节点,控制ros外设
任务介绍:近期正好在研究ros,再加上esp32有的WiFi功能,于是想用esp作为一个jros节点,在主机端通过wifi控制esp32的外设。目前绝大部分机器人是无线连接,如果想要控制mcu就要通过无线的方式。可应用在智能家居与家居机器人的融合领域。由于micropython中没找到ros库,所以这个任务将使用vscode+platformio完成。
主要代码:
导入头文件并进行ros节点的初始化
#include <WiFi.h>
#include <ros.h>
#include <std_msgs/String.h>
// define relay_pin according to pin diagram
#define relay_pin D10
// connect setting
const char* ssid = "WiFi名称";//需要和ros主机在同一WiFi下
const char* password = "密码";
// Set the rosserial socket server IP address
IPAddress server(192,168,3,33);//ros主机的ip地址,用逗号分隔
// Set the rosserial socket server port
const uint16_t serverPort = 11411;
// Ros setting
ros::NodeHandle nh;
// Make a chatter publisher
std_msgs::String str_msg;
// node name: esp32relay
ros::Publisher chatter("esp32relay", &str_msg);
主函数,如果ros主机订阅esp32节点,则将10io口设为高电平,否则设为低电平
void loop() {
if (nh.connected()) {
Serial.println("Connected");
digitalWrite(relay_pin, HIGH);
delay(1000);
} else {
Serial.println("Not Connected");
digitalWrite(relay_pin, LOW);
delay(1000);
}
nh.spinOnce();
// Loop exproximativly at 1Hz
delay(1000);
}
此外还需要ros端安装相关依赖
sudo apt-get install ros-${ROS_DISTRO}-rosserial-arduino
sudo apt-get install ros-${ROS_DISTRO}-rosserial
然后在该1功能包下新建launch文件夹,在launch文件夹下创建esprelay.launch这个启动文件,输入以下代码
<launch>
<node name="rosserial_python" pkg="serial_node.py" type="serial_node" output="screen">
<param name="port" value="tcp" />
</node>
</launch>
最后打开ros主机终端,输入以下命令
roslaunch rosserial_python esprelay.launch
功能展示:
成功控制继电器打开了风扇
说明:ros端使用的是Ubuntu18.04 Ros版本是Melodic
心得建议:使用了与MQTT完全不同的方式,成功使用ros注册节点无线控制外设
第三部分:
可编译下载的代码:源码
|