PROJECT = "adcdemo" VERSION = "1.0.0" log.info("main", PROJECT, VERSION) -- 一定要添加sys.lua…
- User
PROJECT = "adcdemo" VERSION = "1.0.0"
log.info("main", PROJECT, VERSION)
-- 一定要添加sys.lua !!!! sys = require("sys")
-- 添加硬狗防止程序卡死 if wdt then wdt.init(9000) -- 初始化watchdog设置为9s sys.timerLoopStart(wdt.feed, 3000) -- 3s喂一次狗 end
local rtos_bsp = rtos.bsp() function adc_pin() -- 根据不同开发板,设置ADC编号
if rtos_bsp == "EC618" then --Air780E开发板ADC编号 return 0,1,255,255,adc.CH_CPU ,adc.CH_VBAT else log.info("main", "define ADC pin in main.lua") return 0, 0,0,0,0,0 endend local adc_pin_0,adc_pin_1,adc_pin_2,adc_pin_3,adc_pin_temp,adc_pin_vbat=adc_pin() sys.taskInit(function() if rtos_bsp == "AIR105" then adc.setRange(adc.ADC_RANGE_3_6) --开启的内部分压,可以把量程扩大 end if adc_pin_0 and adc_pin_0 ~= 255 then adc.open(adc_pin_0) end
if adc_pin_temp and adc_pin_temp ~= 255 then adc.open(adc_pin_temp) end if adc_pin_vbat and adc_pin_vbat ~= 255 then adc.open(adc_pin_vbat) end -- 下面是循环打印, 接地不打印0也是正常现象 -- ADC的精度都不会太高, 若需要高精度ADC, 建议额外添加adc芯片 while true do if adc_pin_0 and adc_pin_0 ~= 255 then log.debug("adc", "adc" .. tostring(adc_pin_0), adc.get(adc_pin_0)) -- 若adc.get报nil, 改成adc.read end if adc_pin_temp and adc_pin_temp ~= 255 then log.debug("adc", "CPU TEMP", adc.get(adc_pin_temp)) end if adc_pin_vbat and adc_pin_vbat ~= 255 then log.debug("adc", "VBAT", adc.get(adc_pin_vbat)) end local adc_pin = 9 -- 定义热敏电阻的参数 local r0 = 20000 -- 参考电阻值(单位:欧姆),设置为20KΩ local b = 3950 -- B值 -- 模拟函数:读取电流值(实际应用中使用相应的硬件接口函数) function read_current() local current = read_current(adc_pin) -- 读取电流值(实际应用中使用相应的硬件接口函数) local temperature = current_to_temperature(current) end -- 定义温度转换函数 function current_to_temperature(current) if current == 0 then return 0 -- 当电流为0时温度为0摄氏度 end local r = r0 * (1 / (math.exp(b / (current * r0)) - 1)) -- 计算热敏电阻的阻值 local t_kelvin = (b / math.log(r / r0)) -- 使用B值计算对应的绝对温度(单位:开尔文) local t_celsius = t_kelvin - 273.15 -- 将温度转换为摄氏度 return t_celsius end print(string.format("电流 %.2f 安培对应的温度为 %.2f°C", current, temperature)) sys.wait(1000) -- 示例使用:读取电流并转换为温度 end -- 若不再读取, 可关掉adc, 降低功耗, 非必须 if adc_pin_0 and adc_pin_0 ~= 255 then adc.close(adc_pin_0) end if adc_pin_1 and adc_pin_1 ~= 255 then adc.close(adc_pin_1) end if adc_pin_2 and adc_pin_2 ~= 255 then adc.close(adc_pin_2) end if adc_pin_3 and adc_pin_3 ~= 255 then adc.close(adc_pin_3) end if adc_pin_temp and adc_pin_temp ~= 255 then adc.close(adc_pin_temp) end if adc_pin_vbat and adc_pin_vbat ~= 255 then adc.close(adc_pin_vbat) endend) -- 用户代码已结束--------------------------------------------- -- 结尾总是这一句 sys.run() -- sys.run()之后后面不要加任何语句!!!!! 修改以上代码 使其输出正确的温度
- Assistant