avr: ADC with 0-1023 range

This commit is contained in:
Ron Evans
2018-09-18 15:02:38 +02:00
committed by Ayke van Laethem
parent dbb5ae5a23
commit 40f834d58f
4 changed files with 77 additions and 10 deletions
+4
View File
@@ -19,3 +19,7 @@ func (p GPIO) Low() {
type PWM struct {
Pin uint8
}
type ADC struct {
Pin uint8
}
+44
View File
@@ -124,3 +124,47 @@ func (pwm PWM) Set(value uint16) {
panic("Invalid PWM pin")
}
}
// ADC on the Arduino
const (
ADC0 = 0
ADC1 = 1
ADC2 = 2
ADC3 = 3
ADC4 = 4
ADC5 = 5
)
// InitADC initializes the registers needed for ADC.
func InitADC() {
// set a2d prescaler so we are inside the desired 50-200 KHz range at 16MHz.
*avr.ADCSRA |= (avr.ADCSRA_ADPS2 | avr.ADCSRA_ADPS1 | avr.ADCSRA_ADPS0)
// enable a2d conversions
*avr.ADCSRA |= avr.ADCSRA_ADEN
}
// Configure configures a ADCPin to be able to be used to read data.
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.
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))
// start the conversion
*avr.ADCSRA |= avr.ADCSRA_ADSC
// ADSC is cleared when the conversion finishes
for ok := true; ok; ok = (*avr.ADCSRA & avr.ADCSRA_ADSC) > 0 {
}
low := uint16(*avr.ADCL)
high := uint16(*avr.ADCH)
return uint16(low) | uint16(high<<8)
}