Skip to content

Commit ec31bb8

Browse files
fivdimkellner
authored andcommitted
modules/pins/analog: add adc for the esp32 #37
1 parent 587d900 commit ec31bb8

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

modules/pins/analog/esp32/analog.c

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
* Copyright (c) 2016-2018 Moddable Tech, Inc.
3+
*
4+
* This file is part of the Moddable SDK Runtime.
5+
*
6+
* The Moddable SDK Runtime is free software: you can redistribute it and/or modify
7+
* it under the terms of the GNU Lesser General Public License as published by
8+
* the Free Software Foundation, either version 3 of the License, or
9+
* (at your option) any later version.
10+
*
11+
* The Moddable SDK Runtime is distributed in the hope that it will be useful,
12+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14+
* GNU Lesser General Public License for more details.
15+
*
16+
* You should have received a copy of the GNU Lesser General Public License
17+
* along with the Moddable SDK Runtime. If not, see <http://www.gnu.org/licenses/>.
18+
*
19+
*/
20+
21+
#include "xs.h"
22+
#include "xsesp.h"
23+
24+
#include "driver/adc.h"
25+
#include "esp_adc_cal/include/esp_adc_cal.h"
26+
27+
#define V_REF 1100
28+
29+
void xs_analog_read(xsMachine *the)
30+
{
31+
int channel = xsToInteger(xsArg(0));
32+
if (channel < 0 || channel >= ADC1_CHANNEL_MAX)
33+
xsRangeError("invalid analog channel number");
34+
35+
if (ESP_OK != adc1_config_width(ADC_WIDTH_BIT_10))
36+
xsUnknownError("can't configure precision for ADC1 peripheral");
37+
38+
if (ESP_OK != adc1_config_channel_atten(channel, ADC_ATTEN_DB_11))
39+
xsUnknownError("can't configure attenuation for requested channel on ADC1 peripheral");
40+
41+
esp_adc_cal_characteristics_t characteristics;
42+
esp_adc_cal_get_characteristics(V_REF, ADC_ATTEN_DB_11, ADC_WIDTH_BIT_10, &characteristics);
43+
44+
uint32_t milli_volts = adc1_to_voltage(channel, &characteristics);
45+
uint32_t linear_raw_value = c_round(milli_volts / 3300.0 * 1023.0);
46+
47+
xsResult = xsInteger(linear_raw_value);
48+
}
49+

0 commit comments

Comments
 (0)