Setting a timer interrupt on an Arduino Uno R3
I'm looking for sample code for setting a timer interrupt on an Arduino Uno R3.
@scottlu did you ever figure this out?
@scottlu I got this working.
To do it, you have to import the device/avr package and set the values of several registers on your own. I followed this:
https://www.google.com/url?q=https://exploreembedded.com/wiki/AVR_Timer_Interrupts&sa=U&ved=2ahUKEwiopeHmrs74AhV8K0QIHTjUB-8QFnoECAQQAg&usg=AOvVaw2BA6J8R8KUk47fLeIMbvMS
The registers are pretty much named 1-1 with the registers mentioned in the tutorial.
The main difference from the example code is that setting the count to a 16 bit value requires setting the hi and lo (H and L) 8-bit registers, rather than one 16-bit value
Thanks.... looks good.
Sorry for the delay in replying. Here is a Timer1 interrupt example tested on an Arduino Uno with TinyGo 0.44-dev. The onboard LED changes state once per second, and the serial output reports the interrupt count.
Timer0 is left untouched because TinyGo uses it for timekeeping.
package main
import (
"device/avr"
"machine"
"runtime/interrupt"
"runtime/volatile"
"time"
)
var timerTicks volatile.Register8
func timer1Compare(interrupt.Interrupt) {
tick := timerTicks.Get() + 1
timerTicks.Set(tick)
machine.LED.Set(tick&1 != 0)
}
func main() {
machine.LED.Configure(machine.PinConfig{Mode: machine.PinOutput})
machine.LED.Low()
state := interrupt.Disable()
avr.TCCR1A.Set(0)
avr.TCCR1B.Set(0)
avr.TIMSK1.Set(0)
avr.TCNT1H.Set(0)
avr.TCNT1L.Set(0)
const compare = 16_000_000/1024 - 1
avr.OCR1AH.Set(byte(compare >> 8))
avr.OCR1AL.Set(byte(compare & 0xff))
avr.TIFR1.Set(avr.TIFR1_OCF1A)
interrupt.New(avr.IRQ_TIMER1_COMPA, timer1Compare)
avr.TIMSK1.Set(avr.TIMSK1_OCIE1A)
avr.TCCR1B.Set(avr.TCCR1B_WGM10 | avr.TCCR1B_CS12 | avr.TCCR1B_CS10)
interrupt.Restore(state)
for {
time.Sleep(time.Second)
println("Timer1 ticks:", timerTicks.Get())
}
}
Save as main.go, then flash and monitor at 9600 baud:
tinygo flash -target=arduino -monitor -baudrate=9600 main.go
This configures Timer1 in CTC mode with a 1024 prescaler. TCCR1B_WGM10 is the generated constant for register bit 3, called WGM12 in the datasheet.
Closing this as answered. Please open a new issue if you have any further questions about using TinyGo.