tinygo icon indicating copy to clipboard operation
tinygo copied to clipboard

Setting a timer interrupt on an Arduino Uno R3

Open scottlu opened this issue 4 years ago • 4 comments

I'm looking for sample code for setting a timer interrupt on an Arduino Uno R3.

scottlu avatar Jan 06 '22 03:01 scottlu

@scottlu did you ever figure this out?

mccolljr avatar Jun 26 '22 20:06 mccolljr

@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

mccolljr avatar Jun 27 '22 19:06 mccolljr

Thanks.... looks good.

scottlu avatar Jun 27 '22 22:06 scottlu

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.

davecheney avatar Oct 26 '26 06:10 davecheney