YAHAL
Yet Another Hardware Abstraction Library
Loading...
Searching...
No Matches
adc_rp2350.cpp
1// ---------------------------------------------
2// This file is part of
3// _ _ __ _ _ __ __
4// ( \/ ) /__\ ( )_( ) /__\ ( )
5// \ / /(__)\ ) _ ( /(__)\ )(__
6// (__)(__)(__)(_) (_)(__)(__)(____)
7//
8// Yet Another HW Abstraction Library
9// Copyright (C) Andreas Terstegge
10// BSD Licensed (see file LICENSE)
11//
12// ---------------------------------------------
13//
14#include "RP2350.h"
15#include "adc_rp2350.h"
16#include <cassert>
17
18using namespace _IO_BANK0_;
19using namespace _RESETS_;
20adc_rp2350 adc_rp2350::inst;
21
22adc_rp2350::adc_rp2350() {
23 // Take ADC out of reset state
24 RESETS_CLR.RESET.ADC <<= 1;
25 while (!RESETS.RESET_DONE.ADC) ;
26 // Enable the ADC
27 _ADC_::ADC.CS.EN = 1;
28 while (!_ADC_::ADC.CS.READY) ;
29 // Prepare ADC inputs
30 for (int i=40; i < 48; ++i) {
31 // Disable pull-resistors and isolation
32 _PADS_BANK0_::PADS_BANK0.GPIO[i].PUE = 0;
33 _PADS_BANK0_::PADS_BANK0.GPIO[i].PDE = 0;
34 _PADS_BANK0_::PADS_BANK0.GPIO[i].ISO = 0;
35 }
36}
37
38void adc_rp2350::adcMode(uint8_t channel, uint16_t mode) {
39 assert(channel < 8);
40 assert(mode < ADC::ADC_14_BIT);
41 _modes[channel] = mode;
42}
43
44adc_mode_t adc_rp2350::getMode(uint8_t channel) {
45 assert(channel < 8);
46 return _modes[channel];
47}
48
49uint16_t adc_rp2350::adcReadRaw(uint8_t channel) {
50 assert(channel < 8);
51 // Read the 12 bit ADC result
52 _ADC_::ADC.CS.AINSEL = channel;
53 _ADC_::ADC.CS.START_ONCE = 1;
54 while(!_ADC_::ADC.CS.READY) ;
55 uint16_t result = _ADC_::ADC.RESULT;
56 // Our ADC has no real 8 or 10 bit modes, so we simulate
57 // the behaviour by shifting the result...
58 switch(_modes[channel]) {
59 case ADC::ADC_8_BIT:
60 return result >> 4;
61 case ADC::ADC_10_BIT:
62 return result >> 2;
63 default:
64 case ADC::ADC_12_BIT:
65 return result;
66 }
67}
68
69float adc_rp2350::adcReadVoltage(uint8_t channel) {
70 return rawToVoltage(channel, adcReadRaw(channel));
71}
72
73float adc_rp2350::rawToVoltage(uint8_t channel, uint16_t raw) {
74 float voltage = 3.3f * (float)raw;
75 switch(_modes[channel]) {
76 case ADC::ADC_8_BIT:
77 voltage /= 255.0f;
78 break;
79 case ADC::ADC_10_BIT:
80 voltage /= 1023.0f;
81 break;
82 default:
83 case ADC::ADC_12_BIT:
84 voltage /= 4095.0f;
85 break;
86 }
87 return voltage;
88}