Experiment 6: Reading a Button Press
Introduction
到目前为止,我们主要关注输出。现在我们要走到频谱的另一端,并连同输入一起玩。在实验二中,我们使用模拟输入来读取电位器。在这个实验中,我们将通过使用数字输入来读取最常见和最简单的输入之一 – 按钮。我们将使用它来循环RGB上的不同颜色。
Parts Needed
You will need the following parts:
1x Breadboard
1x micro:bit
1x micro:bit Breakout with Headers
1x RGB LED
3x 100Ω Resistors
8x Jumper Wires
1x Push Button
1x 10kΩ Resistor
Didn’t Get the SIK for micro:bit?
If you are conducting this experiment and didn’t get the Inventor’s Kit, we suggest using these parts:
Suggested Reading
Before continuing with this experiment, we recommend you be somewhat familiar with the concepts in these tutorials:
Introducing the Push Button
瞬时按钮仅在按下时关闭或接通电路。按钮有四个引脚,分成两组两个引脚。当你按下按钮并获得一个很好的“咔嗒”声时,按钮桥接两组引脚,并允许电流流过电路。
How do you know which pins are paired up? The buttons included in this kit will only fit across the breadboard ditch in one direction. Once you get the button pressed firmly into the breadboard (across the ditch), the pins are horizontally paired. The pins toward the top of the breadboard are connected, and the pins toward the button of the breadboard are connected.
你怎么知道哪个引脚配对?此套件中包含的按钮仅适用于一个方向上的面包板沟。一旦将按钮牢固地按入面包板(穿过沟渠),这些引脚就会水平配对。面向面包板顶部的引脚已连接,面向面包板按钮的引脚已连接。
注意:并非所有按钮都共享此引脚格式。请参考您特定按钮的数据表以确定哪些引脚配对。
Hardware Hookup
Ready to start hooking everything up? Check out the wiring diagram and hookup table below to see how everything is connected.
Polarized Components
Pay special attention to the component’s markings indicating how to place it on the breadboard. Polarized components can only be connected to a circuit in one direction.
Wiring Diagram for the Experiment
Having a hard time seeing the circuit? Click on the wiring diagram for a closer look.
Note: The full-sized breadboard
注意:全尺寸的面包板电源导轨有中间断开的情况。如果最终使用电源导轨的下半部分,则需要在上端和下端之间跳转。
Run Your Script
Code to Note
micro:bit上的引脚为低电平有效,这意味着外部按钮应连接到引脚并接地以通过按钮触发事件。这在MicroPython中无法更改,因为它可以在MakeCode中进行更改。我们还发现,MicroPython的中断时间非常困难,并且一次只能运行多个线程。使用MakeCode,可以运行多个线程。
pass
由于中断在MicroPython中非常困难,我们决定使用pass。
pass是一种处理来自while 循环的外部触发器而不影响while 循环的方式。在这种情况下,外部触发器是否按钮已被按下。这是使用中断的一种欺骗手段。我们可以连续检查micro:bit上的引脚16,以查看按钮是否被按下。
iter
iter()_方法创建一个对象,可以一次迭代或增加一个元素,直到指定的结束。在迭代结束时,会引发异常:“StopIteration”。
try and exceptiterator
try和except允许程序捕捉意外(或在这种情况下预期)错误,并处理错误,除非程序员想要。在这种情况下的错误将是iter 函数如何让程序知道它已经超过了最后的可迭代值。iter 方法引发的异常是“StopIteration”。我们正在“尝试”下一个异常,直到意外出现。一旦意外出现,我们退出尝试并移至except,这将再次启动迭代器。
What You Should See
当你按下按钮时,RGB将变成一种颜色。当再次按下时,颜色会改变,而另一次按则会再次改变颜色。再按一次,它会关闭。每次按下按钮,它都会增加一个变量,然后我们检查它以设置颜色。如果变量超过2的值,我们将它重置为0,这是关闭的。
Troubleshooting
Light Not Turning On
按钮是方形的,正因为如此,很容易出错。给它一个90度的扭曲,看看它是否开始工作。
Underwhelmed
别担心;这些电路都是非常精简的,以便轻松玩游戏组件,但一旦将它们放在一起,天空才是极限。不过请记住,这些都是钢铁侠套装的基石。