I am relatively new to C++ coding. Recently we were given an assignment to connect an Arduino uno to a photoresistor and code it as a counter. We put 5V to a photoresistor with a wire leading to an analog pin, followed by a 10K ohm resistor going back to ground. The code itself wasn't too tricky, but it miscounts. If you keep your hand over the resistor it continues to count. Any tips to eliminate this problem and also do away with the delay?
Code:
/*
Photoresistor object detector.
Detect when an object blocks light to a photoresistor, and count
the number of times this happened.
The circuit:
* Photoresistor voltage divider connected to analog pin 0.
*/
// These constants won't change. They're used to give names
// to the pins used:
const int analogInPin = A0; // Analog pin the sensor is connected to
int sensorValue = 0; // Value of the sensor reading (0 to 1023)
int count = 0; // Number of times an object blocked the light
void setup() {
Serial.begin(9600); // initialize serial communications at 9600 bps
}
void loop() { // read the analog in value.
sensorValue = analogRead(analogInPin); // Recieve the sensor value
if (sensorValue < 750) { //
count = count + 1; // Increment the count
Serial.println(count); // Print the count and go to the next line
}
delay(100); //
}