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

  1. cd grove.py
  2. nano lesson_2.py

Step 2: Copy the following code

  1. #!/usr/bin/env python
  2.  
  3. import time
  4. from mraa import getGpioLookup
  5. from upm import pyupm_buzzer as upmBuzzer
  6.  
  7. from grove.button import Button
  8. from grove.grove_ryb_led_button import GroveLedButton
  9.  
  10. def main():
  11. # Grove - LED Button connected to port D5
  12. button = GroveLedButton(5)
  13.  
  14. # Grove - Buzzer connected to PWM port
  15. buzzer = upmBuzzer.Buzzer(getGpioLookup('GPIO12'))
  16.  
  17. def on_event(index, event, tm):
  18. if event & Button.EV_SINGLE_CLICK:
  19. print('single click')
  20. button.led.light(True)
  21. buzzer.playSound(upmBuzzer.BUZZER_DO, 500000)
  22.  
  23. elif event & Button.EV_LONG_PRESS:
  24. print('long press')
  25. button.led.light(False)
  26. buzzer.playSound(upmBuzzer.BUZZER_DO, 1000000)
  27.  
  28. button.on_event = on_event
  29.  
  30. while True:
  31. time.sleep(1)
  32.  
  33. if __name__ === '__main__':
  34. main()

Step 3:Uruchomprogram

  1. sudo chmod +x lesson_2.py
  2. 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.

  1. pi@raspberrypi:~/grove.py $ sudo ./lesson_2.py
  2. single click
  3. single click
  4. single click
  5. long press
  6. single click
  7. long press
  8. long press
  9. Traceback (most recent call last):
  10. File "./lesson2.py", line 34, in
  11. main()
  12. File "./lesson2.py", line 31, in main
  13. time.sleep(1)
  14. KeyboardInterrupt
  15. ^Araspberrypipe: ~/grove.

Table of contents

Botland.store - shop for makers!