摘要:本文介绍如何在ubuntu下的idf编写模拟-数字转换(ADC)程序,然后把数据传输到阿里云上。
硬件连接使用的是ESP32的ADC引脚,
下图是示意图
我们要用到的是33引脚,对应的是ADC1的第5通道ADC1_CH5
编程也相对简单,不会编写的话有例程可以借鉴。其中核心功能是:
#define EXAMPLE_ADC1_CHAN1 ADC_CHANNEL_5
然后初始化
//-------------ADC1 Init---------------//
adc_oneshot_unit_handle_t adc1_handle;
adc_oneshot_unit_init_cfg_t init_config1 = {
.unit_id = ADC_UNIT_1,
};
ESP_ERROR_CHECK(adc_oneshot_new_unit(&init_config1, &adc1_handle));
//-------------ADC1 Config---------------//
adc_oneshot_chan_cfg_t config = {
.bitwidth = ADC_BITWIDTH_DEFAULT,
.atten = EXAMPLE_ADC_ATTEN,
};
ESP_ERROR_CHECK(adc_oneshot_config_channel(adc1_handle, EXAMPLE_ADC1_CHAN0, &config));
ESP_ERROR_CHECK(adc_oneshot_config_channel(adc1_handle, EXAMPLE_ADC1_CHAN1, &config));
//-------------ADC1 Calibration Init---------------//
adc_cali_handle_t adc1_cali_chan0_handle = NULL;
adc_cali_handle_t adc1_cali_chan1_handle = NULL;
bool do_calibration1_chan0 = example_adc_calibration_init(ADC_UNIT_1, EXAMPLE_ADC1_CHAN0, EXAMPLE_ADC_ATTEN, &adc1_cali_chan0_handle);
bool do_calibration1_chan1 = example_adc_calibration_init(ADC_UNIT_1, EXAMPLE_ADC1_CHAN1, EXAMPLE_ADC_ATTEN, &adc1_cali_chan1_handle);
在while主循环中,循环采集电压然后LOG出来。
ESP_ERROR_CHECK(adc_oneshot_read(adc1_handle, EXAMPLE_ADC1_CHAN0, &adc_raw[0][0]));
ESP_LOGI(TAG, "ADC%d Channel[%d] Raw Data: %d", ADC_UNIT_1 + 1, EXAMPLE_ADC1_CHAN0, adc_raw[0][0]);
if (do_calibration1_chan0) {
ESP_ERROR_CHECK(adc_cali_raw_to_voltage(adc1_cali_chan0_handle, adc_raw[0][0], &voltage[0][0]));
ESP_LOGI(TAG, "ADC%d Channel[%d] Cali Voltage: %d mV", ADC_UNIT_1 + 1, EXAMPLE_ADC1_CHAN0, voltage[0][0]);
}
最后是通过mqtt指令,将数据上报到阿里云。由于要发送的是json字符串,那么将下面这个字符串中的指定数据替换成最新的数据,需要一个json解析算法。
char mqtt_publish_data2[] = "{\"method\":\"thing.event.property.post\",\"params\":{\"OF\":1,\"waterml\":1036}}";
// 解析JSON字符串
cJSON *root = cJSON_Parse(mqtt_publish_data2);
if (root == NULL) {
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL) {
fprintf(stderr, "Error before: %s\n", error_ptr);
}
//return 1;
}
// 查找"waterml"字段
cJSON *waterml = cJSON_GetObjectItemCaseSensitive(cJSON_GetObjectItemCaseSensitive(root, "params"), "waterml");
if (waterml == NULL) {
fprintf(stderr, "Failed to find 'waterml' field.\n");
cJSON_Delete(root);
//return 1;
}
// 假设newData是三位数
int newData = voltage[0][0];
// 替换"waterml"字段的值
cJSON_SetNumberValue(waterml, newData); // 注意:这里我们直接设