You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

micro:bit Python编程:添加radio变量ch编译报错求助

Fixing Radio Channel Configuration Error on micro:bit

Hey there, let's sort out why your code is throwing errors when using a variable for the radio channel. The core issue here is the order of your radio commands!

The Problem in Your Code

You're calling radio.on() before setting the channel with radio.config(channel=ch). On the micro:bit, once you turn the radio on, you can't modify its configuration anymore—any attempts to call radio.config() after radio.on() will trigger an error.

Corrected Code

Here's how to adjust your code to make it work:

from microbit import *
import radio

# First set the channel using your variable
ch = 30
# Ensure ch stays within valid micro:bit radio channel range (0-83)
if 0 <= ch <= 83:
    radio.config(channel=ch)
else:
    # Fallback to a safe default if ch is out of bounds
    radio.config(channel=7)

# Now turn the radio on
radio.on()

# Rest of your program logic goes here...

Key Tips to Avoid Future Issues

  • Always run radio.config() before radio.on()—this is a strict rule for the micro:bit radio module.
  • Keep your ch variable within the valid channel range: 0 to 83. Values outside this range will cause another error, so adding a quick check like the if statement above can save you headaches.
  • If you need to change the channel while the program is running, you'll have to cycle the radio off and on again:
    radio.off()
    ch = 45  # Update channel with your external input value
    radio.config(channel=ch)
    radio.on()
    

内容的提问来源于stack exchange,提问作者Edson Sobreira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:11:43