How to use a Tricolor LED and a Mini Buzzer

Circuit

The circuit consists of a push button switch, a tricolor LED, mini buzzer and a couple of resistors. Here are the parts list:

  • 1 Tricolor LED (common anode)
  • 1 Push Button Switch
  • 1 Mini Buzzer
  • 5 330 ohms resistor

In this example, we are using pins 9, 10 and 11 to control the tricolor LED. Since our LED is common anode which means that to show a specific color with full brightness, we will send 0 to the corresponding pin and 255 to remove the color. For example, if we want to display red, then we need to set pin 9 to 0 and set 255 to pins 10 and 11. To display green, we need to set pins 9 and 11 to 255 and pin 10 to 0.

Pin 12 will be used to send tone to our piezoelectric speaker or buzzer while pin 2 will be used to detect if our mini switch has been pressed or not. So in summary:

The 3 resistors in series with the 3 legs of our tricolor LED is needed to limit the current that flows thus preventing the LED from being burned.

The resistor connected to the one pin of the push button switch serves as a pull down resistor. This is needed so that at normal position, pin 2 will read a zero input because it is directly grounded. When you push the switch, pin 2 will be logic 1 because the voltage from Vcc of Arduino in series with pin 2.

Sketch

In our setup function:

We set pin 2 as input then we initialize our serial communication and send a broadcast to our android device. All PWM pins are by default output pins so we don’t need to initialize them here.

Here’s our loop function:

Here’s we are randomly generating the value for the end of our loop as well as the increment to mimic the random delays caused by friction in a real roulette game. Then for each iteration, we loop through the 3 colors and send them to the android device for display. The tone() produces the sound for our buzzer. It sends an 8th note 900hz on pin 12 to produce our clicking sound. Once the for loop exits, we need to inform our device that the random selection is done and needs to check whether the user wins or not.

And here are the functions referenced from the loop function:

And in our handler, we set the corresponding color to our view’s background based  on the value we receive from the accessory and once we received the signal that the random selection has ended, we then check if the user’s selected color matches the last color that has been sent to the device.