Advertisement
kvnd

DHT11 for esp8266 - lua

Feb 28th, 2015
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.20 KB | None | 0 0
  1. -- dht11 code for esp8266
  2. -- better approach counting back 40 bits from the last meaningful bit
  3. -- untested yet
  4. -- Kevin D
  5.  
  6. pin = 4
  7.  
  8. function ReadData()
  9.  gpio_read=gpio.read
  10.  gpio_write=gpio.write
  11.  h=0
  12.  hl=0
  13.  t=0
  14.  tl=0
  15.  cs=0
  16.  bl=0
  17.  cscalc=0
  18.  offset=0
  19.  data={}
  20.  for j = 1, 50, 1 do
  21.   data[j]=0
  22.  end
  23.  
  24.  gpio.mode(pin, gpio.OUTPUT)
  25.  gpio.write(pin, gpio.LOW)
  26.  tmr.delay(20000)
  27.  gpio.mode(pin, gpio.INPUT)
  28.  
  29.  for j=1,50,1 do
  30.   bl=0
  31.   while (gpio_read(pin)==0) do end
  32.   while (gpio_read(pin)==1 and bl<10 ) do
  33.    bl=bl+1
  34.   end
  35.   if(bl>=10) then
  36.    offset=j-1-40
  37.    break
  38.   else
  39.    data[j]=bl
  40.   end
  41.  end
  42.  
  43.  for i=1,8,1 do
  44.   if (data[i+0+offset]>2) then
  45.    h = h+2^(8-i)
  46.   end
  47.  end
  48.  
  49.  for i=1,8,1 do
  50.   if (data[i+8+offset]>2) then
  51.    hl = hl+2^(8-i)
  52.   end
  53.  end
  54.  
  55.  for i=1,8,1 do
  56.   if (data[i+16+offset]>2) then
  57.    t = t+2^(8-i)
  58.   end
  59.  end
  60.  
  61.  for i=1,8,1 do
  62.   if (data[i+24+offset]>2) then
  63.    tl = tl+2^(8-i)
  64.   end
  65.  end
  66.  
  67.  for i=1,8,1 do
  68.   if (data[i+32+offset]>2) then
  69.    cs = cs+2^(8-i)
  70.   end
  71.  end
  72.  
  73.  cscalc=(h+hl+t+tl)%256
  74.  
  75.  if(cs==cscalc) then
  76.   print ("t: "..t.."."..tl)
  77.   print ("h: "..h.."."..hl)
  78.  else
  79.   print ("erreur checksum")
  80.  end
  81. end
  82.  
  83. ReadData()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement