Need help fixing code for Candy Dispenser

I am making a candy dispenser, which has a servo motor, a red, yellow , and green LED, and a button running off of an Arduino Uno. When the button is pressed, the red LED should flash, then the servo should dispense the candy, then the yellow LED will flash. After that, the green LED will turn on signifying that the candy is ready to be collected. The servo dispenses candy by turning a rod, which will dump the candy, from a cup attached to the rod, down a chute, and into the receiving area. When I uploaded the code, the red LED would flash repeatedly, and the servo would move around, even though it wasn’t supposed to.


#include <Servo.h>

Servo myServo;
const int greenLED = 4;
const int yellowLED = 5;
const int redLED = 6;
const int button = 10;
int buttonState = 0;
const int ledDelay = 2000;
int buttonPressed = 0;

void setup()
pinMode(greenLED, OUTPUT);
pinMode(yellowLED, OUTPUT);
pinMode(redLED, OUTPUT);

void loop()
buttonState = digitalRead(button);

if (buttonState == HIGH)
buttonPressed = 1;
buttonPressed = 0;

if (buttonPressed == 1)
digitalWrite(redLED, HIGH);
delay(ledDelay / 2);
digitalWrite(redLED, LOW);
digitalWrite(yellowLED, HIGH);
digitalWrite(yellowLED, LOW);
digitalWrite(greenLED, HIGH);
delay(ledDelay * 2);
digitalWrite(greenLED, LOW);
buttonPressed = 0;

Any help would be appreciated :slight_smile:

How have you got the buttons wired up? It sounds like they may be floating.

I think your code is basically OK. I suspect it's the way you have connected your button. I'm just guessing but I assume you have your button has one side connected to pin 10 and the other side connected to 5v. Am I correct.

Now what you also want to do is have a "pulldown resistor" connected from pin 10 to the GND pin. Otherwise, when your button is not being pressed, pin 10 is left "floating". (it's not connected to anything). In this state it quite often causes false positives on the digitalRead function.

An alternative is to use the button in an ACTIVE LOW type configuration. To configure your button for this you connect one side of the button, to GND and the other side to pin 10. Then in your setup, you would have pinMode(button, INPUT_PULLUP); This allows the arduino to use it's own pullup resistor. And you'd also have to change the logic of your sketch. The first line of your loop would then read something like

Thank you both for the helpful advice!
My dispenser is working great now!

Thank you both for the helpful advice!
My dispenser is working great now!

Aww. That's not fair, you need to tell us what was wrong with it.