Use the ATtiny84 ADC0 pin as both input and output

attinyavr

I am using the ADC0 (PA0) pin of an Attiny84 to read analog values from an audio circuit. This part is working fine. Since I need to connect the Attiny84 to 8 LEDs, I'd like to use the ADC0 pin as an output also.

Here is the schematic:

schematic

simulate this circuit – Schematic created using CircuitLab

But this doesn't work. The LEDs don't light up. (They are turned on based on ADC0 values read in.)

Does this have something to do with enabling pull-ups?

Or is it not possible to switch ADC0 between input and output?

Here is the code:

// set pin as input
DDRA &= ~(1 << PA0);

// unset DIDR0
DIDR0 &= (1 << ADC0D);

// enable ADC
ADCSRA |= (1 << ADEN);

// start conversion
ADCSRA |= (1 << ADSC);
// loop till done
while(ADCSRA & (1 << ADSC));

// use h/l regs
unsigned char adcl = ADCL;
unsigned char adch = ADCH;
int result = (adch << 8) | adcl; 

// set DIDR0
DIDR0 |= ~(1 << ADC0D);

// set pin as output
DDRA |= (1 << PA0);

// switch LED on
PORTA |= (1 << PA0);

// switch other LEDs on which have been set as output
//...
PORTA |= (1 << PA1); 

The above code is being called from the 8-bit timer overflow interrupt handler. The timer is setup from main() as follows:

// set 8-bit timer
  cli();

  // set prescaler to 256
  TCCR0B |= (1 << CS02);
  // set overflow interrupt enable
  TIMSK0 |= (1 << TOIE0);

  sei(); 

Best Answer

There is a battle between the LM358 and the MCU pin so if the LM358 wins and it wants to output a fairly low voltage then the LED won't light up no matter how hard you try. I think a possible solution is to put a resistor (maybe 470 ohms) in series with the LM358 output. This will allow PA0 to win every time but the problem arises when the port is being used as an analogue input - will the LED and resistor affect the analogue voltage?

I'm not sure what voltage range you are using for your analogue input but if it's 1V maximum then you should be OK. Maybe OK even at 2V but above two volts the LM358 will be trying to drive the LED and losing voltage thru the 470 ohms I recommended you put in series originally.

If the Vmax for the ADC is less than 2V it should be OK and also add a 10nF cap down to ground on the input to reduce impedance increases from the 470 ohm resistor.