Hi everyone,
I have a problem in my project. This project aims that counting pulses from signal generator, but condition is when digital pin 2 and digital pin 3 are "1" at the same time, counter should be increase. Additionally every second count value prints in serial monitor. The problem is counter fails, sometimes gives negative numbers. It can not stabilized.
int count = 0;
int pins;
unsigned long timeAgo = millis();
int SensorPrevTotal= 0;
void setup(){
Serial.begin(9600);
}
void loop()
{
if (millis() - timeAgo >1000 ){
timeAgo = millis();
Serial.println(count);
count =0;
}
pins = PIND;
if(pins ==15){
count = count +1;
}
pins=0;
}
BijendraSingh:
I am running your code on my arduino uno, and it continuously printing 0.
so, instead of using PIND use
pins1 = digitalRead(2);
pins2 = digitalRead(3);
if(pins1 == 1 && pins2 == 2)
count++;
> count should be long in size to avoid overflow
Firstly I tried to use digitalRead(); it is so useful but when i have to count bigger pulses counter lose pulses because of this I think I have to use pin manupulation.
The problem converts this:
I send 10 pulse in every second but I see in serial monitor 36000 - 40000 pulses in every second.
You're reading the port as fast as the Arduino can go so each pulse is being counted many times. You need to only count when there is a change of state.
This is the common case of wanting to count when something changes,
not count everytime you look at something...
You need a variable to remember the previous observation and compare
that to the current observation - otherwise you cannot tell if something has
changed.