avr: time runs too slow after machine.Timer0.Configure changes the prescaler

オープン
#6,071 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
3/5
見積もり時間
1〜2日
初心者へのやさしさ
72/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
arduino, go

調査の方向性

Start in src/runtime/runtime_avr.go at currentNanosecondsInTick and inspect how the TCCR0B clock select bits map to the Timer0 prescaler. The reproduction uses machine.Timer0.Configure and time.Sleep on ATmega328P; run it on an AVR target and compare measured sleep duration at prescaler 1 and 64. Done means runtime time functions keep accurate durations after changing the prescaler.

索引モデルが issue の本文から書いたものです。

説明

On ATmega328P and ATmega1280/2560, the runtime monotonic clock uses Timer0. machine.Timer0.Configure can change the Timer0 prescaler, and then it calls adjustMonotonicTimer to update the tick length. The tick length is only correct with prescaler 1, which is the runtime default. With any other PWM period, time.Sleep, time.Now and time.Since run too slow.

Steps to reproduce
package main

import (
	"machine"
	"time"
)

func main() {
	machine.D8.Configure(machine.PinConfig{Mode: machine.PinOutput})
	machine.Timer0.Configure(machine.PWMConfig{Period: 1024000}) // prescaler 64
	for {
		machine.D8.High()
		time.Sleep(10 * time.Millisecond)
		machine.D8.Low()
		time.Sleep(10 * time.Millisecond)
	}
}

tinygo flash -target arduino (TinyGo 0.44.0), then measure D8.

Expected

D8 changes state every 10 ms.

Actual

D8 changes state every 1920 ms. Measured with a logic analyser on an ATmega328P (Freetronics Eleven, Uno clone) at 16 MHz:

PWM period Prescaler Sleep(10ms) measured Error
16 µs (default) 1 10.09 ms none
1024 µs 64 1920 ms 192× too slow
4096 µs 256 about 10 s 1024× too slow

The PWM output on D6 had the correct periods (16.1 µs, 1024.0 µs, 4095.8 µs), so the hardware runs at the requested prescaler. Only the runtime's time is wrong.

Cause

currentNanosecondsInTick in src/runtime/runtime_avr.go uses the CS0[2:0] select bits of TCCR0B as the prescaler divider, and it divides by that value where it must multiply. For CS0 = 3 (prescaler 64) it uses 1/3 where it must use 64, so the tick length is 192 times too small. The CS0 values are in the TCCR0B "Clock Select Bit Description" table of the ATmega328P datasheet. Only CS0 = 1 (prescaler 1) gives the correct value.

When this is fixed, #6070 can also occur.

主要言語
Go
スター
17.8k
フォーク
1.1k
平均マージ
1日 4時間
マージ済み PR(30日)
380

環境構築

このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

tinygo-org/tinygo のほかの issue

tinygo-org/tinygo の issue をすべて見る

似ている issue

Go の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。