如何在MicroPython的Pi Pico上实现按钮循环切换城市选项
实现Raspberry Pi Pico按钮循环切换城市并获取时间温度
核心修改思路
- 给按钮添加单次单击触发逻辑,避免重复触发
- 维护一个当前选中的城市索引,每次单击后循环更新索引
- 集成API调用逻辑,切换城市后自动获取对应数据
修改后的完整代码
import machine import time import urequests import json # 1. 定义11个预定义的城市/国家(可替换为适配目标API的参数格式) locations = [ "Beijing,CN", "Shanghai,CN", "Guangzhou,CN", "Shenzhen,CN", "London,UK", "New York,US", "Tokyo,JP", "Seoul,KR", "Paris,FR", "Berlin,DE", "Sydney,AU" ] # 2. 初始化按钮和状态变量 button = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP) current_index = 0 # 当前选中的城市索引 last_button_state = 1 # 记录上一次按钮状态,初始为高电平(未按下) api_key = "你的API密钥" # 替换为实际使用的API密钥 # 3. 定义获取天气和时间的函数 def get_location_data(location): # 示例使用OpenWeatherMap API,可替换为你实际使用的接口 url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}&units=metric" try: response = urequests.get(url) data = json.loads(response.text) response.close() # 提取温度和当地时间(根据API返回结构调整) temperature = data["main"]["temp"] utc_time = time.time() timezone_offset = data["timezone"] # API返回的时区偏移(秒) local_time = utc_time + timezone_offset local_time_str = time.localtime(local_time) return f"地点: {location}\n温度: {temperature}°C\n当地时间: {local_time_str[0]}-{local_time_str[1]}-{local_time_str[2]} {local_time_str[3]}:{local_time_str[4]}" except Exception as e: return f"获取数据失败: {str(e)}" # 4. 主循环 print(f"当前选中: {locations[current_index]}") print(get_location_data(locations[current_index])) while True: current_button_state = button.value() time.sleep(0.01) # 防抖延时 # 检测按钮单次按下(从高到低的跳变) if last_button_state == 1 and current_button_state == 0: # 更新索引,循环切换 current_index += 1 if current_index >= len(locations): current_index = 0 # 打印当前选中的地点并获取数据 print("\n--- 切换地点 ---") print(f"当前选中: {locations[current_index]}") print(get_location_data(locations[current_index])) # 等待按钮释放,避免重复触发 while button.value() == 0: time.sleep(0.01) last_button_state = current_button_state
关键部分解释
- 按钮单击检测:通过记录
last_button_state,仅在按钮从松开(高电平)变为按下(低电平)时触发一次切换,同时等待按钮释放,避免长按多次触发。 - 循环索引:每次单击后
current_index自增,当超过列表长度时重置为0,实现11个地点的循环切换。 - API调用:使用
urequests库发送HTTP请求,解析JSON数据提取温度和时间,需根据实际使用的API调整URL和数据提取逻辑。
注意事项
- 确保Pico已连接网络(Pico W可直接用内置WiFi,普通Pico需外接WiFi模块)。
- 若使用Pico W,需提前添加WiFi连接代码(初始化并连接到热点)。
内容的提问来源于stack exchange,提问作者thelivingJoJo's reference
相关产品推荐
相关产品推荐

