In pseudocode I want to do following:
i = 0
state = 0
while (1):
compareState = readDigitalIn()
if state == compareState:
i = i+1
else:
i = 0
state = compareState
writeDigitalOut(dataVector[i])
In english, I want to reset the counter i every time I change the state of digitalIn-pin.
Is the above a good way of doing this? Does attiny have event listeners or similar?
The ultimate goal is to synchronize multiple pwm controllers in different chips (writeDigitalOut is changed to AdjustPwmFrequency…)
Edit: Can I use interrupts for this? How? Can create an interrupt that fires when digitalIn-pin is changed?
Best Answer
Yes, this is a pretty good application to use interrupts for.
What you are interested in is the external interrupt, but let's break down the general structure of an interrupt first.
If you have enabled a particular interrupt on your system, when that interrupt type occurs, the processor will look up into a table to find the function or service routine to jump to in order to service that particular event.
This function is called an Interrupt Service Routine, or ISR for short. This is a method that you must write.
So let's identify which interrupt you want and which ISR you want to write. To do this, we need to consult the datasheet. The type of interrupt that you're interested in is in the family of interrupts called external interrupts. An excerpt from the ATiny45 datasheet:
So they've mentioned some registers of interest here:
PCMSK
andMCUCR
PCMSK
controls which pins can trigger the interrupt - so you want to wire up your toggling signal to whichever pin(s) you specify here, andMCUCR
defines how the pins must change in order to trigger the interrupt. In this case, you would probably be interested in configuring your interrupt forAny logical change on INT0 generates an interrupt request.
As outlined in table 9-2 in the document. Continue reading what the registers do in the external interrupt section, they are as follows:MCUCR
,GIMSK
,GIFR
,PCMSK
. The information you want to get out of this isPCMSK
andMCUCR
)GIMSK
)GIFR
)Now on to the actual coding. The structure will look something like this (pseudo code):
Now whenever a pin change occurs on one of the pins you specified (given that you've set-up all the registers correctly), the
ISR(PCINT0_ISR)
routine will be executed.So how did I know to use
ISR(PCINT0_ISR)
? You will need to lookup in whatever definitions file that you are using to see if they have provided thePCINT0_ISR
mapping for you, if not, consult the datasheet again and look at section9.1 Interrupt Vectors in ATtiny25/45/8
and define it yourself. If you are using avr-gcc, theISR()
macro is defined here.I think this covers the basics without giving away too much code. Good luck and have fun!