1. 程式人生 > 實用技巧 >ESP8266模組 - NodeMCU韌體連線DHT11和OLED模組

ESP8266模組 - NodeMCU韌體連線DHT11和OLED模組

前篇,ESP8266 相關韌體的編譯文章:
ESP-12F WIFI模組開發(NonOS, RTOS, NodeMCU韌體編譯)


NodeMCU連線DHT11模組

參考上面連結,,掌握ModeMCU韌體的編譯和燒錄。使用最新版NodeMCU V3.0,自帶DHT庫,配置韌體,開啟DHT模組。

目錄:nodemcu-firmware/app/include
修改檔案:user_modules.h,該檔案是管理各種模組的。
找到DHT巨集定義,取消註釋。

#define LUA_USE_MODULES_DHT

檔案 user_config.h 涉及 Flash 大小,波特率,韌體浮點或整形,SSL啟動等。

配置檔案修改完成後,進入nodemcu根目錄,,輸入make開始編譯。
編譯成功後,會在bin目錄下有:0x00000.bin, 0x10000.bin 兩個檔案。
使用esp燒錄工具,將韌體燒錄到esp8266模組。

使用ESPlorer工具連線ESP8266串列埠,開機如下:


DHT11測試程式碼:

function mydht11()
	pin = 4  -- GPIO2
	status, temp, humi, temp_dec, humi_dec = dht.read11(pin)
	if status == dht.OK then
		-- Integer firmware using this example
		print(string.format("DHT Temperature:%d.%03d;Humidity:%d.%03d\r\n",
			  math.floor(temp),
			  temp_dec,
			  math.floor(humi),
			  humi_dec
		))

		-- Float firmware using this example
		print("DHT Temperature:"..temp..";".."Humidity:"..humi)

	elseif status == dht.ERROR_CHECKSUM then
		print( "DHT Checksum error." )
	elseif status == dht.ERROR_TIMEOUT then
		print( "DHT timed out." )
	end
end

ESPlorer工具左側輸入程式碼,傳送到esp8266模組,在右側下面命令列輸入mydht11(),就可獲取溫溼度資料。

注: DHT11模組精度低,沒有小數位,所以小數一直為0。


網頁顯示DHT11資訊:

pin = 4 --GPIO2

-- a simple HTTP server
srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
    conn:on("receive", function(sck, payload)
        print(payload)
        local status, temp, humi, temp_dec, humi_dec = dht.read11(pin)
        local buf = "";
        buf = buf.."<meta http-equiv=\"refresh\" content=\"3\">";
        buf = buf.."<meta charset=\"gbk\">";
        buf = buf.."<h2>DHT11</h2>";  
        buf = buf.."<p>當前溫度: "..temp.."."..temp_dec.."'C</p>";  
        buf = buf.."<p>當前溼度: "..humi.."."..humi_dec.."%</p>"; 
        -- sck:send("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n<h1> Hello DHT11 </h1>".."<p>Temp: "..temp.."'C</p>")
        sck:send(buf)
        
    end)
    conn:on("sent", function(sck) sck:close() end)
end)

OLED模組

修改檔案:user_modules.h,開啟IIC, SPI, u8g2模組,

#define LUA_USE_MODULES_I2C
#define LUA_USE_MODULES_SPI
#define LUA_USE_MODULES_U8G2

OLED程式碼

function init_oled()
	local sda = 5 -- GPIO14
	local scl = 6 -- GPIO12
	local sla = 0x3c
	
	i2c.setup(0, sda, scl, i2c.SLOW)
	disp = u8g2.ssd1306_i2c_128x64_noname(0, sla)

	disp:setFont(u8g2.font_6x10_tf)
	disp:setFontRefHeightExtendedText()
	disp:setDrawColor(1)
	disp:setFontPosTop()
	disp:setFontDirection(0)

	disp:drawFrame(0, 0, 128, 64)
end

function oled_show_msg(temp, hum)
	if temp ~= nil then
		disp:drawStr(5, 5, "Temp: "..temp)
		disp:drawStr(5, 20, "Hum : "..hum)
		disp:sendBuffer()
	end
end

預設 u8g2 模組只開啟了2種字型,字型啟用在: u8g2_fonts.h 檔案裡。