Im trying to control a solenoid and a servo motor. the servo motor will activate when a total of 20 pulses is received and the solenoid will activate every time 4 pulses are detected. it works fine if I start with the coin that equal 4 pulses but it I start with a coin that equals 10 pulses or 20 the servo will activate but then she solenoid won’t work again.
#include <Servo.h>
int solenoidPin = 7; //This is the output pin on the Arduino we
// Constants
const int coinpin = 2;
const int targetcents =20 ;
int servoPin = 9;
Servo servo;
int angle = 0; // servo position in degrees
float metal, metall;
int reading;
int metalPin = A0;
int metalPinn = A1;
// Variables
volatile int pulse = 0;
volatile int pulsee = 0;
int pesos = 0;
// Setup
void setup() {
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(coinpin), coinInterrupt, RISING);
// Servo motor///////
servo.attach(servoPin);
// put your setup code here, to run once:
pinMode(solenoidPin, OUTPUT); //Sets the pin as an output
}
// Main loop
void loop() {
reading = analogRead(metalPin);
metal = (float)reading*100/1024.0;
Serial.print("Metal in Proximity = ");
Serial.println(metal);
reading = analogRead(metalPinn);
metall = (float)reading;
Serial.print("Metall in Proximity = ");
Serial.println(metall);
if (pulse >= targetcents) {
pesos = pesos+1;
pulse = pulse - targetcents;
}
delay(10);
switch(pulsee){
case 1:
pulsee=0;
break;
case 4:
digitalWrite(solenoidPin, HIGH); //Switch Solenoid ON
delay(100); //Wait 1 Second
digitalWrite(solenoidPin, LOW); //Switch Solenoid OFF
delay(100); //Wait 1 Second
pulsee=0;
Serial.print(pulsee);
Serial.println("4 pulsossssssssssssssssssssssssssssssssssssssssssss");
delay(10);
break;
}
if (pulse==2) {
pesos=1;
}
Serial.print(pesos);
Serial.println(" Pesos insertados");
delay(10);
if (pulse==4) {
pesos=2;
}
Serial.print(pesos);
Serial.println(" Pesos insertados");
delay(10);
if (pulse==10) {
pesos=5;
}
Serial.print(pesos);
Serial.println(" Pesos insertados");
delay(10);
delay(1000);
if (pulse==20) {
// scan from 0 to 180 degrees
for(angle = 0; angle < 90; angle++)
{
servo.write(angle);
delay(3);
}
// now scan back from 180 to 0 degrees
for(angle = 90; angle >5; angle--)
{
servo.write(angle);
delay(3);
}
}
}
// Interrupt
void coinInterrupt(){
// Each time a pulse is sent from the coin acceptor, interrupt main loop to add 1 cent and flip on the LED
pulse = pulse + 1;
pulsee=pulsee+1;
}