Lesson 2: Button with red LED
Objective
Using the Grove - a button with a red LED to control the LED flashing and to allow the buzzer to generate various sound effects.
Hardware requirement
Prepare:
- microUSB cable
- Raspberry Pi 3 Model B
- Computer
Included in the set
- Grove Base Hat
- Grove wire
- Grove - button with red LED
- Grove - Buzzer
Connecting equipment
Step 1: Use the Grove cable to connect the Grove-Buzzer to the PWM port and the Grove-Buzzer to the red LED button to D5 on the Base Hat, and put an overlay on the Raspberry Pi.
Step 2: Connect the Raspberry Pi to the power source using the microUSB cable.
Programming
Step 1: Enter the following commands to create a Python file
- cd grove.py
- nano lesson_2.py
Step 2: Copy the following code
- #!/usr/bin/env python
- import time
- from mraa import getGpioLookup
- from upm import pyupm_buzzer as upmBuzzer
- from grove.button import Button
- from grove.grove_ryb_led_button import GroveLedButton
- def main():
- # Grove - LED Button connected to port D5
- button = GroveLedButton(5)
- # Grove - Buzzer connected to PWM port
- buzzer = upmBuzzer.Buzzer(getGpioLookup('GPIO12'))
- def on_event(index, event, tm):
- if event & Button.EV_SINGLE_CLICK:
- print('single click')
- button.led.light(True)
- buzzer.playSound(upmBuzzer.BUZZER_DO, 500000)
- elif event & Button.EV_LONG_PRESS:
- print('long press')
- button.led.light(False)
- buzzer.playSound(upmBuzzer.BUZZER_DO, 1000000)
- button.on_event = on_event
- while True:
- time.sleep(1)
- if __name__ === '__main__':
- main()
Step 3:Uruchomprogram
- sudo chmod +x lesson_2.py
- sudo ./lesson_2.py
Success If everything goes well, you will see that when you press the button for a long time, the LED will go out and the buzzer will give a long "Do" sound. If you press the button once, the LED will light up and the buzzer will give a short "Do" sound. |
- pi@raspberrypi:~/grove.py $ sudo ./lesson_2.py
- single click
- single click
- single click
- long press
- single click
- long press
- long press
- Traceback (most recent call last):
- File "./lesson2.py", line 34, in
main() File "./lesson2.py", line 31, in main time.sleep(1) KeyboardInterrupt ^Araspberrypipe: ~/grove.