Issues porting capacitive touch code from Arduino to avr

I'm trying to port GreatScott's capacitive touch code to avr. From my understanding the timer is constantly generating a pulse via the TIMER1_COMPA interrupt and the circuit works when I test it through Arduino IDE but I've hit a roadblock. When trying to port the code the circuit doesn't work at all and if it does work it's very unreliable. I've managed to pinpoint the issue being in the ISR(TIMER1_COMPA_vect) method. Here's the main body code which is pretty much identical in both implementations

unsigned long value;
uint8_t outputstate = 0;

void setup()
    TCCR1A = 0;
    TCCR1B = (1 << ICES1) | (1 << WGM12) | (1 << CS10);

    OCR1A = 8000;
    TIMSK1 = (1 << OCIE1A);
    ACSR = (1 << ACI) | (1 << ACIE) | (1 << ACIS1) | (1 << ACIS0);

    DDRB |= (1 << DDB4);

void loop()
    if (value > 1000)
        outputstate = -1;
        outputstate = 0;

    if (outputstate)
        PORTB |= (1 << DDB4);
        PORTB &= ~(1 << DDB4);


    value = TCNT1;

The only real differences exist in the following method.

    pinMode(8, OUTPUT);
    digitalWrite(8, HIGH);
    pinMode(8, INPUT);

    DDRB |= 1;
    PORTB |= 1;
    DDRB &= ~1;
    PORTB &= ~1;

Now, I cannot figure out for the life of me why my implementation gives me a different result than the arduino code. Any help would be appreciated. Website

Which Arduino did GreatScott use ?

Because the time take between driving pin 8 high and making it an input is very different perhaps? digitalWrite and pinMode have overheads of several microseconds each, whereas the time between

    PORTB |= 1;


    DDRB &= ~1;

is a small fraction of a ┬Ás as there is almost no overhead, just direct register bit flips. Thus the pulse on the pin lasts a tiny fraction of the time compared to the Arduino code. An explicit delay is needed to define the pulse width.

Note: In the 'avr' version, cli() and sei() are NOT needed in an ISR.

aren't most Arduinos AVRs ?
What specific AVR are you using. (and what are you porting from, but someone asked already.)

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.