@@ -187,3 +187,88 @@ func (spi SPI) Tx(w, r []byte) error {
187187
188188return nil
189189}
190+
191+ // InitADC initializes the registers needed for ADC.
192+ func InitADC () {
193+ return // no specific setup on nrf51 machine.
194+ }
195+
196+ // Configure configures an ADC pin to be able to read analog data.
197+ func (a ADC ) Configure (ADCConfig ) {
198+ return // no pin specific setup on nrf51 machine.
199+ }
200+
201+ // Get returns the current value of a ADC pin in the range 0..0xffff.
202+ func (a ADC ) Get () uint16 {
203+ var value uint32
204+
205+ adcPin := a .getADCPin ()
206+
207+ // Enable ADC.
208+ nrf .ADC .SetENABLE (nrf .ADC_ENABLE_ENABLE_Enabled )
209+
210+ // Set pin to read.
211+ nrf .ADC .SetCONFIG_PSEL (adcPin )
212+
213+ // config ADC
214+ nrf .ADC .SetCONFIG_RES (nrf .ADC_CONFIG_RES_10bit )
215+ nrf .ADC .SetCONFIG_INPSEL (nrf .ADC_CONFIG_INPSEL_AnalogInputOneThirdPrescaling )
216+ nrf .ADC .SetCONFIG_REFSEL (nrf .ADC_CONFIG_REFSEL_SupplyOneThirdPrescaling )
217+
218+ // Start tasks.
219+ nrf .ADC .TASKS_START .Set (1 )
220+
221+ // Wait until the sample task is done.
222+ for nrf .ADC .EVENTS_END .Get () == 0 {
223+ }
224+ nrf .ADC .EVENTS_END .Set (0x00 )
225+
226+ value = nrf .ADC .GetRESULT ()
227+
228+ // Stop the ADC
229+ nrf .ADC .TASKS_STOP .Set (1 )
230+ for nrf .ADC .EVENTS_END .Get () == 0 {
231+ }
232+ nrf .ADC .EVENTS_END .Set (0 )
233+
234+ // Disable ADC.
235+ nrf .ADC .SetENABLE (nrf .ADC_ENABLE_ENABLE_Disabled )
236+
237+ if value < 0 {
238+ value = 0
239+ }
240+
241+ // Return 16-bit result from 10-bit value.
242+ return uint16 (value << 6 )
243+ }
244+
245+ func (a ADC ) getADCPin () uint32 {
246+ switch a .Pin {
247+ case 1 :
248+ return nrf .ADC_CONFIG_PSEL_AnalogInput2
249+
250+ case 2 :
251+ return nrf .ADC_CONFIG_PSEL_AnalogInput3
252+
253+ case 3 :
254+ return nrf .ADC_CONFIG_PSEL_AnalogInput4
255+
256+ case 4 :
257+ return nrf .ADC_CONFIG_PSEL_AnalogInput5
258+
259+ case 5 :
260+ return nrf .ADC_CONFIG_PSEL_AnalogInput6
261+
262+ case 6 :
263+ return nrf .ADC_CONFIG_PSEL_AnalogInput7
264+
265+ case 26 :
266+ return nrf .ADC_CONFIG_PSEL_AnalogInput0
267+
268+ case 27 :
269+ return nrf .ADC_CONFIG_PSEL_AnalogInput1
270+
271+ default :
272+ return 0
273+ }
274+ }
0 commit comments