Skip to content

Commit a323261

Browse files
committed
Implement analogRead() API which allows to read the value provided at any of the analog pins of the ESP32.
1 parent 0f9f831 commit a323261

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

main/CommandHandler.cpp

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1193,6 +1193,34 @@ int getDigitalRead(const uint8_t command[], uint8_t response[])
11931193
return 6;
11941194
}
11951195

1196+
extern "C" {
1197+
#include <driver/adc.h>
1198+
}
1199+
1200+
int getAnalogRead(const uint8_t command[], uint8_t response[])
1201+
{
1202+
uint8_t pin = command[4];
1203+
1204+
/* Power up the ADC. */
1205+
adc_power_on();
1206+
/* Initialize the ADC. */
1207+
adc_gpio_init(ADC_UNIT_1, (adc_channel_t)pin);
1208+
/* Set maximum analog bit-width = 12 bit. */
1209+
adc1_config_width(ADC_WIDTH_BIT_12);
1210+
/* Configure channel attenuation. */
1211+
adc1_config_channel_atten((adc1_channel_t)pin, ADC_ATTEN_DB_0);
1212+
/* Read the analog value from the pin. */
1213+
uint16_t const adc_raw = adc1_get_raw((adc1_channel_t)pin);
1214+
/* Power down the ADC. */
1215+
adc_power_off();
1216+
1217+
response[2] = 1; // number of parameters
1218+
response[3] = sizeof(adc_raw); // parameter 1 length = 2 bytes
1219+
memcpy(&response[4], &adc_raw, sizeof(adc_raw));
1220+
1221+
return 7;
1222+
}
1223+
11961224
int writeFile(const uint8_t command[], uint8_t response[]) {
11971225
char filename[32 + 1];
11981226
size_t len;
@@ -1579,7 +1607,7 @@ const CommandHandlerType commandHandlers[] = {
15791607
setEnt, NULL, NULL, NULL, sendDataTcp, getDataBufTcp, insertDataBuf, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
15801608

15811609
// 0x50 -> 0x5f
1582-
setPinMode, setDigitalWrite, setAnalogWrite, getDigitalRead, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
1610+
setPinMode, setDigitalWrite, setAnalogWrite, getDigitalRead, getAnalogRead, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
15831611

15841612
// 0x60 -> 0x6f
15851613
writeFile, readFile, deleteFile, existsFile, downloadFile, applyOTA, renameFile, downloadOTA, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,

0 commit comments

Comments
 (0)