Page 1 of 1

ATTINY2313 PWM

Posted: Sat Feb 06, 2010 10:10 am
by Focus_Torn
Have been lurking here for a while and think this forum is great, so I figured I would try my hand at asking for some help.

I am using an ATTINY2313, and have the ICP working fine using:
Code: Select all
#include <avr/io.h>
#include <avr/interrupt.h>

#define READ(port,pin) (PIN ## port & (1<<pin)) 
#define INPUT(port,pin) DDR ## port &= ~(1<<pin)
#define OUTPUT(port,pin) DDR ## port |= (1<<pin)
#define CLEAR(port,pin) PORT ## port &= ~(1<<pin)
#define SET(port,pin) PORT ## port |= (1<<pin)
#define TOGGLE(port,pin) PORT ## port ^= (1<<pin)

	volatile unsigned int pWidth;
	volatile unsigned int pStart;
	volatile unsigned int pStop;

int main (void)
{
	INPUT(D,6);	// Input Capture Pin set as input
	SET(D,6);	// Enable pull-up resistor

	OUTPUT(B,0);	// Declare PB0 as output

	TCCR1B = (1<<CS11);	// Set prescaler to 8
	TCCR1B |= (1<<ICES1);	// Input capture in rising edge
	TIMSK = (1<<ICIE1);	// Enable Input Capture interrupt

	pWidth = 1500;

	while(1)
	{
		sei();
		if(pWidth <= 1470)
		{
			PORTB |= (1<<PB0);
		}
		else
		{
			PORTB &= ~(1<<PB0); 
		}
	}
}

ISR(TIMER1_CAPT_vect)
{

	PORTB ^= (1<<PB0);
    pStop = ICR1;
    if (TCCR1B & (1<<ICES1))
	{
        TCCR1B &= ~(1<<ICES1);
        pStart = pStop;
    }
	else
	{
        TCCR1B |= (1<<ICES1);
        pWidth = pStop - pStart;
    } 
}
I am wondering if I am searching for the holy grail by trying to incorporate a PWM output to an LED on the same timer? Or maybe I can not wrap my head around what needs to be done.

Is this even possible? If it is, what am I looking to do?

Is the code ok for what I am wanting or am I registers that are inhibiting the PWM out?

Ending result is to have one PWM being read on Timer0, one PWM being read on the ICP and to have the ICP PWM decide what duty cycle to be used for a PWM output.

Please show me the light. :D

Re: ATTINY2313 PWM

Posted: Tue Mar 02, 2010 3:36 pm
by bugtraker
Before we'll get to the solution, could you clarify what you're trying to do (I know about 2xPWM and timer etc.)?
For now:
- sei() should not be called all the time in while(1) loop (should be called before the loop)
- You toogle the pin in while(1) loop and then you toogle the same pin in ISR context

Please clarify.