NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » Counting the changes in a pin

July 04, 2012
by lcruz007
lcruz007's Avatar

Hi,

I am trying to make a simple counter for every change (0V-5V) in a pin of the MCU. The variable I am using in my code, however, is NOT incrementing every time the square wave passes from 0V to 5V and vice versa. But instead, whenever there is a change in the pin, the variable is incrementing by hundreds and not just one increment.

Here is my code:

void setup() {

PCMSK1 |= (1<<PCINT10);

PCICR |= (1<<PCIE1);
PCIFR |= (1<<PCIF1);
sei();
}

//How many times does the MCU reads 0V? or 5V?
volatile int changes_low; 
volatile int changes_high; //+5V

ISR(PCINT1_vect)
{

    //If high (5V)
    if( PINC & (1<<PC2)){
      changes_high++;
    }
    else{
     changes_low++;
    }
}

In the main loop I am reading those variables, and sending data over the serial port... Every time the interrupt is triggered, the variables are updated and incremented by 10 or even 100 sometimes. It's supposed to increment by one though....

What am I doing wrong here?

P.S the signal that goes into pin PC2 is a square wave, and it's looking alright on the oscilloscope.

Thanks in advance!

July 04, 2012
by lcruz007
lcruz007's Avatar

By the way, Here's a screenshot of the signal. It's a low frequency and non-periodic square wave coming from an IR sensor.

July 04, 2012
by dgikuljot
dgikuljot's Avatar

The signal changes really fast, so in 1 second the signal can change from high to low even hundreds of times and that is why it is counting is such high increments. Also there is the effect of bouncing. If I am wrong, please correct me someone.

Post a Reply

Please log in to post a reply.

Did you know that an electroluminescent backlight for an LCD panel requires hundreds of volts AC to run? Learn more...