From de694b585750dd09d0428902b235f8e5ff0563dd Mon Sep 17 00:00:00 2001 From: Ayke van Laethem Date: Thu, 20 Sep 2018 21:24:41 +0200 Subject: [PATCH] avr: set ADLAR bit in ADC to get a value scaled to 16-bit --- src/examples/adc/adc.go | 2 +- src/machine/machine_avr.go | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/examples/adc/adc.go b/src/examples/adc/adc.go index 8d1a9f4dc..69500c0b1 100644 --- a/src/examples/adc/adc.go +++ b/src/examples/adc/adc.go @@ -19,7 +19,7 @@ func main() { for { val := sensor.Get() - if val < 512 { + if val < 0x8000 { led.Low() } else { led.High() diff --git a/src/machine/machine_avr.go b/src/machine/machine_avr.go index d338af1d5..1c5e19a24 100644 --- a/src/machine/machine_avr.go +++ b/src/machine/machine_avr.go @@ -149,13 +149,15 @@ func (a ADC) Configure() { return // no pin specific setup on AVR machine. } -// Get returns the current value of a ADC pin. The AVR will return a 10bit value ranging -// from 0-1023. +// Get returns the current value of a ADC pin, in the range 0..0xffff. The AVR +// has an ADC of 10 bits precision so the lower 6 bits will be zero. func (a ADC) Get() uint16 { // set the analog reference (high two bits of ADMUX) and select the // channel (low 4 bits), masked to only turn on one ADC at a time. - // this also sets ADLAR (left-adjust result) to 0 (the default). - *avr.ADMUX = avr.RegValue(avr.ADMUX_REFS0 | (a.Pin & 0x07)) + // set the ADLAR bit (left-adjusted result) to get a value scaled to 16 + // bits. This has the same effect as shifting the return value left by 6 + // bits. + *avr.ADMUX = avr.RegValue(avr.ADMUX_REFS0 | avr.ADMUX_ADLAR | (a.Pin & 0x07)) // start the conversion *avr.ADCSRA |= avr.ADCSRA_ADSC