Electrical – Attiny not working after ADC conversion

adcavr

I am trying to get a simple IR sensor to work on my an attiny85. To do this I first wrote some code to setup the ADC and the perform an operation based on the outcome. Because the code didn't function as expected I decided to test if some code where I simply do one ADC conversion and then turn on an LED works.
This did however not work. The cause of this seems to be that the attiny stops executing code after the ADC conversion.
I am running the attiny at internal 8Mhz clock and the ADC is hooked up to ground through a 200 ohm resistor.

The following code does not turn on the pin at PB0:

#include <avr/io.h>
#include <util/delay.h>

int main(void) {

DDRB |= _BV(DDB0); //set PB0 to output

ADMUX = _BV(ADLAR) | _BV(MUX1); //set ADC 2, left adjust result
ADCSRA = _BV(ADPS1) | _BV(ADPS2); //prescaler 64
ADCSRA |= _BV(ADEN); //enable ADC

while(1) {

    ADCSRA |= _BV(ADSC); //start conversion
    while (ADCSRA & _BV(ADSC)); //wait for conversion to end
    uint8_t adc_result = ADCH; //adc results (should be 0)

    PORTB |= _BV(PORTB0); //set PB0 to high


}

return(0);
}

When I, however, put the "PORTB |= _BV(PORTB0);" line at the start of the loop, so before the ADC conversion, the line does execute and the LED at PB0 does turn on.

Also commenting out the line "ADCSRA |= _BV(ADSC);" makes the code run fine and makes PB0 go high. So I am pretty certain that the attiny somehow crashes when executing that line.

Disabling interrupts using "cli()" does not solve the problem either.

Best Answer

I do not have any Attiny85 but I used your code and I write it to Attiny13.

The code I used:

#include <avr/io.h>

uint8_t adc_result = 0;

int main( void ) {

    DDRB |= ( 1 << DDB0 ); //set PB0 to output
    ADMUX  |= ( 1 << ADLAR ) | ( 1 << MUX1 ); //set ADC 2 (PB4), left adjust result
    ADCSRA |= ( 1 << ADEN ); //enable ADC
    ADCSRA |= ( 1 << ADPS1 ) | ( 1 << ADPS2 ); //prescaler 64

    while ( 1 ) {

        ADCSRA |= ( 1 << ADSC ); //start conversion

        while ( ADCSRA & ( 1 << ADSC ) );//wait for conversion to end

        adc_result = ADCH; //adc results (should be 0)

        PORTB ^= ( 1 << PB0 ); //Toggle LED at PB0 

    }

    return( 0 );
}   

As you can see I slightly modified the code because My C compilers do not recognize _BV macro so, I replace it with (1 << x) instead. And I also Toggle the led (PB0).

And the signal at PB0 pin looks like this:

enter image description here

Notice the signal frequency is around 5.2MHz.

So it's is very interesting why this code don't work at attiny85.