最近又重溫一下nodemcu

看了好幾天的 lua & nodemcu for lua document

找個簡單的來玩玩

網上找了 關於這個 的練習題 for nodemcu (lua) 還真少 覺得不大精實 
即然用了LUA 當然得多利用 LUA的特性囉 
那就是setmetatable

也因為這樣 翻了好幾天的 LUA 的書

硬體說明網路上到處都有 , 請自行查閱

還是說明 程式規畫吧

1 需要 output pin

 
輸出 15us HIGH

  利用 gpio.serout() 這個指令超強的 ,這個指令就幹掉 1  3項 的程序 ,當然還有 LUA callback 的語法 整合 
  送出 15us HIGH 50000us LOW count N 次 ,結束後 callback 算均值

2 需要計算 echo 回來的 HIGH 的時間

     在啟動1前 先將 TRIGpin 拉到低,設置 gpio 中斷 上下緣 觸發

    上緣中斷   存下 中斷時間

   下緣中斷  將時間差 加入 total

3 可以重覆測量 做均值

    完成取值後 在cb中 做均值運算並存下來

 

未來擴充項目

  ntp 時間同步   mqtt pub & sub

cron 模組

 


 
-- file hc-sr04.lua
-- use requrie or dofile
-- 全域變數 建立
HC_SR04={}
HC_SR04.__index=HC_SR04
-- HC_SR04.__index = HC_SR04
-- 關閉 中斷
local function rel_gpio(t)
gpio.trig(t.int,"none")
end
-- 啟動前將 IO設置
local function set_gpio(t)
print(t)
gpio.mode(t.trig,gpio.OUTPUT)
gpio.write(t.trig,gpio.LOW)
gpio.mode(t.int,gpio.INT)
end
-- 將table 轉成字串 供 print() 用
function HC_SR04:tostring(t)
local out,sep,sp,endchr="{",":","\t","}"
if t then -- not nil
if type(t) ~= "table" then
return t
end
--- t is table
elseif self then
t=self
end
-- table KEY & value to string
for k,v in pairs(t) do
if type(v) ~= "function" then
out= out .. k .. sep .. v .. sp
end
end
out= out .. endchr
return out
end
-- return value 記得要用 : 呼叫 才 找得到 SELF
function HC_SR04:get_value()
return self.value
end
-- 開始 測量
function HC_SR04:start(cb) -- cb( value)
-- local node=HC_SR04
local p1=0
local total=0
local cut=0
-- local gm
set_gpio(self)
self.value=nil
-- 2 中斷取時間
gpio.trig(self.int,"both", function (lave,us,count)
-- print("lae:",lave,"time:",us,"count: " , count)
if lave == gpio.HIGH then -- start time
p1=us
else -- end time
if p1 then -- if p1 nil abort this time
total = total + us -p1
cut= cut+1
p1=nil
end
-- print( "time:" ,us - p1)
end
end
)
-- start trig HC-SR04
--
gpio.serout(self.trig,gpio.HIGH,{self.trig_time,self.rel_time}, self.count ,
function()
rel_gpio(self)
self.value = total/ cut /58 -- 29us/cm *2
-- print("------",node.value,"-----")
if type(cb) == "function" then
cb(self.value)
end
end
)
end
-- 生一個 metatable
function HC_SR04.new(tri,intt,countt,trig_t,res_t)
local cself={ trig=tri or 1 , int=intt or 2 ,count= countt or 2, value=nil,trig_time= trig_t or 15,rel_time=res_t or 50000 }
-- local node={trig=tri or 1 ,int=intt or 2 ,count= countt or 2, value=nil}
return setmetatable( cself, HC_SR04 )
end

範列:

 
require 'hc-sr04.lua'
hc=HC_SR04.new(1,2,5) -- trigpin 1 , echopin 2 , count 5
hc:start()
print(hc:tostring())
print(hc:value())
hc:start( function(varue) print(value .. " cm") )
hc.count= 3
hc:start( function(varue) print(value .. " cm") )
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 shewerlu 的頭像
    shewerlu

    shewerlu的部落格

    shewerlu 發表在 痞客邦 留言(0) 人氣()