PANIC: 在调用 Lua API 时未保护的错误(script1.lua:34: 尝试对全局变量 'http' 进行索引 (a nil value))

当我尝试在我的 NodeMCU(使用 Lua 编程语言)上执行 HTTP GET 请求时,我会收到这个错误。它通过 WiFi 连接。

当 PIR 传感器(主动红外线传感器)检测到运动时,函数 'roepIFTTT()' 就会被调用。IFTTT 的 HTTP POST 工作良好。

PANIC: 在调用 Lua API 时未保护的错误(script1.lua:35: 尝试对全局变量 'http' 进行索引 (a nil value))

 ets Jan  8 2013,rst cause:2, boot mode:(3,7)

load 0x40100000, len 26096, room 16
tail 0
chksum 0x0c
load 0x3ffe8000, len 2232, room 8
tail 0
chksum 0x7a
load 0x3ffe88b8, len 8, room 8
tail 0
chksum 0x5f
csum 0x5f
ŒÂœäƒoä’sƒûo|ìld$l`„âr›lŒdŒŸ

这是固件内容:

NodeMCU custom build by frightanic.com
    branch: master
    commit: 7b83bbb2ea134cd85ac9d63108603cc02c4e20f7
    SSL: false
    modules: adc,bit,cjson,coap,dht,file,gpio,i2c,mqtt,net,node,ow,pwm,rtctime,sntp,spi,tmr,uart,wifi,ws2812
 build  built on: 2016-11-25 08:30
 powered by Lua 5.1.4 on SDK 1.5.4.1(39cb9a32)

这是我的代码:

wifi.setmode(wifi.STATION)
wifi.sta.config("ssid", "password")
wifi.sta.connect()

ledpen = 0
gpio.mode(ledpen, gpio.OUTPUT)
gpio.write(ledpen, gpio.HIGH)

pirsensorpen = 2

gpio.mode(pirsensorpen, gpio.INT, gpio.PULLUP)

function beweging() -- 这个函数在检测到运动时被调用
    print("PIR 传感器检测到运动")
    gpio.write(ledpen, gpio.LOW)
    roepIFTTT(1)
    tmr.alarm(0, 2000, tmr.ALARM_SINGLE, function()
        gpio.write(ledpen, gpio.HIGH)
    end)
end

function roepIFTTT(value1)
  -- 触发 IFTTT 上的 flashbutton
  conn = nil
  conn = net.createConnection(net.TCP, 0)
  conn:on("receive", function(conn, payload) end)
  conn:connect(80,"maker.ifttt.com")
  conn:on("connection", function(conn, payload)
  conn:send("POST /trigger/pirsensor/with/key/API_KEY?value1="..value1.." HTTP/1.1\r\nHost: maker.ifttt.com\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n") end)
  conn:close()
  print("已调用 IFTTT")

-- 关于下面的代码会生成错误。如果有另外一种简单的创建 HTTP GET 请求的方法,欢迎分享。
    http.get("http://httpbin.org/ip", nil, function(code, data)
    if (code < 0) then
      print("HTTP 请求失败")
    else
      print(code, data)
    end
  end)
  -- 上述代码

end

function metingNaarThingSpeak()
  local a = adc.read(0)
  print("湿度传感器的值: "..a)
  local conn = nil
  conn = net.createConnection(net.TCP, 0)
  conn:on("receive", function(conn, payload) end)
  conn:connect(80, "api.thingspeak.com")
  conn:on("connection", function(conn, payload)
  conn:send("GET /update?api_key=API_KEY&field1="..a.." HTTP/1.1\r\nHost: api.thingspeak.com\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n") end)
  conn:close()
  print("已发送到 ThingSpeak 的数据")
end

gpio.trig(pirsensorpen, "up", beweging)
tmr.alarm(4, 60000, tmr.ALARM_AUTO, function() metingNaarThingSpeak() end)

我做错了什么?

注:我是一名完全的新手,在 Lua 编程语言方面没有任何经验,也没有使用过 NodeMCU。我有其他的编程技能,因此编程对于我来说不是一件新的事情。

点赞
用户131929
用户131929

错误就在这里

modules: adc,bit,cjson,coap,dht,file,gpio,i2c,mqtt,net,node,ow,pwm,rtctime,sntp,spi,tmr,uart,wifi,ws2812

你的 NodeMCU 固件缺少了 HTTP 模块。

2017-01-14 10:52:58