counter analog


can someone tell me how to do counter in analog sensor? i am using photoresistor, i want count how many times it get blocked, but seem like in my code, it keep counting when it get blocking. what i want is like button (so it counted when it pressed and when it get blocking = 1, not keep counting)

#include <TimedAction.h>
int potPin = 0;    // select the input pin for the photoresistor
int ledPin = 13;   // select the pin for the LED
int val = 0;       // variable to store the value coming from the sensor
int currVal =0;
int valShadow = 0;

TimedAction resetAction = TimedAction(5000,resetShadowCount);
TimedAction updateShadowAction = TimedAction(500,updateShadow);

void setup() {
  Serial.begin(9600); // get value 
  pinMode(ledPin, OUTPUT);  // declare the ledPin as an OUTPUT

void loop() {

void resetShadowCount(){
  //valShadow += currVal;
  Serial.print("Your shadow is ");
  Serial.println(" times");
  currVal = 0;
  valShadow = 0;

void updateShadow(){
  val = analogRead(potPin);
  if (val < 300){
    currVal = 1;
  //while (val < 350){
  //  currVal != 1;
  valShadow += currVal;
if (val < 300){
    currVal = 1;

I think you need to set “currVal = 0” if “val >= 300”,

otherwise, you only reset it every five seconds.

Maybe lose the “return” in there too?


yes, actually i want to count it in estimation time (5 sec, how many it get blocked) but seem like the response from photoresistor is not fast enough and when i keep blocking it keep counting. what i really want to do is when i block, it counted as 1 even if i keep blocking, after unblock and block again it counted++ as 2 and so on.

Sounds like you just need to watch the pin until the state changes back.

Just a simple while loop when you detect it is blocked that waits until it is unblocked. If you don't want to block your whole program, you can set a flag that says it is blocked and not increment your counter unless the flag says it isn't blocked.