I am trying to count the number of breaks an IR sensor has while running a servo motor at the same time and when the number of counts is finished, the servo stops. The code I am using is:
#include <Servo.h>
Servo myservo;
int potpin = 0;
int val;
int currentCount = 0;
int endCount = 1;
#define LEDPIN 13
#define SENSORPIN 4
int sensorState = 0, lastState=0;
void setup() {
// put your setup code here, to run once:
myservo.attach(9);
pinMode(LEDPIN, OUTPUT);
pinMode(SENSORPIN, INPUT);
digitalWrite(SENSORPIN, HIGH);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
sensorState = digitalRead(SENSORPIN);
if (currentCount < endCount) {
Serial.println("Starting Count less than End Count");
val = analogRead(potpin);
val = map(val, 0, 1023, 1000, 2000);
myservo.writeMicroseconds(val);
delay(1500);
if (sensorState && !lastState) {
currentCount = currentCount +1;
Serial.println(currentCount);
}
//if IR Sensor is broken +1 to current count
}
else {
Serial.println("Done Counting " + currentCount);
// stop moving the sensor
val = map(val, 0, 0, 0, 0);
}
}
I am trying to double check by having it print start count and each time the IR breaks the count adds one. Currently the beginning starts out well but once the IR breaks once, this prints out rapidly:
one Counting
one Counting
one Counting
one Counting
one Counting
one Counting
one Counting
one Counting
one Counting
one Counting
one Counting
one Counting
one Counting
one Counting
one Counting
After that it no longer can count anymore. Is it an issue that I used an if else statement? Do you guys have any suggestions? Thank you for the help.