User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sat Sep 29, 2018 6:45 am

tlfong01 wrote:
Fri Sep 28, 2018 2:07 pm
Appendix - How to install LUA
*** Method 1 - Using curl
1. Build lua-5.3.5
curl -R -O http://www.lua.org/ftp/lua-5.3.5.tar.gz
tar zxf lua-5.3.5.tar.gz
cd lua-5.3.5
make linux test
Results - Fatal error - no readline.h
2. Install readline development libraries
sudo apt-get install libreadline-dev
3. make linux test
Results - make OK.

*** Method 2 - Using apt-get
sudo apt-get update
sudo apt-get install lua5.3
Results - Install OK.

Problem
The command lua still starts with version 5.1.5. I need to find out how to change the path thing, ...

Lua: configuring path settings - Tieske 2016jan01
http://www.thijsschreijer.nl/blog/?p=1025

A common problem with Lua newbies is the setup of the Lua environment. As many other programming/scripting languages Lua allows you to load external libraries. To prevent you from having to type exact system paths, Lua uses so called library paths to automatically look them up.

For this purpose Lua has 2 environment variables, LUA_PATH and LUA_CPATH. The former is used for loading Lua libraries, the latter for C libraries. Despite the different targets, they both work the same. And if you are familiar with the regular system PATH variables, then you already know the concept.

NOTE: from Lua 5.2 onwards, the versioned variables eg. LUA_PATH_5_2 and LUA_CPATH_5_2 for Lua 5.2, take precedence over the unversioned ones.

Most applications use external libraries, so it is quite essential to understand the paths, especially if your system setup deviates from the most common standards.

require

Lua uses the `require` function to load external libraries, to find the modules Lua uses package searchers. The use of those is beyond the scope of this post, but the one thing you need to know is that the searcher for Lua modules is tried first and if it fails, the searcher for C modules will be used. These two are the ones using the path variables to find what they are looking for.

When a module is requested as in

local socket = require("socket")

Then Lua will start looking for the module named “socket” within the configured paths.

Path format

Each search location in the path is separated by “;” (semicolon), and a “?” (question mark) indicates the name of the module. So an example LUA_PATH could look like this;

LUA_PATH=/usr/local/lua/?.lua;./modules/?.lua

This example specifies two locations (in order) to look for the module (assuming we’re still requiring “socket“);

/usr/local/lua/socket.lua
./modules/socket.lua


Nested paths

In Lua, if a package consists of multiple modules, they usually are organized in a tree structure. When requiring a module on this tree, the individual path elements are dot separated `.`

local mime = require("socket.mime")

In this case the separating `.` denotes the directory structure, think of replacing them by ‘/‘ (or ‘\‘ on Windows). So in this case, with the following paths;

LUA_PATH=/usr/local/lua/?.lua;./modules/?.lua

The files Lua will look for will be;

/usr/local/lua/socket/mime.lua
./modules/socket/mime.lua


There is a caveat to this; if you include the exact location of the module, but then ‘require‘ it using a nested module name, the module will not be found;

LUA_PATH=/usr/local/lua/socket/?.lua

and then requiring

local mime = require("socket.mime")

will look for

/usr/local/lua/socket/socket/mime.lua

Note the double ‘socket‘ in there, and Lua will fail to find it.

Defaults

If the environment variables are not found Lua will use it’s defaults. The default paths are denoted by `;;` (double semi-colon). So in the example above, if you want Lua to first check the specific directory, and then check its default locations, it would look like this;

LUA_PATH=/usr/local/lua/?.lua;./modules/?.lua;;

Note the double semicolon at the end, which is the placeholder where the default Lua paths will be inserted.

init.lua

If you look at the default paths you’ll probably see `/?/init.lua` in there. So what is this about?

If you create a module that in itself contains multiple sub modules then the `init.lua` can help you to keep things nice and tidy. Consider a module with 2 sub modules

./mymodule.lua
./mymodule/api.lua
./mymodule/config.lua

So this module has a module file as well as a sub directory by the same name. A common pattern is to use `init.lua` in those cases. `init.lua` will have the contents of `mymodule.lua` and be located inside the subdirectory:

./mymodule/init.lua #contents of: mymodule.lua
./mymodule/api.lua
./mymodule/config.lua

So now our entire module is encapsulated inside the directory with the module name, as said: nice and tidy.

By using a Lua path like this:

./?.lua;./?/init.lua

Everything will still work as it did before, because when we do `require(“mymodule”)` the second clause will expand to `./mymodule/init.lua`. So all together there is nothing special about it, it is just a practice that was so common, that it actually made it into the Lua defaults.

Manipulating Lua

What if you want to change the paths from inside Lua? In that case there are 2 global properties; `package.path` and `package.cpath` which contain the paths searched. In those variables, the placeholder for the defaults, “;;“, will already have been expanded to the actual defaults.

Troubleshooting

Now what if you set everything up, but it still doesn’t work?

Try inserting this line to see what paths are being searched;

print("LUA MODULES:\n",(package.path:gsub("%;","\n\t")),"\n\nC MODULES:\n",(package.cpath:gsub("%;","\n\t")))

(this will do a pretty-print of the paths) and see whether they match what you configured/expected.

Check the error message (which is usually quite descriptive)

Check the casing of the module name, names and paths are case sensitive (except on Windows)

If using a Lua version 5.2 or higher, check the versioned environment variables, eg. LUA_PATH_5_2, etc.

Check any command-line scripts being invoked for path manipulation, eg. LuaRocks usually inserts extra paths to its package repository (rocktrees) to make sure packages can be found

Check your application documentation, Lua is often embedded into a host application. Obviously the host application might override any default Lua behaviours.

More info

http://www.luafaq.org/#T1.19

http://www.lua.org/pil/8.1.html

.END


Update 2018sep29hkt1537

The above notes is very detailed, but it is too complicated for a LUA newbie like (who have so far only written one program, "Hello World". So I will stop here, and come back when I really need to upgrade LUA. For now, I think Raspian stretch's preinstalled LUA5.1.5 should be good enough for me to mess around.
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sat Sep 29, 2018 2:48 pm

tlfong01 wrote:
Sat Sep 29, 2018 6:45 am
The above notes is very detailed, but it is too complicated for a LUA newbie like (who have so far only written one program, "Hello World". So I will stop here, and come back when I really need to upgrade LUA. For now, I think Raspian stretch's preinstalled LUA5.1.5 should be good enough for me to mess around.

One Dollar ESP8266 Compatible Relay (ESP8266 Not Included!)
https://www.aliexpress.com/item/ESP8266 ... 6f1dd319-8
Attachments
es8266_relay_2018sep2901.jpg
es8266_relay_2018sep2901.jpg (164.02 KiB) Viewed 3154 times
Last edited by tlfong01 on Sun Sep 30, 2018 3:24 am, edited 2 times in total.
I am an electronics and smart home hobbyist.

petermeigs
Posts: 96
Joined: Thu Mar 23, 2017 1:34 pm
Location: Los Altos, California

Re: GPIO.input voltage levels vs edge detection

Sat Sep 29, 2018 5:03 pm

Some esp8266 tips:
1. Be careful of which gpio pins you use. At power-on, some of the pins change value cycling between on and off until they get to their startup state.: See http://rabbithole.wwwdotorg.org/2017/03 ... -gpio.html
2. I like using a raspbian-boot raspberry pi for working on the esp8266. Yes, you have to deal with linux serial issues but its not that hard. The benefit is that you can use a simple ribbon cable for the serial connection. I use both raspberry pi 3 and pi zero-w. Because its nice to have a gui for Esplorer, a pi3b or 3b+ is nice. For raspberry pi here are my notes:
a. checkouthttp://www.pihome.eu/2017/10/08/enable- ... an-jessie/, # https://hallard.me/enable-serial-port ... pberry-pi/, and
https://spellfoundry.com/2016/05/29/con ... ding-pi-3/. These may be a little out of date and you will find that raspi-config will do some of it for you. The main thing to be aware of it that rasbperry pi gives the hardware serial port to bluetooth and for high baud rates, you will have less trouble is you use that for the serial ports.
b. Also, rpi gives the serial port to the linux bootup console so you will need to turn that off as explained in the urls. After you follow the process verify that in /boot/config.txt, you have

Code: Select all

enable_uart=1
dtoverlay=pi3-disable-bt
dtoverlay=pi3-miniuart-bt # I just turn off bluetooth to avoid issues
c. In /boot/cmdline.txt, make sure "console=serial0,115200" is removed.
d. After rebooting you can find out what serial ports you have with:

Code: Select all

ls -l /dev/tty[^0-9]*
ls -ld /dev/ser*
There should be only two that you care about.


3. I like esp_flasher from nodemcu flashing the esp8266. (http://www.nodemcu.com) It is the most trouble free. Be carefully to fully erase the eprom before you start to get rid of old files on it. I've lost my notes on how to do that but I don't recall it being very hard.

4. Here is what i use for an init.lua. It lets force a startup baud rate if I uncomment one of the setup lines. Also, it is minimalistic and defers the "real" code to be run elsewhere.

Code: Select all

-- uart.setup(0, 115200, 8, 0, 1, 1)
-- uart.setup(0, 57600, 8, 0, 1, 1)
print("running init.lua")
print("0: " .. uart.getconfig(0))
print("1: " .. uart.getconfig(1))
runfileList = { 
    "uploader.lua",
    "myserver.lua",
    "testserver.lua"
}

function ls()
  for k,v in pairs(file.list()) do
    print("name:" .. k .. ", size: " ..v.. ".")
  end
end

for i, runfile in ipairs(runfileList) do
  if file.exists(runfile) then
    print(i .. " Runfile " .. runfile .. " exists")
    dofile(runfile)
  end
end

5. Here is myserver.lua. It will do the wifi connection for you after you update the tables with your ssid and key. Note that it uses a callback for the connection. This is much more reliable than straight line coding. There is a bunch of other stuff here to handle a relay and an HC-SR04 distance sensor but I think you can ignore this as I don't think it will hurt to have the code there:

Code: Select all

print("Starting ...")

function main()
  device = {}  

  wifistatus = {
    [wifi.STA_IDLE] = "wifi.STA_IDLE",
    [wifi.STA_CONNECTING] = "wifi.STA_CONNECTING",
    [wifi.STA_WRONGPWD] = "wifi.STA_WRONGPWD",
    [wifi.STA_APNOTFOUND] = "wifi.STA_APNOTFOUND",
    [wifi.STA_FAIL] = "wifi.STA_FAIL",
    [wifi.STA_GOTIP] = "wifi.STA_GOTIP"
  }

  esp = {
    GPIO16 =  0,
    GPIO5 =   1,
    GPIO4 =   2,
    GPIO0 =   3,
    GPIO2 =   4,
    GPIO14 =  5,
    GPIO12 =  6,      
    GPIO13 =  7,
    GPIO15 =  8,
    GPIO3 =   9,
    GPIO1 =  10,
    GPIO9 =  11,
    GPIO10 = 12
  }

  pin = {
    TRIG   = esp.GPIO15,
    ECHO   = esp.GPIO5,
    led1   = esp.GPIO0,
    led2   = esp.GPIO2,
    BREAK  = esp.GPIO12,
    DOOR   = esp.GPIO4,
    TOGGLE = esp.GPIO14
  }

  function clearPinCBs(pintable) 
    local name
    local pin
    for name, pin in pairs(pintable) do
      gpio.trig(pin, "none")
    end
  end

  function breakcb(level, when)     -- break is used to stop the program
    print("break")
    device.timer:unregister()
    clearPinCBs(pin)
    if file.exists("init.lua") then
      print("Config file exists")
      file.rename("init.lua", "noinit.lua")
    end
    sb = "-- uart.setup(0, 115200, 8, 0, 1, 1)"
    fd = file.open("init.lua", "w")
    if fd then
      fd:writeline(sb)
      fd:close()
      fd = nil
    end
    node.restart()
  end

  clearPinCBs(pin)

  hcsr04 = {};

  pinval = { [gpio.LOW] = "LOW",
             [gpio.HIGH] = "HIGH"
  }

  gpio.mode(pin.led1, gpio.OUTPUT)
  gpio.mode(pin.led2, gpio.OUTPUT)
  gpio.mode(pin.DOOR, gpio.OUTPUT)

  gpio.write(pin.led1, gpio.LOW);
  gpio.write(pin.led2, gpio.LOW);
  gpio.write(pin.DOOR, gpio.LOW);

  gpio.mode(pin.BREAK, gpio.INT, gpio.PULLUP)
  gpio.trig(pin.BREAK, "down", breakcb )

  wifi.sta.disconnect()

  function hcsr04.init(pin_trig, pin_echo)
    local self = {}
    self.time_start = 0
    self.time_end = 0
    self.lastGoodDistance = 0
    self.lastGoodDistanceTime = 0

    self.pin_trig = pin_trig -- or 3
    self.pin_echo = pin_echo -- or 4
    gpio.trig(self.pin_trig, "none")
    gpio.trig(self.pin_echo, "none")


    gpio.mode(self.pin_trig, gpio.OUTPUT)
    gpio.mode(self.pin_echo, gpio.INT)
    gpio.write(self.pin_trig, gpio.LOW)
    
    function self.echo_cb(level, when )
      if level == gpio.HIGH then
        self.time_start = when
        self.time_end = 0
        gpio.trig(self.pin_echo, "down", self.echo_cb)
      else
        self.time_end = when 
      end
      -- print("w=", when, ", l=" .. level)
    end

    function self.ping(type)
      -- print("ping at " .. tmr.now() .. ", type =" .. type)
      gpio.trig(self.pin_echo, type, self.echo_cb)
      gpio.write(self.pin_trig, gpio.HIGH)
      tmr.delay(100)
      gpio.write(self.pin_trig, gpio.LOW)
    end

    function self.measure()
      local diff = self.time_end - self.time_start
      local distance = (diff +  74) / 148
      if diff < 0 then
        return -1
      end
      return distance
    end

    self.ping("none") 
    return self
  end

  function onconnect(conn)
    conn:on("receive", 
      function(client, request)
        local buf = "";
        local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
        print("-------------receive-----------")
        print(request)
        if(method == nil)then
          _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
        end
        local _GET = {}
        if (vars ~= nil)then
          for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
            _GET[k] = v
          end
        end
                 
        local _on,_off = "",""
        if(_GET.pin == "ON1")then
          gpio.write(pin.led1, gpio.HIGH);
          -- gpio.write(esp.GPIO4, gpio.HIGH)
        elseif(_GET.pin == "OFF1")then
          gpio.write(pin.led1, gpio.LOW);
          -- gpio.write(esp.GPIO4, gpio.LOW)
        elseif(_GET.pin == "ON2")then
          gpio.write(pin.led2, gpio.HIGH);
        elseif(_GET.pin == "OFF2")then
          gpio.write(pin.led2, gpio.LOW);
        elseif(_GET.pin == "ONDOOR")then
          gpio.write(pin.DOOR, gpio.HIGH);
        elseif(_GET.pin == "OFFDOOR")then
          gpio.write(pin.DOOR, gpio.LOW);
        elseif(_GET.pin == "PULSEDOOR")then
       	  gpio.write(pin.DOOR, gpio.LOW);
          tmr.create():alarm(500, tmr.ALARM_SINGLE, function (mytimer) 
           	  gpio.write(pin.DOOR, gpio.HIGH);
	          tmr.create():alarm(1000, tmr.ALARM_SINGLE, function (mytimer) 
    	          gpio.write(pin.DOOR, gpio.LOW);
        	    end
        	  )    
        	end
          )    
        end

        buf = buf..[[<html>
<head> <meta content="text/html; charset="UTF-8">
<title>Sonar Relay ESP8266 Controller</title></head>
<body>
<h1> ESP8266 Web Server</h1>
<p>Distance from sensor ]] .. device.lastGoodDistance .. [[ inches, Measured at ]] .. device.lastGoodDistanceTime .. [[ </p>
<p>GPIO0 ]] .. pinval[gpio.read(pin.led1)] .. [[ <a href="?pin=ON1"><button>ON</button></a>&nbsp;
         <a href="?pin=OFF1"><button>OFF</button></a></p>
<p>GPIO2 ]] .. pinval[gpio.read(pin.led2)] .. [[ <a href="?pin=ON2"><button>ON</button></a>&nbsp;
         <a href="?pin=OFF2"><button>OFF</button></a></p>
<p>DOOR  ]] .. pinval[gpio.read(pin.DOOR)] .. [[ <a href="?pin=PULSEDOOR"><button>PULSE</button></a>&nbsp;
         <a href="?pin=ONDOOR"><button>ON</button></a>&nbsp;
         <a href="?pin=OFFDOOR"><button>OFF</button></a></p>
</body>
</html>         
]]
        
        print (buf)
        client:send(buf);
    end
    )
    conn:on("sent",
      function(conn) 
        conn:close() 
      end
    )
  end

  function startMeasuring()
    local device = hcsr04.init(pin.TRIG, pin.ECHO ) -- (trigger, echo)
    device.led1state = gpio.LOW
    device.timer = tmr.create()
    device.timer:register(1000, tmr.ALARM_SEMI, function (mytimer) 
        if device.led1state == gpio.LOW then
          device.led1state = gpio.HIGH
        else
          device.led1state = gpio.LOW
        end
        gpio.write(pin.led1, device.led1state)
        local distance = device.measure()
        if distance > 0 then
          device.lastGoodDistance = distance
          device.lastGoodDistanceTime = device.time_end
          --  print ("measure: start=" .. device.time_start .. ", end =" .. device.time_end .. ", diff= " .. (device.time_end - device.time_start) .. ", distance= " .. distance)
        end
        device.ping("up") 
        mytimer:start()
      end
    )
    device.timer:start()
    return device
  end    

  function gotipcb() 
    local status = wifi.sta.status()
    local ip = wifi.sta.getip()
    if status == nil then 
      print("status=nil")
    elseif wifistatus[status] == nil then 
      print("wifi_status[" .. status.. "]=nil")
    else
      print("wifi_status=".. wifistatus[status])
    end  
    if ip ~= nil then
      print("wifi_ip=".. ip)
    else
      print("wifi_ip=nil")
    end
    srv = net.createServer()
    srv:listen(80, onconnect)
  end

  wifi.setmode(wifi.STATION)

  station_cfg={
    ssid = "MYSSID",
    pwd = "mysecretpassword",
    got_ip_cb = gotipcb,
    auto = true,
    save = true
  }

  device = startMeasuring()
  wifi.sta.config(station_cfg)
  
end
print("Begin v1.2")
main()
6. Here is testserver.lua: It does much the same thing as myserver.lua but does not have the HC-SR04 distance measure code in it. The idea is to only have one or the other present, don't have both:

Code: Select all

print("Starting ...")

function main()
  device = {}  

  wifistatus = {
    [wifi.STA_IDLE] = "wifi.STA_IDLE",
    [wifi.STA_CONNECTING] = "wifi.STA_CONNECTING",
    [wifi.STA_WRONGPWD] = "wifi.STA_WRONGPWD",
    [wifi.STA_APNOTFOUND] = "wifi.STA_APNOTFOUND",
    [wifi.STA_FAIL] = "wifi.STA_FAIL",
    [wifi.STA_GOTIP] = "wifi.STA_GOTIP"
  }

  esp = {
    GPIO16 =  0,
    GPIO5 =   1,
    GPIO4 =   2,
    GPIO0 =   3,
    GPIO2 =   4,
    GPIO14 =  5,
    GPIO12 =  6,      
    GPIO13 =  7,
    GPIO15 =  8,
    GPIO3 =   9,
    GPIO1 =  10,
    GPIO9 =  11,
    GPIO10 = 12
  }

  pin = {
    TRIG   = esp.GPIO15,
    ECHO   = esp.GPIO5,
    led1   = esp.GPIO0,
    led2   = esp.GPIO2,
    BREAK  = esp.GPIO12,
    DOOR   = esp.GPIO4,
    TOGGLE = esp.GPIO14
  }

  function clearPinCBs(pintable) 
    local name
    local pin
    for name, pin in pairs(pintable) do
      gpio.trig(pin, "none")
    end
  end

  function breakcb(level, when)     -- break is used to stop the program
    print("break")
    device.timer:unregister()
    clearPinCBs(pin)
    if file.exists("init.lua") then
      print("Config file exists")
      file.rename("init.lua", "noinit.lua")
    end
    sb = "-- uart.setup(0, 115200, 8, 0, 1, 1)"
    fd = file.open("init.lua", "w")
    if fd then
      fd:writeline(sb)
      fd:close()
      fd = nil
    end
    node.restart()
  end

  clearPinCBs(pin)

  hcsr04 = {};

  pinval = { [gpio.LOW] = "LOW",
             [gpio.HIGH] = "HIGH"
  }

  gpio.mode(pin.led1, gpio.OUTPUT)
  gpio.mode(pin.led2, gpio.OUTPUT)
  gpio.mode(pin.DOOR, gpio.OUTPUT)

  gpio.write(pin.led1, gpio.LOW);
  gpio.write(pin.led2, gpio.LOW);
  gpio.write(pin.DOOR, gpio.LOW);

  gpio.mode(pin.BREAK, gpio.INT, gpio.PULLUP)
  gpio.trig(pin.BREAK, "down", breakcb )

  wifi.sta.disconnect()

  function hcsr04.init(pin_trig, pin_echo)
    local self = {}
    self.time_start = 0
    self.time_end = 0
    self.lastGoodDistance = 0
    self.lastGoodDistanceTime = 0

    self.pin_trig = pin_trig -- or 3
    self.pin_echo = pin_echo -- or 4
    gpio.trig(self.pin_trig, "none")
    gpio.trig(self.pin_echo, "none")


    gpio.mode(self.pin_trig, gpio.OUTPUT)
    gpio.mode(self.pin_echo, gpio.INT)
    gpio.write(self.pin_trig, gpio.LOW)
    
    function self.echo_cb(level, when )
      if level == gpio.HIGH then
        self.time_start = when
        self.time_end = 0
        gpio.trig(self.pin_echo, "down", self.echo_cb)
      else
        self.time_end = when 
      end
      -- print("w=", when, ", l=" .. level)
    end
    return self
  end

  function onconnect(conn)
    conn:on("receive", 
      function(client, request)
        local buf = "";
        local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
        print("-------------receive-----------")
        print(request)
        if(method == nil)then
          _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
        end
        local _GET = {}
        if (vars ~= nil)then
          for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
            _GET[k] = v
          end
        end
                 
        local _on,_off = "",""
        if(_GET.pin == "ON1")then
          gpio.write(pin.led1, gpio.HIGH);
          -- gpio.write(esp.GPIO4, gpio.HIGH)
        elseif(_GET.pin == "OFF1")then
          gpio.write(pin.led1, gpio.LOW);
          -- gpio.write(esp.GPIO4, gpio.LOW)
        elseif(_GET.pin == "ON2")then
          gpio.write(pin.led2, gpio.HIGH);
        elseif(_GET.pin == "OFF2")then
          gpio.write(pin.led2, gpio.LOW);
        end

        buf = buf..[[<html>
<head> <meta content="text/html; charset="UTF-8">
<title>Sonar Relay ESP8266 Controller</title></head>
<body>
<h1> ESP8266 Web Server</h1>
<p>GPIO0 ]] .. pinval[gpio.read(pin.led1)] .. [[ <a href="?pin=ON1"><button>ON</button></a>&nbsp;
         <a href="?pin=OFF1"><button>OFF</button></a></p>
<p>GPIO2 ]] .. pinval[gpio.read(pin.led2)] .. [[ <a href="?pin=ON2"><button>ON</button></a>&nbsp;
         <a href="?pin=OFF2"><button>OFF</button></a></p>
</body>
</html>         
]]
        print (buf)
        client:send(buf);
    end
    )
    conn:on("sent",
      function(conn) 
        tmr.create():alarm(1500, tmr.ALARM_SINGLE, function (mytimer) 
            conn:close() 
            end
          )
      end
    )
  end

  function startMeasuring()
    local device = hcsr04.init(pin.TRIG, pin.ECHO ) -- (trigger, echo)
    device.led1state = gpio.LOW
    device.timer = tmr.create()
    device.timer:register(1000, tmr.ALARM_SEMI, function (mytimer) 
        if device.led1state == gpio.LOW then
          device.led1state = gpio.HIGH
        else
          device.led1state = gpio.LOW
        end
        gpio.write(pin.led1, device.led1state)
        mytimer:start()
      end
    )
    device.timer:start()
    return device
  end    

  function gotipcb() 
    local status = wifi.sta.status()
    local ip = wifi.sta.getip()
    if status == nil then 
      print("status=nil")
    elseif wifistatus[status] == nil then 
      print("wifi_status[" .. status.. "]=nil")
    else
      print("wifi_status=".. wifistatus[status])
    end  
    if ip ~= nil then
      print("wifi_ip=".. ip)
    else
      print("wifi_ip=nil")
    end
    srv = net.createServer()
    srv:listen(80, onconnect)
  end

  wifi.setmode(wifi.STATION)

  station_cfg={
    ssid = "MYSSID",
    pwd = "mysecretwifipassword",
    got_ip_cb = gotipcb,
    auto = true,
    save = true
  }

  device = startMeasuring()
  wifi.sta.config(station_cfg)
  
end
print("Begin v2.4")
main()

7. Here is uploader.lua. This will let you telnet to your esp8266 which is much cleaner that the serial port. You will have had to establish your wifi connection before this

Code: Select all

-- a simple telnet server
telnet_srv = net.createServer(net.TCP, 180)
telnet_srv:listen(2323, function(socket)
    local fifo = {}
    local fifo_drained = true

    local function sender(c)
      if #fifo > 0 then
        c:send(table.remove(fifo, 1))
      else
        fifo_drained = true
      end
    end

    local function s_output(str)
      table.insert(fifo, str)
      if socket ~= nil and fifo_drained then
        fifo_drained = false
        sender(socket)
      end
    end

    node.output(s_output, 0)   -- re-direct output to function s_ouput.

    socket:on("receive", function(c, l)
        node.input(l)           -- works like pcall(loadstring(l)) but support multiple separate line
      end
    )
    socket:on("disconnection", function(c)
        node.output(nil)        -- un-regist the redirect output function, output goes to serial
      end
    )

    socket:on("sent", sender)
    print("Welcome to NodeMCU world.")
  end
)

8. The reason to give all this code is that when I started, I just wrote staright-line code with sleeps to get my wifi connect. This is a bad idea as it is unreliable. It's much better to create event routines. In fact, I suggest that whenever you are tempted to sleep to wait for something to happen, its a good idea to see if there is a "onCondition" callback available. Sorry about the few comments but I hope the code is short enough to make sense.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sun Sep 30, 2018 3:18 am

petermeigs wrote:
Sat Sep 29, 2018 5:03 pm
Some esp8266 tips:
a. Be careful of which gpio pins you use, ...
b. I like raspberry pi on the esp8266 ...linux serial issues
c. can use a simple ribbon cable for the serial connection.

ESP8266 pins

Ah, I think you are at least 6 months ahead of me. So I only understand about 10% of what you are saying. As last time playing with power electronics and A3700 etc, I will google slowly to try to understand every step.

I agree it is a good idea to use serial signals directly, and not with USB. So my first step is to get to know what the pins are doing.

So far I have only written one newbie program - Hello World. My next program is of course still newbie - Blinky!

I need to decide first which LED to blink. I am too lazy to wire my own LED, so I will be blinking the built in LED connected to GPIO 16, ...
Attachments
esp8266_pinout_2018sep3002.jpg
esp8266_pinout_2018sep3002.jpg (180.86 KiB) Viewed 3125 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sun Sep 30, 2018 6:16 am

petermeigs wrote:
Sat Sep 29, 2018 5:03 pm
1. I like esp_flasher from nodemcu flashing the esp8266. (http://www.nodemcu.com) It is the most trouble free. Be carefully to fully erase the eprom before you start to get rid of old files on it. I've lost my notes on how to do that but I don't recall it being very hard.

2. Here is myserver.lua. It will do the wifi connection for you after you update the tables with your ssid and key. Note that it uses a callback for the connection. This is much more reliable than straight line coding.

3. The reason to give all this code is that when I started, I just wrote staright-line code with sleeps to get my wifi connect. This is a bad idea as it is unreliable. It's much better to create event routines. In fact, I suggest that whenever you are tempted to sleep to wait for something to happen, its a good idea to see if there is a "onCondition" callback available.

Flashing and Wifi Connection Reliability

1. I remember the first time I used esptool to flash to the esp8266 chip, esptool completed the job and said the hash thing was checked OK. So I could sleep well.

But later when I tried other flash tools, I noticed that most of them recommend to clear the flash first. I guess this means that the flash processes is not that reliable. I remember I found a flash program from NodeMcu, but I think they only have a Windows version, linux not entertained.

Flash Download Tools (ESP8266 & ESP32) Windows PC V3.6.4 2018.03.06
https://www.espressif.com/en/support/do ... ther-tools

2. Your suggestion on server setup and connection is a bit too advanced for me (I always feel uncomfortable or nervous using interrupt/callback. I always use looping instead.). I have never setup any proper Rpi Wifi server because I never needed to. I did use wired SSH server once or twice, but I found using Windows superTerm or teraTerm (not to mention the stupid puTTY) not that user friendly. So these years I always have a dedicated keyboard, mouse and mon for my Rpi, almost never SSHing.

3. Again your suggestion of Wifi connection using the event thing is too advanced for me. I know I need to face these ugly things sooner or later, but not now when the newbie is busy writing his great blinky program.

But when I googled about Esp8266 wireless things earlier, I found guys talking about noise problems and unreliable connections. So earlier when I find one TabBao shop selling their USB to TTL cable, boasting that their cable is very good, because they are using the very reliable CH340 chip, and that they use a very big 1000uF to by pass the noise, I got somewhat brainwashed and ordered their high class, highly reliable 9 yuan cable. Their ad even said their cable is HGT (High, Great, and Trendy), so you will lose face using old things like FTDI.
Attachments
esp8266_usb_cable_2018sep3001.jpg
esp8266_usb_cable_2018sep3001.jpg (119.31 KiB) Viewed 3111 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sun Sep 30, 2018 7:20 am

tlfong01 wrote:
Sun Sep 30, 2018 6:16 am
Flashing and Wifi Connection Reliability
But when I googled about Esp8266 wireless things earlier, I found guys talking about noise problems and unreliable connections. So earlier when I find one TabBao shop selling their USB to TTL cable, boasting that their cable is very good, because they are using the very reliable CH340 chip, and that they use a very big 1000uF to by pass the noise, I got somewhat brainwashed and ordered their high class, highly reliable 9 yuan cable. Their ad even said their cable is HGT (High, Great, and Trendy), so you will lose face using old things like FTDI.

NodeMcu Auto Program Signals

I found the buttons Reset and Flash a bit confusing. I only know that for my version of NodeMcu, I don't need to press any button when flashing. But the earlier version needs. So I read the schematic to clear my mind.
Attachments
usb_to_uart_cct_2018sep3001.jpg
usb_to_uart_cct_2018sep3001.jpg (154.73 KiB) Viewed 3100 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sun Sep 30, 2018 7:58 am

tlfong01 wrote:
Sun Sep 30, 2018 7:20 am
Flashing and Wifi Connection Reliability
But when I googled about Esp8266 wireless things earlier, I found guys talking about noise problems and unreliable connections. So earlier when I find one TabBao shop selling their USB to TTL cable, boasting that their cable is very good, because they are using the very reliable CH340 chip, and that they use a very big 1000uF to by pass the noise, I got somewhat brainwashed and ordered their high class, highly reliable 9 yuan cable. Their ad even said their cable is HGT (High, Great, and Trendy), so you will lose face using old things like FTDI.

Fake USB to TTL Drivers

One annoying thing I found with my USB to TTL drivers is that whenever I upgrade my Windows, from XT to Win7, to Win10 and so on, the old drivers won't work and the manufacturers almost always do not update the drivers for their old hardware, and you must buy their new version hardware.

And sometimes some seemingly good guys volunteer to update the drivers for the bad manufacturers. But usually the seemingly good guys' get around drivers don't work either, and most sadly of all, is that they trick or mislead you to upload some useless or virus or trojan horse programs, which are very difficult to get rid off, and I need to waste time reinstall the whole new Windows, sometimes losing valuable and unrecoverable data files.

I once thought that most such bad guys are small guys, but then I found big guys can be worse. One example is FTDI as described by Wikipedia:
https://en.wikipedia.org/wiki/FTDI

...

Driver controversy

On 29 September 2014, FTDI released an updated version of their USB-to-Serial driver for Windows on their website. Users who manually downloaded the new drivers reported problems.

After Windows drivers became available on 14 October (Patch Tuesday) via Windows Update, it was reported by users of hardware enthusiast forums and websites that the drivers could soft brick counterfeit and software-compatible clones of the chips by changing their USB "Product ID" to "0000".

The change prevents the chip from being recognized by drivers of any OS, effectively making them inoperable unless the product ID is changed back.

The behaviour was supported by a notice in the drivers' end user license agreement, which warned that use of the drivers with non-genuine FTDI products would "irretrievably damage" them.

Critics felt that FTDI's actions were unethical, considering that users may be unaware that their chips were counterfeit, or that Windows had automatically installed a driver meant to disable them.

On 22 October 2014, an emergency patch was made to the FTDI drivers in the Linux kernel to recognize devices with the "0000" ID.

On 24 October 2014, in response to the criticism, FTDI withdrew the driver and admitted that the measure was intended to protect its intellectual property and encourage users to purchase genuine FTDI products.

The company also stated that it was working to create an updated driver which would notify users of non-genuine FTDI products in a "non-invasive" manner.

In February 2016, it was reported that FTDI had published another driver on Windows Update with DRM components intended to block non-genuine products.

This time, the driver will communicate with affected devices, but all transmitted and received data is replaced with the arbitrary, looped ASCII string "NON GENUINE DEVICE FOUND!", which could cause irregular interactions with devices.


It's A Sin - Pet Shop Boys 44,455,619 views
https://www.youtube.com/watch?v=dRHetRTOD1Q
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Mon Oct 01, 2018 2:23 am

tlfong01 wrote:
Sat Sep 29, 2018 2:48 pm
One Dollar ESP8266 Compatible Relay (ESP8266 Not Included!)
https://www.aliexpress.com/item/ESP8266 ... 6f1dd319-8

ESP01 WiFi Relay References

SODIAL ESP8266 ESP-01S 5V WiFi Relay Module $4.66
https://www.amazon.com/SODIAL-ESP8266-E ... 07B6HN77B
Top customer reviews - September 13, 2018
https://www.amazon.com/SODIAL-ESP8266-E ... merReviews

It says they have the APP and that it is very simple to install. That couldn't be more far from the truth.
The seller, just replied once, 30 days ago saying she will get in contact soon. And Since that last email.-- Radio Silence.
No app, no manual nor instructions. No nothing. not even links to anything.
I have researched in multiple places, and there is no easy way to setup and use these things. You need to hack the device, do some hardware changes, and then upload a modified code. Assuming you are experienced and comfortable coding in Arduino and hacking electronics.


ESP-01S Relay v1.0 Datasheet
http://himalayansolution.com/storage/do ... KntDAX.pdf

Control a Relay From Anywhere Using the ESP8266 - Marco Schwartz
https://openhomeautomation.net/control- ... re-esp8266

ESP8266 WiFi 5V Relay $12.99
https://www.amazon.com/WHDTS-ESP8266-Ch ... CRXWBCPMBP

SP01/01S RELAY MODULE TUTORIAL - TechnologyWireless
https://www.instructables.com/id/ESP010 ... -TUTORIAL/
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Mon Oct 01, 2018 4:45 am

tlfong01 wrote:
Sun Sep 30, 2018 6:16 am
Flashing and Wifi Connection Reliability
But when I googled about Esp8266 wireless things earlier, I found guys talking about noise problems and unreliable connections. So earlier when I find one TabBao shop selling their USB to TTL cable, boasting that their cable is very good, because they are using the very reliable CH340 chip, and that they use a very big 1000uF to by pass the noise, I got somewhat brainwashed and ordered their high class, highly reliable 9 yuan cable. Their ad even said their cable is HGT (High, Great, and Trendy), so you will lose face using old things like FTDI.

My fake FTDI USB to TTL cable

I have an old USB to TTL adapter cable, using the PL2302HX chip. The USB end of the adapter marked "FTDI 232". I am not sure if this means my cable is a fake FTDI cable. Anyway, I found the TTL end has two Vcc pads, one marked 5V, the other 3V3 which is not connected. I guess I need to use 3V3 signals for ESP8266. So I am going to shift the wire from 5V0 to 3V3.
Attachments
pl2303hx_usb_ttl_2018oct0101.jpg
pl2303hx_usb_ttl_2018oct0101.jpg (141.01 KiB) Viewed 3056 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Mon Oct 01, 2018 5:53 am

tlfong01 wrote:
Mon Oct 01, 2018 4:45 am
tlfong01 wrote:
Sun Sep 30, 2018 6:16 am
Flashing and Wifi Connection Reliability
But when I googled about Esp8266 wireless things earlier, I found guys talking about noise problems and unreliable connections. So earlier when I find one TabBao shop selling their USB to TTL cable, boasting that their cable is very good, because they are using the very reliable CH340 chip, and that they use a very big 1000uF to by pass the noise, I got somewhat brainwashed and ordered their high class, highly reliable 9 yuan cable.
My fake FTDI USB to TTL cable
I have an old USB to TTL adapter cable, using the PL2302HX chip. The USB end of the adapter marked "FTDI 232". I am not sure if this means my cable is a fake FTDI cable. Anyway, I found the TTL end has two Vcc pads, one marked 5V, the other 3V3 which is not connected. I guess I need to use 3V3 signals for ESP8266. So I am going to shift the wire from 5V0 to 3V3.

Cheap fake FTDI USB to TTL cable keyboard echo testing notes

I shorted Tx to Rx and checked if keyboard input is echoed to console output. Everything goes well.
Attachments
usb_ttl_echo_2018oct0101.jpg
usb_ttl_echo_2018oct0101.jpg (156.06 KiB) Viewed 3046 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Mon Oct 01, 2018 6:58 am

tlfong01 wrote:
Mon Oct 01, 2018 5:53 am
I shorted Tx to Rx and checked if keyboard input is echoed to console output. Everything goes well.

Stack Overflow's 1,324 Esp8266 Questions

I don't know how to test my esp8266-12. So I go to Stack Overflow and see if other guys ask the same questions. There are 1,324 questions tagged with esp8266, and search [esp8266] + LUA gives 458 results. So 458/1324 = 34% of questions are on LUA. That is surprising.

By the way, I also googled to have confirmed that javascript is indeed not like MIT App Inventor, a toy language for children.

Top 5 Programming Languages to Learn in 2018 ... - 1,414,305 views
https://www.youtube.com/watch?v=f3EbDbm8XqY

Stack Overflow is 10! - 29,958 views
https://www.youtube.com/watch?v=QwS1r1m ... nniversary

Stack Overflow esp8266 Questions tagged - 1,324 questions
https://stackoverflow.com/questions/tagged/esp8266

ESP8266 is a highly integrated chip designed for the needs of an increasingly connected world. It offers a complete and self-contained Wi-Fi networking solution, allowing it to either host applications or offload all Wi-Fi networking functions from another application processor.
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Mon Oct 01, 2018 9:11 am

tlfong01 wrote:
Mon Oct 01, 2018 5:53 am
Cheap fake FTDI USB to TTL cable keyboard echo testing notes
I shorted Tx to Rx and checked if keyboard input is echoed to console output. Everything goes well.

ESP8266 UART connection testing notes

I connected the PL2303HX USB to 3V3 TTL cable to ESP8266 and used TeraTerm serial 115,200 buad. I send string "AT" etc and found that ESP8266 seems to hear something and return the prompt > and >>.

Then it sent event detection messages. I don't know how to tell ESP8266 not to bother detecting events. I need to read the manual again.

Anyway, I closed the TeraTerm and used ESPlorer to open COM3 115,200 and sent print('hello world') statement and found results window displayed results OK.

So my experiment of interfacing ESP8266's 3V3 UART Tx Rx signals seems OK. I am thinking what to do next, playing AT commands, or using Rpi/Wind10 LUA5.1.x to send and receive text data at the COM port.

Or should I go back to write my newbie blinky program first?
Attachments
esp8266_ttl_uart_test_2018oct0101.jpg
esp8266_ttl_uart_test_2018oct0101.jpg (170.28 KiB) Viewed 3021 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Mon Oct 01, 2018 2:11 pm

tlfong01 wrote:
Mon Oct 01, 2018 9:11 am
Then it sent event detection messages. I don't know how to tell ESP8266 not to bother detecting events. I need to read the manual again.
So my experiment of interfacing ESP8266's 3V3 UART Tx Rx signals seems OK. I am thinking what to do next, playing AT commands, or using Rpi/Wind10 LUA5.1.x to send and receive text data at the COM port.
Or should I go back to write my newbie blinky program first?

Trying AI Thinker Firmware

I now think that NodeMcu firmware might be too advanced for a newbie like me, because I have very little experience of using callbacks and therefore should not start any NodeMcu event driven programming now. I think I will try a simple firmware.

I have successfully flashed the AI Thinker firmware to the ESP8266 board, but then ESPlorer cannot connect to the board - I need to read the manual again. :(

Appendix - Flashing AI Thinker Firmware using Win10 Power Shell

PS D:\work\rpi_forum\nodemcu\ai_firmware> esptool --port=COM9 write_flash -fm=dio -fs=4MB 0x00000 ai-thinker-0.9.5.2-115200.bin

esptool.py v2.5.1
Serial port COM9
Connecting....
Detecting chip type... ESP8266
Chip is ESP8266EX
Features: WiFi
MAC: 5c:cf:7f:78:15:ab
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Flash params set to 0x0240
Compressed 520192 bytes to 165300...
Wrote 520192 bytes (165300 compressed) at 0x00000000 in 14.6 seconds (effective 285.9 kbit/s)...
Hash of data verified.


Leaving...
Hard resetting via RTS pin...
PS D:\work\rpi_forum\nodemcu\ai_firmware>
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Mon Oct 01, 2018 2:33 pm

tlfong01 wrote:
Mon Oct 01, 2018 2:11 pm
Trying AI Thinker Firmware
I have successfully flashed the AI Thinker firmware to the ESP8266 board, but then ESPlorer cannot connect to the board - I need to read the manual again. :(

AI Thinker Firmware is not LUA, only an AT command interpreter!

I tried connecting again and this time succeeded. I sent a LUA print statement but got an error message. I then guessed that AI Thinker is no LUA, perhaps only an AT command interpreter. I have little idea what this means. I only remember the blogger Big Dan played with AT commands. I need to visit his blog again, ...

Can I write a batch file to set up the ESP8266 board to do WiFi? I need to google longer this time, ...
Attachments
ai_thinker_test_2018oct0101.jpg
ai_thinker_test_2018oct0101.jpg (162.96 KiB) Viewed 3004 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Mon Oct 01, 2018 2:57 pm

tlfong01 wrote:
Mon Oct 01, 2018 2:33 pm
AI Thinker Firmware is not LUA, only an AT command interpreter!
I tried connecting again and this time succeeded. I sent a LUA print statement but got an error message. I then guessed that AI Thinker is no LUA, perhaps only an AT command interpreter. I have little idea what this means. I only remember the blogger Big Dan played with AT commands. I need to visit his blog again, ...

AI Thinker ESP12S AT Commands
Attachments
at_command_2018oct0101.jpg
at_command_2018oct0101.jpg (166.53 KiB) Viewed 3001 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Tue Oct 02, 2018 7:02 am

petermeigs wrote:
Sat Sep 29, 2018 5:03 pm
... I like using a raspberry pi for working on the esp8266.
... Yes, you have to deal with linux serial issues but its not that hard. The benefit is that you can use a simple ribbon cable for the serial connection.

Rpi to ESP8266 using 3V3 UART / +-5V RS232 serial connection

Yes, using 3V3 UART and +-5V RS232 serial is a good idea. I am thinking of letting Rpi to directly talk to ESP8266, using 4,800 baud at a distance of 200 meters, so I can place my Rpi3B+ at home, and the rooftop garden ESP8266 5 floors above, using D-Sub 9, double shielded cables, ...

I will be using python at the Rpi end, and NodeMcu LUA serial modules at the ESP8266 end. I guess Python/LUA UART programming should be much easier than I2C.
Attachments
roof_top_garden_connect_2018oct0201.jpg
roof_top_garden_connect_2018oct0201.jpg (184.36 KiB) Viewed 2979 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Tue Oct 02, 2018 7:07 am

tlfong01 wrote:
Tue Oct 02, 2018 7:02 am
Yes, using 3V3 UART and +-5V RS232 serial is a good idea. I am thinking of letting Rpi to directly talk to ESP8266, using 4,800 baud at a distance of 200 meters, so I can place my Rpi3B+ at home, and the rooftop garden ESP8266 5 floors above, using D-Sub 9, double shielded cables, ...

3V3 UART TTL to +-5V RS232 Converter Module

And this is the converter I will be using.
Attachments
ttl_to_rs232_2018oct0201.jpg
ttl_to_rs232_2018oct0201.jpg (180.28 KiB) Viewed 2978 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Tue Oct 02, 2018 8:48 am

tlfong01 wrote:
Tue Oct 02, 2018 7:07 am
tlfong01 wrote:
Tue Oct 02, 2018 7:02 am
Yes, using 3V3 UART and +-5V RS232 serial is a good idea. I am thinking of letting Rpi to directly talk to ESP8266, using 4,800 baud at a distance of 200 meters, so I can place my Rpi3B+ at home, and the rooftop garden ESP8266 5 floors above, using D-Sub 9, double shielded cables, ...

Tidying up PL2303HX USB to TTL to ESP8266 TTL wiring
Attachments
usb_ttl_connect_2018oct0202.jpg
usb_ttl_connect_2018oct0202.jpg (175.5 KiB) Viewed 2961 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Wed Oct 03, 2018 4:02 am

tlfong01 wrote:
Mon Oct 01, 2018 2:57 pm
tlfong01 wrote:
Mon Oct 01, 2018 2:33 pm
AI Thinker Firmware is not LUA, only an AT command interpreter!
AI Thinker ESP12S AT Commands

Newbie Learning notes on ESP8266 AT Commands

So I have flashed my modules with AI Thinker's firmware, and found that it is only an AT command interpreter. I don't know what are those AT commands. So I googled the datasheet and made a summary, for a newbie like me to try out.

ESP8266 AT Commands - newbie learning notes v1.0

ESP8266 AT Instruction Set Version 2.2.1 (70 pages!) - Espressif 2018
https://ieee-sensors.org/wp-content/upl ... set_en.pdf

(note - AI Thinker firmware does not always match ESP8266 manual)

The AT commands can be divided according to applications:

1. Basic AT commands,

2. Wi-Fi AT commands, and

3. TCP/IP AT commands.


The AT commands can also divided according to functions:

1. Test Command AT+<x>=? - Queries the Set Commands’ internal parameters and their range of values.

2. Query Command AT+<x>? - Returns the current value of parameters.

3. Set Command AT+<x>=<…> - Sets the value of user-defined parameters in commands, and runs these commands.

4. Execute Command AT+<x> - Runs commands with no user-defined parameters.

These are basic AT commands for newbies:

1. AT - Tests AT startup.

2. AT+RST - Restarts the module.

3. AT+GMR - Checks version information.

4. AT+UART_CUR? - Checks current UART configuration.

5. AT+RESTORE - Restores the factory default settings of the module.


These are the Wifi commands for newbies:

1. AT+CWMODE=1 - Set module to station mode
(note - not AT+CWMODE_CUR=1)

2. AT+CWAP - Lists all nearby access points


Appendix - AT Commands Summary

Contents

Chapter 1 Overview Provides instructions on user-defined AT commands and downloading of AT firmware.

Chapter 2 Command Description Gives a basic description of AT commands.

Chapter 3 Basic AT Commands Lists AT commands of basic functions.

Chapter 4 Wi-Fi AT Commands Lists Wi-Fi-related AT commands.

Chapter 5 TCP/IP-Related AT Commands Lists TCP/IP-related AT commands.

Chapter 6 Appendix A Lists the AT commands of which the configuration is saved in the flash.

Chapter 7 Appendix B Lists messages of AT firmware.

Chapter 8 Q & A Provides information on where and how to consult questions about ESP8266 AT commands.

Basic AT Commands (22)

AT Tests AT startup.

AT+RST Restarts the module.

AT+GMR Checks version information.

AT+GSLP Enters Deep-sleep mode.

ATE Configures echoing of AT commands.

AT+RESTORE Restores the factory default settings of the module.

AT+UART UART configuration. [@deprecated]

AT+UART_CUR The current UART configuration.

AT+UART_DEF The default UART configuration, saved in flash.

AT+SLEEP Configures the sleep modes.

AT+WAKEUPGPIO Configures a GPIO to wake ESP8266 up from Light-sleep mode.

AT+RFPOWER Sets the maximum value of the RF TX Power.

AT+RFVDD Sets the RF TX Power according to VDD33.

AT+RFAUTOTRACE Sets RF frequency offset trace.

AT+SYSRAM Checks the available RAM size.

AT+SYSADC Checks the ADC value.

AT+SYSIOSETCFG Sets configuration of IO pins.

AT+SYSIOGETCFG Gets configuration of IO pins.

AT+SYSGPIODIR Configures the direction of GPIO.

AT+SYSGPIOWRITE Configures the GPIO output level

AT+SYSGPIOREAD Checks the GPIO input level.

AT+SYSMSG_CUR Sets current system messages.

Wifi Commands (40)

AT+CWMODE Sets the Wi-Fi mode (Station/AP/Station+AP). [@deprecated]

AT+CWMODE_CUR Sets the Wi-Fi mode (Station/AP/Station+AP); configuration not saved in the flash.

AT+CWMODE_DEF Sets the default Wi-Fi mode (Station/AP/Station+AP); configuration saved in the flash.

AT+CWJAP Connect to an AP. [@deprecated]

AT+CWJAP_CUR Connects to an AP; configuration not saved in the flash.

AT+CWJAP_DEF Connects to an AP; configuration saved in the flash.

AT+CWLAPOPT Sets the configuration of command AT+CWLAP.

AT+CWLAP Lists available APs.

AT+CWQAP Disconnects from an AP.

AT+CWSAP Sets the configuration of the ESP8266 SoftAP. [@deprecated]

AT+CWSAP_CUR Sets the current configuration of the ESP8266 SoftAP; configuration not saved in the flash.

AT+CWSAP_DEF Sets the configuration of the ESP8266 SoftAP; configuration saved in the flash.

AT+CWLIF Gets the Station IP to which the ESP8266 SoftAP is connected

AT+CWDHCP Enables/Disables DHCP. [@deprecated]

AT+CWDHCP_CUR Enables/Disables DHCP; configuration not saved in the flash.

AT+CWDHCP_DEF Enable/Disable DHCP; configuration saved in the flash.

AT+CWDHCPS_CUR Sets the IP range of the DHCP server; configuration not saved in the flash.

AT+CWDHCPS_DEF Sets the IP range of the DHCP server; configuration saved in the flash.

AT+CWAUTOCONN Connects to an AP automatically on power-up.

AT+CIPSTAMAC Sets the MAC address of the ESP8266 Station. [@deprecated]

AT+CIPSTAMAC_CUR Sets the MAC address of the ESP8266 Station; configuration not saved in the flash.

AT+CIPSTAMAC_DEF Sets the MAC address of ESP8266 station; configuration saved in the flash.

AT+CIPAPMAC Sets the MAC address of the ESP8266 SoftAP. [@deprecated]

AT+CIPAPMAC_CUR Sets the MAC address of the ESP8266 SoftAP; configuration not saved in the flash.

AT+CIPAPMAC_DEF Sets the MAC address of the ESP8266 SoftAP; configuration saved in the flash.

AT+CIPSTA Sets the IP address of the ESP8266 Station. [@deprecated]

AT+CIPSTA_CUR Sets the IP address of the ESP8266 Station; configuration not saved in the flash.

AT+CIPSTA_DEF Sets the IP address of the ESP8266 Station; configuration saved in the flash.

AT+CIPAP Sets the IP address of ESP8266 SoftAP. [@deprecated]

AT+CIPAP_CUR Sets the IP address of ESP8266 SoftAP; configuration not saved in the flash.

AT+CIPAP_DEF Sets the IP address of ESP8266 SoftAP; configuration saved in the flash.

AT+CWSTARTSMART Starts SmartConfig.

AT+CWSTOPSMART Stops SmartConfig.

AT+CWSTARTDISCOVER Enables the mode that ESP8266 can be found by WeChat.

AT+CWSTOPDISCOVER Disables the mode that ESP8266 can be found by WeChat.

AT+WPS Sets the WPS function.

AT+MDNS Sets the MDNS function.

AT+CWHOSTNAME Sets the host name of the ESP8266 Station.

AT+CWHOSTNAME Sets the host name of the ESP8266 Station.

AT+CWCOUNTRY_CUR Sets current WiFi country code

AT+CWCOUNTRY_DEF Sets default WiFi country code

Return Messages (12)

ready The AT firmware is ready.

ERROR AT command error, or error occurred during execution.

WIFI CONNECTED ESP8266 station connected to an AP.

WIFI GOT IP ESP8266 station got IP address.

WIFI DISCONNECT ESP8266 station disconnected from an AP.

busy s... Busy sending. The system is sending data now, cannot accept the newly input.

busy p... Busy processing. The system is in process of handling the previous command, cannot accept the newly input.

<conn_id>,CONNECT A network connection of which ID is <conn_id> is established.

<conn_id>,CLOSED A network connection of which ID is <conn_id> ends.

+IPD Received network data.

+STA_CONNECTED:<sta_mac> A station connects to the ESP8266 softAP.

+DIST_STA_IP:<sta_mac>,<sta_ip> ESP8266 softAP distributes an IP address to the station connected.

+STA_DISCONNECTED:<sta_mac> A station disconnects from the ESP8266 softAP.

.END
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Wed Oct 03, 2018 6:38 am

tlfong01 wrote:
Wed Oct 03, 2018 4:02 am
Newbie Learning notes on ESP8266 AT Commands

ESP8266 AT Command Testing Notes

So I tested some of the basic AT commands and found things more or less OK.

*** Config ***
ESPlorer v0.20-rc5 by 4refrOnt
ai-thinker-0.9.5.2-115200bin (2018/10/1 508kB)

*** AI Thinker Firmware Download Record ***


PS D:\work\rpi_forum\nodemcu\ai_thinker_firmware> esptool --port=COM10 write_flash -fm=dio -fs=4MB 0x00000 ai-thinker-0.9.5.2-115200.bin
esptool.py v2.5.1
Serial port COM10
Connecting....
Detecting chip type... ESP8266
Chip is ESP8266EX
Features: WiFi
MAC: 84:f3:eb:7b:2d:55
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Flash params set to 0x0240
Compressed 520192 bytes to 165300...
Wrote 520192 bytes (165300 compressed) at 0x00000000 in 14.7 seconds (effective 283.4 kbit/s)...
Hash of data verified.

*** AT Command Testing tlfong01 2018oct03 ***

PORT OPEN 115200
Communication with MCU..Got answer! Communication with MCU established.
AutoDetect firmware...
Can't autodetect firmware, because proper answer not received (may be unknown firmware).
Please, reset module or continue. [press reset button]
���������������������������齔�驊����檭蔞��[鷟瀦_譋逜~�蝢�<�.q�.粿龢ss貏�銳s^^蔍�9\�>&0�3�Q�1'

Ai-Thinker Technology Co. Ltd.

ready

AT

OK

AT+GMR

AT version:0.21.0.0
SDK version:0.9.5
OK

AT+CWMODE=?

+CWMODE:(1-3)
OK

AT+CWMODE=1

OK

AT+CIFSR

+CIFSR:STAIP,"0.0.0.0"
+CIFSR:STAMAC,"18:fe:34:78:15:ab"

OK
AT+CWLAP

+CWLAP:(2,"KaiOffice",-85,"c8:3a:35:45:c7:50",1)
+CWLAP:(3,"tlfong01",-35,"20:e5:2a:32:07:de",1)
+CWLAP:(4,"TP-LINK_41FC",-94,"b8:f8:83:8b:41:fc",1)
+CWLAP:(4,"Wong",-90,"c8:3a:35:61:96:e1",1)
+CWLAP:(4,"Kavita",-91,"14:91:82:9a:8a:55",1)
+CWLAP:(4,"FanFan",-92,"ac:84:c6:e6:42:1f",2)
+CWLAP:(3,"amyp",-88,"34:97:f6:5d:75:b8",3)
+CWLAP:(3,"jojotheme",-91,"18:d6:c7:64:95:c6",4)
+CWLAP:(4,"TONY",-90,"40:16:7e:ba:f0:b4",1)
+CWLAP:(3,"Linksys05020",-86,"24:f5:a2:0a:a9:b3",5)
+CWLAP:(0,"Linksys10180-guest",-90,"2a:f5:a2:0e:1e:cb",5)
+CWLAP:(4,"TP-Link CEA50",-90,"14:cc:20:ce:a5:e0",5)
+CWLAP:(3,"Ronald2.4",-91,"60:38:e0:c2:fe:a1",6)
+CWLAP:(3,"Calbee88",-89,"58:ef:68:58:77:b1",6)
+CWLAP:(4,"hidewesker",-78,"c8:3a:35:3a:22:a1",8)
+CWLAP:(3,"Chu 2.4ghz",-86,"10:c3:7b:d0:d7:90",8)
+CWLAP:(3,"Lun & Irene",-89,"24:05:88:06:a6:9f",11)
+CWLAP:(4,"kinman0702",-79,"f4:28:53:6c:60:a6",11)
+CWLAP:(3,"NETGEAR",-91,"a0:63:91:db:fd:24",11)
+CWLAP:(3,"Asus-Giggs",-91,"14:dd:a9:ca:21:60",11)
+CWLAP:(3,"KF CHAN",-81,"c0:56:27:4b:e2:e7",11)
+CWLAP:(3,"Teng",-90,"38:d5:47:40:45:40",11)
+CWLAP:(4,"micmiclau2",-93,"50:c7:bf:06:a6:c0",12)
+CWLAP:(4,"CHC_Home",-90,"58:ef:68:aa:16:db",12)
+CWLAP:(4,"ho",-91,"f4:28:53:79:48:b2",13)
OK

AT+CWJAP="tlfong01","abcxyz123***"

OK

AT+CIPSTATUS

STATUS:5
OK

AT+CIPMUX?

+CIPMUX:0
OK

AT+CIPMUX=1

OK

AT+CIPSERVER=1,8087

OK

AT+CIPSTO?

+CIPSTO:180
OK

AT+CIPSTO=200

OK

.END
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Thu Oct 04, 2018 5:10 am

tlfong01 wrote:
Wed Oct 03, 2018 6:38 am
tlfong01 wrote:
Wed Oct 03, 2018 4:02 am
Newbie Learning notes on ESP8266 AT Commands
ESP8266 AT Command Testing Notes
So I tested some of the basic AT commands and found things more or less OK.
ESPlorer v0.20-rc5 by 4refrOnt
ai-thinker-0.9.5.2-115200bin (2018/10/1 508kB)

ESPlorer AT mode for testing AT commands

I found ESPlorer has a very newbie friendly AT command mode for testing AT commands. So I don't need to type "at+***" etc.
Attachments
at_command_test_2018oct0401.jpg
at_command_test_2018oct0401.jpg (180.78 KiB) Viewed 2874 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Thu Oct 04, 2018 7:18 am

tlfong01 wrote:
Thu Oct 04, 2018 5:10 am
ESPlorer AT mode for testing AT commands
I found ESPlorer has a very newbie friendly AT command mode for testing AT commands.

RealTerm for testing ESP8266 AT commands, and also I2C?

I googled and found most newbies are using RealTerm to test ESP8266 AT commands. I guess one important reason is that RealTerm has many more powerful features, such as capture/log file with time stamp, send batch file, pin status check etc.

One thing realTerm surprises me is that it has I2C checking. I have no idea how it does it, perhaps it can send or receive I2C data, and also log it. That should be as useful as using a scope. I need to check out later.
Attachments
realterm_setting_2018oct0401.jpg
realterm_setting_2018oct0401.jpg (161.74 KiB) Viewed 2865 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Thu Oct 04, 2018 1:16 pm

petermeigs wrote:
Sun Sep 23, 2018 3:05 pm
For using esp8266 I like using esplorer, the java program. I can use it from linux, windows, or Mac. It has a nice set of little tools to test things.

Buggy ESPlorer

ESPlorer looks powerful, but I was uncomfortable using it, for the following reasons.

1. It is buggy. The file upload (to ESP8266) / save (to PC hard disk) commands seems not working properly. I lost script files a couple of times because the save commands seems not working. See appendix below for Big Dan's comments about this ESPlorer.

The lesson I learnt is always save the editing script to hard disk first, before executing or uploading the script.

2. It is not maintained. It appears that the original author of ESPlorer has abondoned his project, and no one seems able or willing to maintain it.

3. There is no proper user manual.


Update 2018oct04hkt2151

I also tried LUA Loader V0.91(2016) but did not find it impressive. I think I will still use ESPlorer for now.


Appendix - Big Dan The Blogging Man's ESP8266 WIFI Module Posts

ESP8266 NodeMCU/LUA: Saving, Executing, and Compiling Script Files Posted on April 21, 2015
https://bigdanzblog.wordpress.com/2015/ ... ipt-files/

... there are some slightly clunkiness when accessing the flash file system.

I would expect to modify the source of the script in ESPlorer, periodically save to disk (on my PC), periodically upload the source to a file on the ESP8266, and then periodically execute the file from flash on the ESP8266.

It isn’t totally obvious how to do these operations by themselves. I keep having source uploaded to the ESP8266 and executed when that’s not what I mean to happen.

You would think ‘Save to ESP’ would just send the file to the ESP8266 and ‘Save&Run’ would save and run. No. ‘Save to ESP’ saves and runs.

Instead,

make sure the file has been saved to local disk,

and click on ‘Upload’. That will upload the disk file to the ESP8266 (it will not upload the editor contents so make sure you save to disk first).
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 1312
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Fri Oct 05, 2018 6:24 am

tlfong01 wrote:
Thu Oct 04, 2018 1:16 pm
Buggy ESPlorer
ESPlorer looks powerful, but I was uncomfortable using it, for the following reasons.
It is buggy. The file upload (to ESP8266) / save (to PC hard disk) commands seems not working properly. I lost script files a couple of times because the save commands seems not working.
The lesson I learnt is always save the editing script to hard disk first, before executing or uploading the script.
BigDan: It isn’t totally obvious how to do these operations by themselves. I keep having source uploaded to the ESP8266 and executed when that’s not what I mean to happen.
make sure the file has been saved to local disk, ...

Using ESPlorer v0.2.0-rc5 and LUAedit v3.0.10 (2010) Together

I googled and found luaedit v3.0.10 which is another tool not maintained for a couple of years. But two old tools working together is OK, at least for newbies.
Attachments
luaedit_2018oct0502.jpg
luaedit_2018oct0502.jpg (164.5 KiB) Viewed 2827 times
I am an electronics and smart home hobbyist.

petermeigs
Posts: 96
Joined: Thu Mar 23, 2017 1:34 pm
Location: Los Altos, California

Re: GPIO.input voltage levels vs edge detection

Fri Oct 05, 2018 1:15 pm

With ESPlorer, try turning off "echo command" when uploading file. Flow control is not great.

Also, when you send a file to the 8266, try to upload it as a file, then you can dofile as a command later to run it. You'll notice that upload just creates a script to do a line by line write to a file.

I would up putting a lot of things in snippets to run them later.

Earlier, I have posted a script to let you telnet to the esp and that will help a lot but does not solve the upload issue.

If you find a proper ftp to be able to upload (and download) please post it here. That would be super useful.

Return to “Python”