## Timing how long a capacitor takes to discharge

2 posts / 0 new
Author
Message

Hello all,
please bear with me if this is a stupid question, but I'm a newbie. :) This is mostly a hardware issue, but I suppose that there might be some faulty logic in my reasoning too.

Situation: atmega8, a capacitor (let's say 1 µF), two digital I/O pins. I want to be able to time how long it's going to take to discharge it after charging it (or rather, until it reached the threshold for a logic 0).
As a 'display', I have 8 leds connected to PORTD; not very precise, but so far it's been displaying either random things, or just 1 (that is, 00000001).

I am using PB0 and PB1 with the capacitor between them.

Step 1: I set both to output, with PB0 to logic 1 and PB1 to logic 0 to charge the capacitor.
Step 2: I set both to input, with PB0 in tristate (Hi-Z) and PB1 pulled-up internally. This way I'm supposed to be receiving a logic 1 until the capacitor discharges enough, at which point I will get a logic 0.
Step 3: polling PB1 as long as it's at logic 1
Step 4: repeat all

Now, I have been trying to do this all day (alternating thoughts and randomness), also attempting to use an external pull-down resistor to keep PB1 to logic 0 when not in use, connecting the capacitor in other ways, and so on. So far, however, only once I had come to the point of seeing the capacitor discharge (using a voltmeter) but there was certainly some logic flaw because it didn't show the "time" on PORTD.

This is the code I'm trying right now, and it doesn't even charge the capacitor anymore:

```#include

int main(void)
{
int i;
DDRD = 0xff;

DDRB |= (1<<PB0);	// out
while(1)
{
i=0;

DDRB |= (1<<PB1) | (1<<PB0);		// always out

PORTB |=  (1<<PB0);		// on  (+)
PORTB &= ~(1<<PB1);		// off (-)

DDRB &= ~(1<<PB0) & ~(1<<PB1);	// in
PORTB |= 1<<PB1;	// pull up
PORTB &= ~(1<<PB0);	// tristate
do
{
i++;
} while(PINB & (1<<PB1));	// keep incrementing as long as it's charged
PORTD = i;
}
}
```

The MCU is running at 8 MHz using the internal oscillator (I changed the fuses) so there should be plenty of time for it to count and possibly overflow the counter.

As you might have noticed, I'm quite confused about the whole thing. I considered using the ADC, but I just want to see how long it takes until it discharges. I can't even see a practical reason for charging a capacitor and timing how long it takes to discharge it, but it came to mind and it became a challenge. :)

Any hints towards what I'm missing will be greatly, greatly appreciated.

Thank you very much!