counter not counting

Post here about your Arduino projects, get help - for Adafruit customers!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
keithg
 
Posts: 82
Joined: Thu Oct 30, 2008 8:30 pm

counter not counting

Post by keithg »

This sketch is intended to run a dc motor between two optointerrupters and stop after 5 passes. Why is the counter not counting? The serial monitor shows nothing but "0".


Code: Select all

int opto1 = 4;
int opto2 = 5;
int motor1 = 9;
int motor2 = 6;
int enable = 8;
int val1;
int val2;
int counter= 0;
int previousVal1 = LOW;
int previousVal2 = LOW; 

void setup() {
 counter = 0; 
 pinMode(opto1,INPUT);
 pinMode(opto2,INPUT);
 pinMode(motor1,OUTPUT);
 pinMode(motor2,OUTPUT);

pinMode(enable,OUTPUT);
digitalWrite(motor1,HIGH);
Serial.begin(9600);
    
}

void loop() {
  counter = 1;
  
 digitalWrite(enable,HIGH);
 val1 = digitalRead(opto1);
 val2 = digitalRead(opto2);
 
if(val1 == HIGH && previousVal1 == LOW)
{
   digitalWrite(motor1,HIGH);
   digitalWrite(motor2,LOW);
   counter = counter +1;
}
previousVal1 = val1;
  
// }
 
if(val2 == HIGH && previousVal2 == LOW)
{
   digitalWrite(motor1,HIGH);
   digitalWrite(motor2,LOW);
   counter = counter +1;
}
previousVal2 = val2;
  
 //}
 
if(counter >5){
  
   digitalWrite(motor1,LOW);
   digitalWrite(motor2,LOW);
   
}
Serial.println(counter);
 }   


arielariel
 
Posts: 10
Joined: Fri Dec 04, 2009 9:22 am

Re: counter not counting

Post by arielariel »

I am still learning this myself, but what I would try to do while you wait for the experts is to put yourself in a lot more serial printouts so you can see which parts of the program are and aren't getting executed.

ie, have it print you out the value of counter @ the beginning of the loop and then at the bottom of each if statement (ie, "Switch one was thrown; counter is now xx").

I think there is something funny going on with how you are modifying the counter, but I don't know enough to really pick it apart. Are you sure the circuitry is actually working for your inputs?

keithg
 
Posts: 82
Joined: Thu Oct 30, 2008 8:30 pm

Re: counter not counting

Post by keithg »

Thanks. I will try the serial monitor and look at the results.

User avatar
ahdavidson
 
Posts: 131
Joined: Wed Jun 03, 2009 9:59 am

Re: counter not counting

Post by ahdavidson »

The code in the setup() function in an Arduino sketch is executed once, when the sketch starts (when the Arduino is reset).

The code in the loop() function is continuously executed, over and over again, as fast as the processor can go.

The first statement in your loop() function assigns the value 1 to counter, so every time through the loop, you are resetting it to 1. Thus it will never become greater than 5.

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino”