Thanks a lot for your continued help!
ve tried to put in the new de-bounce code provided by alnath but something still isnt correct. Pressing the tactile switch for “coin in” starts the relay and hopper but then it only dispenses a couple of coins and goes off.
I just want to confirm - I am no longer using a button to replicate the pulses but the actual hopper itself which sends a pulse each coin dispenced. The relay is active LOW.
I am using a standard tactile switch to initiate the hopper into action which momentarily goes HIGH when pressed- this switch replicated a £1 coin entering the machine and initiating the dispensing of coins.
Code so far:
int CoinButton_pin = 2;
int Relay_pin = 13;
int optical_pin = 3;
unsigned long start_time ;
unsigned long critical_time = 500 ; //maybe it is a bit too long
byte flag_alarm = 0 ; // alarm flag
int coinCounter = 0; // this is variable used to count the coins until 10
digitalWrite(Relay_pin, HIGH); //turn off relay on startup
if (digitalRead(CoinButton_pin) == 1) //Coin inserted - button goes high (currently a push switch)
digitalWrite(Relay_pin,LOW); //Turn on relay - active low.
while(coinCounter < 10)
if(digitalRead(optical_pin) == HIGH ) //if the optical pin goes high
start_time = millis();
coinCounter+=1; // add one to counter
while(digitalRead(optical_pin) == HIGH)
if((millis() - start_time) > critical_time) // something is wrong
flag_alarm = 1; // you can use the flag to launch an alarm …
break; // get out of there
} //end of while coin counter loop - i.e 10 coins dispenced
} // end of coin button if sttatement
coinCounter = 0;
if(flag_alarm == 1 )
// alarm or … NOTHING YET BUT I SEE ITS USE
} // end void loop
Any more help would be much appreciated. As I say, pressing the tactile switch starts the hopper but instead on waiting for 10 pulses, it just goes off after a sort delay - 1 or 2 coins being dispensed.
I do not see anywhere in your code where you are counting the pulses in from the Hopper ? Do you know what it is sending ? i.e. is it just raising a 5v signal or is it a proper pulse signal that you need to capture ?
How have you connected the hopper in ? Just straight into a digital pin ?
I would suggest you remove it to start with an emulate it with a push button until you can get your code right, once you have that you can then introduce the hopper back in.