- ajouté les fichiers Lua à Hugo :-)

This commit is contained in:
Christian Zufferey
2018-07-22 12:47:37 +02:00
parent 4608e4092e
commit 26d3f422cd
31 changed files with 1346 additions and 0 deletions

0
Hugo/Icon Normal file
View File

37
Hugo/README.md Executable file
View File

@@ -0,0 +1,37 @@
# NodeMCU_Lua
Petit dossier avec des programmes pour apprendre à coder sur un NodeMCU en lua.
### Faire clignoter une ou plusieurs leds
1.led_blink_1.lua<br>
2.led_blink_2.lua
### Modifier l'intensité d'une ou plusieurs leds
1.led_intensite.lua<br>
2.led_intensite_variable.lua
### Allumer une led, en pressant un bouton
1.led_press_button.lua
### Connecter le NodeMCU à un réseau WIFI et créer un serveur web pour contrôler une led
1.web_liste_deroulante_led_change.lua<br>
2.web_press_button_led.lua
### Robot
1.robot_avance_arrete.lua<br>
2.robot_mesure_turn_right.lua<br>
3.robot_random_mesure.lua
### Utilitaires
1.u_dir.lua<br>
2.u_get_ip.lua<br>
3.u_start_job.lua<br>
4.u_telnet_srv.lua<br>
5.u_web_stop.lua
### Tests
1.test_init_1.lua<br>
2.test_blink_1.lua<br>
3.test_blink_2.lua<br>
4.test_get_ip_1.lua<br>
5.test_press_button_1.lua<br>
6.test_web_1.lua

13
Hugo/init.lua Executable file
View File

@@ -0,0 +1,13 @@
--Programme qui démarre le robot en appuyant sur le bouton flash et le redémarre si le bouton flash est appuyer pendant 3 secondes
print("\ninit.lua hv180717.1101\n")
zswitch=3 --switch flash
gpio.mode(zswitch, gpio.INT, gpio.PULLUP)
function bouton()
print("Start start_job.lua...")
dofile("start_job.lua")
end
gpio.trig(zswitch, "both", bouton)

23
Hugo/led_blink_1.lua Executable file
View File

@@ -0,0 +1,23 @@
-- programme pour faire clignoter un LED
--hv20180711.1007
zpin=1
valeur=gpio.HIGH
duration = 300 --> en ms
function clignoter ()
if valeur==gpio.LOW then
valeur=gpio.HIGH
else
valeur=gpio.LOW
end
gpio.write(zpin, valeur)
end
gpio.mode(zpin, gpio.OUTPUT)
gpio.write(zpin, valeur)
tmr.alarm(0,duration, tmr.ALARM_AUTO, clignoter)

39
Hugo/led_blink_2.lua Executable file
View File

@@ -0,0 +1,39 @@
-- programme pour faire clignoter deux LED
--hv20180711.1008
zpin1=1
zpin2=2
valeur1=gpio.HIGH
valeur2=gpio.HIGH
duration1 = 300 --> en ms
duration2 = 1000 --> en ms
function LED1 ()
if valeur1==gpio.LOW then
valeur1=gpio.HIGH
else
valeur1=gpio.LOW
end
gpio.write(zpin1, valeur1)
end
function LED2 ()
if valeur2==gpio.LOW then
valeur2=gpio.HIGH
else
valeur2=gpio.LOW
end
gpio.write(zpin2, valeur2)
end
gpio.mode(zpin1, gpio.OUTPUT)
gpio.write(zpin1, valeur1)
gpio.mode(zpin2, gpio.OUTPUT)
gpio.write(zpin2, valeur2)
tmr.alarm(1, duration1, tmr.ALARM_AUTO, LED1)
tmr.alarm(2, duration2, tmr.ALARM_AUTO, LED2)

11
Hugo/led_intensite.lua Executable file
View File

@@ -0,0 +1,11 @@
--Programme pour choisir l'intensité des leds
--hv20180711.1702
zpin1=1
zpin2=2
pwm.setup(zpin1, 100, 1022)
pwm.start(zpin1)
pwm.setup(zpin2, 100, 100)
pwm.start(zpin2)

27
Hugo/led_intensite_variable.lua Executable file
View File

@@ -0,0 +1,27 @@
--Programme pour augmenter l'intensité d'une led au même temps que l'autre led descend d'intensité
--hv20180712.1503
zledred=1
zledgreen=2
zlum=1023
zinc=-1023/40
zduration = 80
function zincrementation()
zlum=zlum+zinc
if (zlum<0) or (zlum>1023) then
zinc=zinc*-1
zlum=zlum+2*zinc
end
pwm.setduty(zledred, zlum)
pwm.setduty(zledgreen, 1023-zlum)
print(zlum..","..zinc)
end
pwm.start(zledred)
pwm.setup(zledred,100,zlum)
pwm.start(zledgreen)
pwm.setup(zledgreen,100,1023-zlum)
zalarm1 = tmr.create()
tmr.alarm(zalarm1, zduration, tmr.ALARM_AUTO, zincrementation)

17
Hugo/led_press_button.lua Executable file
View File

@@ -0,0 +1,17 @@
-- Programme qui allume la led bleue quand on appuie le bouton flash
-- hv180711.1125
zledbleue=0 --led bleue
zswitch=3--switch flash
gpio.mode(zswitch, gpio.INT, gpio.PULLUP)
function bouton()
if gpio.read(zswitch)==0 then
gpio.write(zledbleue, gpio.LOW)
else
gpio.write(zledbleue, gpio.HIGH)
end
end
gpio.trig(zswitch, "both", bouton)

358
Hugo/luatool.py Executable file
View File

@@ -0,0 +1,358 @@
#!/usr/bin/env python2
#
# ESP8266 luatool
# Author e-mail: 4ref0nt@gmail.com
# Site: http://esp8266.ru
# Contributions from: https://github.com/sej7278
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
# Street, Fifth Floor, Boston, MA 02110-1301 USA.
import sys
import serial
from time import sleep
import socket
import argparse
from os.path import basename
tqdm_installed = True
try:
from tqdm import tqdm
except ImportError, e:
if e.message == 'No module named tqdm':
tqdm_installed = False
else:
raise
version = "0.6.4"
class TransportError(Exception):
"""Custom exception to represent errors with a transport
"""
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
class AbstractTransport:
def __init__(self):
raise NotImplementedError('abstract transports cannot be instantiated.')
def close(self):
raise NotImplementedError('Function not implemented')
def read(self, length):
raise NotImplementedError('Function not implemented')
def writeln(self, data, check=1):
raise NotImplementedError('Function not implemented')
def writer(self, data):
self.writeln("file.writeline([==[" + data + "]==])\r")
def performcheck(self, expected):
line = ''
char = ''
i = -1
while char != chr(62): # '>'
char = self.read(1)
if char == '':
raise Exception('No proper answer from MCU')
if char == chr(13) or char == chr(10): # LF or CR
if line != '':
line = line.strip()
if line+'\r' == expected and not args.bar:
sys.stdout.write(" -> ok")
elif line+'\r' != expected:
if line[:4] == "lua:":
sys.stdout.write("\r\n\r\nLua ERROR: %s" % line)
raise Exception('ERROR from Lua interpreter\r\n\r\n')
else:
expected = expected.split("\r")[0]
sys.stdout.write("\r\n\r\nERROR")
sys.stdout.write("\r\n send string : '%s'" % expected)
sys.stdout.write("\r\n expected echo : '%s'" % expected)
sys.stdout.write("\r\n but got answer : '%s'" % line)
sys.stdout.write("\r\n\r\n")
raise Exception('Error sending data to MCU\r\n\r\n')
line = ''
else:
line += char
if char == chr(62) and expected[i] == char:
char = ''
i += 1
class SerialTransport(AbstractTransport):
def __init__(self, port, baud, delay):
self.port = port
self.baud = baud
self.serial = None
self.delay = delay
try:
self.serial = serial.Serial(port, baud)
except serial.SerialException as e:
raise TransportError(e.strerror)
self.serial.timeout = 3
self.serial.interCharTimeout = 3
def writeln(self, data, check=1):
if self.serial.inWaiting() > 0:
self.serial.flushInput()
if len(data) > 0 and not args.bar:
sys.stdout.write("\r\n->")
sys.stdout.write(data.split("\r")[0])
self.serial.write(data)
sleep(self.delay)
if check > 0:
self.performcheck(data)
elif not args.bar:
sys.stdout.write(" -> send without check")
def read(self, length):
return self.serial.read(length)
def close(self):
self.serial.flush()
self.serial.close()
class TcpSocketTransport(AbstractTransport):
def __init__(self, host, port):
self.host = host
self.port = port
self.socket = None
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as e:
raise TransportError(e.strerror)
try:
self.socket.connect((host, port))
except socket.error as e:
raise TransportError(e.strerror)
# read intro from telnet server (see telnet_srv.lua)
self.socket.recv(50)
def writeln(self, data, check=1):
if len(data) > 0 and not args.bar:
sys.stdout.write("\r\n->")
sys.stdout.write(data.split("\r")[0])
self.socket.sendall(data)
if check > 0:
self.performcheck(data)
elif not args.bar:
sys.stdout.write(" -> send without check")
def read(self, length):
return self.socket.recv(length)
def close(self):
self.socket.close()
def decidetransport(cliargs):
if cliargs.ip:
data = cliargs.ip.split(':')
host = data[0]
if len(data) == 2:
port = int(data[1])
else:
port = 23
return TcpSocketTransport(host, port)
else:
return SerialTransport(cliargs.port, cliargs.baud, cliargs.delay)
if __name__ == '__main__':
# parse arguments or use defaults
parser = argparse.ArgumentParser(description='ESP8266 Lua script uploader.')
parser.add_argument('-p', '--port', default='/dev/ttyUSB0', help='Device name, default /dev/ttyUSB0')
parser.add_argument('-b', '--baud', default=9600, help='Baudrate, default 9600')
parser.add_argument('-f', '--src', default='main.lua', help='Source file on computer, default main.lua')
parser.add_argument('-t', '--dest', default=None, help='Destination file on MCU, default to source file name')
parser.add_argument('-c', '--compile', action='store_true', help='Compile lua to lc after upload')
parser.add_argument('-r', '--restart', action='store_true', help='Restart MCU after upload')
parser.add_argument('-d', '--dofile', action='store_true', help='Run the Lua script after upload')
parser.add_argument('-v', '--verbose', action='store_true', help="Show progress messages.")
parser.add_argument('-a', '--append', action='store_true', help='Append source file to destination file.')
parser.add_argument('-l', '--list', action='store_true', help='List files on device')
parser.add_argument('-w', '--wipe', action='store_true', help='Delete all lua/lc files on device.')
parser.add_argument('-i', '--id', action='store_true', help='Query the modules chip id.')
parser.add_argument('-e', '--echo', action='store_true', help='Echo output of MCU until script is terminated.')
parser.add_argument('--bar', action='store_true', help='Show a progress bar for uploads instead of printing each line')
parser.add_argument('--delay', default=0.3, help='Delay in seconds between each write.', type=float)
parser.add_argument('--delete', default=None, help='Delete a lua/lc file from device.')
parser.add_argument('--ip', default=None, help='Connect to a telnet server on the device (--ip IP[:port])')
args = parser.parse_args()
transport = decidetransport(args)
if args.bar and not tqdm_installed:
sys.stdout.write("You must install the tqdm library to use the bar feature\n")
sys.stdout.write("To install, at the prompt type: \"pip install tqdm\"\n")
sys.exit(0)
if args.list:
transport.writeln("local l = file.list();for k,v in pairs(l) do print('name:'..k..', size:'..v)end\r", 0)
while True:
char = transport.read(1)
if char == '' or char == chr(62):
break
sys.stdout.write(char)
sys.exit(0)
if args.id:
transport.writeln("=node.chipid()\r", 0)
id=""
while True:
char = transport.read(1)
if char == '' or char == chr(62):
break
if char.isdigit():
id += char
print("\n"+id)
sys.exit(0)
if args.wipe:
transport.writeln("local l = file.list();for k,v in pairs(l) do print(k)end\r", 0)
file_list = []
fn = ""
while True:
char = transport.read(1)
if char == '' or char == chr(62):
break
if char not in ['\r', '\n']:
fn += char
else:
if fn:
file_list.append(fn.strip())
fn = ''
for fn in file_list[1:]: # first line is the list command sent to device
if args.verbose:
sys.stderr.write("Delete file {} from device.\r\n".format(fn))
transport.writeln("file.remove(\"" + fn + "\")\r")
sys.exit(0)
if args.delete:
transport.writeln("file.remove(\"" + args.delete + "\")\r")
sys.exit(0)
if args.dest is None:
args.dest = basename(args.src)
# open source file for reading
try:
try:
f = open(args.src, "rt")
except:
import os
base_dir = os.path.dirname(os.path.realpath(__file__))
f = open(os.path.join(base_dir, args.src), "rt")
os.chdir(base_dir)
except:
sys.stderr.write("Could not open input file \"%s\"\n" % args.src)
sys.exit(1)
# Verify the selected file will not exceed the size of the serial buffer.
# The size of the buffer is 256. This script does not accept files with
# lines longer than 230 characters to have some room for command overhead.
num_lines = 0
for ln in f:
if len(ln) > 230:
sys.stderr.write("File \"%s\" contains a line with more than 240 "
"characters. This exceeds the size of the serial buffer.\n"
% args.src)
f.close()
sys.exit(1)
num_lines += 1
# Go back to the beginning of the file after verifying it has the correct
# line length
f.seek(0)
# set serial timeout
if args.verbose:
sys.stderr.write("Upload starting\r\n")
# remove existing file on device
if args.append==False:
if args.verbose:
sys.stderr.write("Stage 1. Deleting old file from flash memory")
transport.writeln("file.open(\"" + args.dest + "\", \"w\")\r")
transport.writeln("file.close()\r")
transport.writeln("file.remove(\"" + args.dest + "\")\r")
else:
if args.verbose:
sys.stderr.write("[SKIPPED] Stage 1. Deleting old file from flash memory [SKIPPED]")
# read source file line by line and write to device
if args.verbose:
sys.stderr.write("\r\nStage 2. Creating file in flash memory and write first line")
if args.append:
transport.writeln("file.open(\"" + args.dest + "\", \"a+\")\r")
else:
transport.writeln("file.open(\"" + args.dest + "\", \"w+\")\r")
line = f.readline()
if args.verbose:
sys.stderr.write("\r\nStage 3. Start writing data to flash memory...")
if args.bar:
for i in tqdm(range(0, num_lines)):
transport.writer(line.strip())
line = f.readline()
else:
while line != '':
transport.writer(line.strip())
line = f.readline()
# close both files
f.close()
if args.verbose:
sys.stderr.write("\r\nStage 4. Flush data and closing file")
transport.writeln("file.flush()\r")
transport.writeln("file.close()\r")
# compile?
if args.compile:
if args.verbose:
sys.stderr.write("\r\nStage 5. Compiling")
transport.writeln("node.compile(\"" + args.dest + "\")\r")
transport.writeln("file.remove(\"" + args.dest + "\")\r")
# restart or dofile
if args.restart:
transport.writeln("node.restart()\r")
if args.dofile: # never exec if restart=1
transport.writeln("dofile(\"" + args.dest + "\")\r", 0)
if args.echo:
if args.verbose:
sys.stderr.write("\r\nEchoing MCU output, press Ctrl-C to exit")
while True:
sys.stdout.write(transport.read(1))
# close serial port
transport.close()
# flush screen
sys.stdout.flush()
sys.stderr.flush()
if not args.bar:
sys.stderr.write("\r\n--->>> All done <<<---\r\n")

31
Hugo/meter_mesure.lua Executable file
View File

@@ -0,0 +1,31 @@
--mesure la distance avec un module à ultra son hc-sr04
--Attention le module doit être alimenter en 5V et il faut mettre une resistance de 100 ohm sur la pin echo
--hv180713.1138
ztrig=5
zecho=6
ztstart=0
ztstop=0
gpio.mode(ztrig, gpio.OUTPUT)
gpio.write(ztrig, gpio.LOW)
gpio.mode(zecho, gpio.INT, gpio.PULLUP)
function zmesure_pulse()
gpio.write(ztrig, gpio.HIGH)
tmr.delay(10)
gpio.write(ztrig, gpio.LOW)
end
function zmesure()
if gpio.read(zecho)==1 then
ztstart=tmr.now()
else
ztstop=tmr.now()
zlength=360*(ztstop-ztstart)/2/10000
print("distance [cm]: "..math.floor(zlength))
end
end
gpio.trig(zecho, "both", zmesure)
tmr.alarm(1, 1000, tmr.ALARM_AUTO, zmesure_pulse)

71
Hugo/oled_first.lua Executable file
View File

@@ -0,0 +1,71 @@
--Affiche simplement un Hello Wolrd sur le display OLED
print("\nDémarrage hv20180720.1616 \n")
-- Utilisation :
-- pin_sda = 5
-- pin_scl = 6
-- disp_sla = 0x3c
-- _dofile("i2c_display")
-- disp_add_data(texte)
-- avec texte un json du type
-- texte = '{ "id": "id_du_texte",
-- "column": [0-20], (si omis : 0)
-- "row": [0-5], (si omis : 0)
-- "text": "abcdef", (si omis : "")
-- "angle": [0,90,180,270] }' (si omis 0°)
--
-- disp_add_data('{"id":"id_du_texte"}') efface le texte
-------------------------------------------------
-- Modules nécessaires dans le firmware :
-- i2c, u8g(avec font ssd1306_128x64_i2c), cjson
-------------------------------------------------
pin_sda = 12
pin_scl = 11
disp_sla = 0x3c
function init_OLED(sda, scl) --Set up the u8glib lib
i2c.setup(0, sda, scl, i2c.SLOW)
disp = u8g.ssd1306_128x64_i2c(disp_sla)
-- https://github.com/olikraus/u8glib/wiki/fontsize
disp:setFont(u8g.font_6x10)
disp:setFontRefHeightExtendedText()
disp:setDefaultForegroundColor()
disp:setFontPosTop()
end
function draw()
disp:drawStr(0,0,"Hello Hugo !")
disp:drawStr(0,11,"et zuzu !")
end
init_OLED(pin_sda, pin_scl) --Run setting up
disp:firstPage()
repeat
draw()
until disp:nextPage() == false
--print( string.gsub("hello+zuzu+%26+une+belle+%E9cole%5Cun+b%E2teau","+"," ")
--[[ source OLED:
https://www.google.ch/search?q=nodemcu+lua+oled+display&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjG8ba8ra3cAhVDCpoKHedlDS4Q_AUICigB&biw=1536&bih=828
https://www.hackster.io/kayakpete/esp8266-oled-display-52ae50
http://blog.rl.cx/2017/01/08/bien-d%C3%A9buter-avec-nodemcu/
https://github.com/FredThx/nodemcu_iot/blob/master/i2c_display.lua
https://www.instructables.com/id/NODEMCU-LUA-ESP8266-With-I2C-LCD-128-X-64-OLED-Dis/
]]

62
Hugo/robot_avance_arrete.lua Executable file
View File

@@ -0,0 +1,62 @@
--Programme pour faire tourner aleatoirement le robot à droite ou à gauche tant qu'il soit à moins de 20cm de l'obstacle
--hv20180717.1613
--parametres pour le module ultra son
ztrig=5
zecho=6
ztstart=0
ztstop=0
gpio.mode(ztrig, gpio.OUTPUT)
gpio.write(ztrig, gpio.LOW)
gpio.mode(zecho, gpio.INT, gpio.PULLUP)
--parametres pour les moteurs
pin_a_speed = 1
pin_a_dir = 3
pin_b_speed = 2
pin_b_dir = 4
FWD = gpio.LOW
REV = gpio.HIGH
duty = 1023
--initialise moteur A
gpio.mode(pin_a_speed,gpio.OUTPUT)
gpio.write(pin_a_speed,gpio.LOW)
pwm.setup(pin_a_speed,1000,duty) --PWM 1KHz, Duty 1023
pwm.start(pin_a_speed)
pwm.setduty(pin_a_speed,0)
gpio.mode(pin_a_dir,gpio.OUTPUT)
--initialise moteur B
gpio.mode(pin_b_speed,gpio.OUTPUT)
gpio.write(pin_b_speed,gpio.LOW)
pwm.setup(pin_b_speed,1000,duty) --PWM 1KHz, Duty 1023
pwm.start(pin_b_speed)
pwm.setduty(pin_b_speed,0)
gpio.mode(pin_b_dir,gpio.OUTPUT)
-- speed is 0 - 100
function motor(pin_speed, pin_dir, dir, speed)
gpio.write(pin_dir,dir)
pwm.setduty(pin_speed, (speed * duty) / 100)
end
function motor_a(dir, speed)
motor(pin_a_speed, pin_a_dir, dir, speed)
end
function motor_b(dir, speed)
motor(pin_b_speed, pin_b_dir, dir, speed)
end
function avance_robot()
motor_a(FWD, 60)
motor_b(FWD, 60)
end
function stop_robot()
motor_a(FWD, 0)
motor_b(FWD, 0)
end

106
Hugo/robot_mesure_turn_right.lua Executable file
View File

@@ -0,0 +1,106 @@
--Programme pour faire tourner aleatoirement le robot à droite ou à gauche tant qu'il soit à moins de 20cm de l'obstacle
--hv20180717.1613
--parametres pour le module ultra son
ztrig=5
zecho=6
ztstart=0
ztstop=0
gpio.mode(ztrig, gpio.OUTPUT)
gpio.write(ztrig, gpio.LOW)
gpio.mode(zecho, gpio.INT, gpio.PULLUP)
--parametres pour les moteurs
pin_a_speed = 1
pin_a_dir = 3
pin_b_speed = 2
pin_b_dir = 4
FWD = gpio.LOW
REV = gpio.HIGH
duty = 1023
--initialise moteur A
gpio.mode(pin_a_speed,gpio.OUTPUT)
gpio.write(pin_a_speed,gpio.LOW)
pwm.setup(pin_a_speed,1000,duty) --PWM 1KHz, Duty 1023
pwm.start(pin_a_speed)
pwm.setduty(pin_a_speed,0)
gpio.mode(pin_a_dir,gpio.OUTPUT)
--initialise moteur B
gpio.mode(pin_b_speed,gpio.OUTPUT)
gpio.write(pin_b_speed,gpio.LOW)
pwm.setup(pin_b_speed,1000,duty) --PWM 1KHz, Duty 1023
pwm.start(pin_b_speed)
pwm.setduty(pin_b_speed,0)
gpio.mode(pin_b_dir,gpio.OUTPUT)
-- timer personnelle
hvtimer1=tmr.create()
hvtimer2=tmr.create()
-- speed is 0 - 100
function motor(pin_speed, pin_dir, dir, speed)
gpio.write(pin_dir,dir)
pwm.setduty(pin_speed, (speed * duty) / 100)
end
function motor_a(dir, speed)
motor(pin_a_speed, pin_a_dir, dir, speed)
end
function motor_b(dir, speed)
motor(pin_b_speed, pin_b_dir, dir, speed)
end
--Robot avance, s'arrete, tourne à droite, tourne à gauche
function avance_robot()
t=math.random(1,2)
--print(t)
motor_a(FWD, 60)
motor_b(FWD, 60)
end
function stop_robot()
motor_a(FWD, 0)
motor_b(FWD, 0)
end
function turn_right_robot()
motor_a(FWD, 60)
motor_b(REV, 60)
end
function turn_left_robot()
motor_a(REV, 60)
motor_b(FWD, 60)
end
--start pulse10 us
function zmesure_pulse()
gpio.write(ztrig, gpio.HIGH)
tmr.delay(10)
gpio.write(ztrig, gpio.LOW)
end
-- mesure la distance et il s'arrete si < 20cm
function zmesure()
if gpio.read(zecho)==1 then
ztstart=tmr.now()
else
ztstop=tmr.now()
zlength=360*(ztstop-ztstart)/2/10000
if zlength>200 then zlength=0 end
if zlength<20 then
turn_right_robot()
tmr.alarm(hvtimer1, 1000, tmr.ALARM_SINGLE, avance_robot)
end
print("distance [cm]: "..math.floor(zlength))
end
end
gpio.trig(zecho, "both", zmesure)
tmr.alarm(hvtimer2, 1000, tmr.ALARM_AUTO, zmesure_pulse)
avance_robot()

108
Hugo/robot_random_mesure.lua Executable file
View File

@@ -0,0 +1,108 @@
--Programme pour faire tourner aleatoirement le robot à droite ou à gauche tant qu'il soit à moins de 20cm de l'obstacle
--hv20180717.1613
--parametres pour le module ultra son
ztrig=5
zecho=6
ztstart=0
ztstop=0
gpio.mode(ztrig, gpio.OUTPUT)
gpio.write(ztrig, gpio.LOW)
gpio.mode(zecho, gpio.INT, gpio.PULLUP)
--parametres pour les moteurs
pin_a_speed = 1
pin_a_dir = 3
pin_b_speed = 2
pin_b_dir = 4
FWD = gpio.LOW
REV = gpio.HIGH
duty = 1023
--initialise moteur A
gpio.mode(pin_a_speed,gpio.OUTPUT)
gpio.write(pin_a_speed,gpio.LOW)
pwm.setup(pin_a_speed,1000,duty) --PWM 1KHz, Duty 1023
pwm.start(pin_a_speed)
pwm.setduty(pin_a_speed,0)
gpio.mode(pin_a_dir,gpio.OUTPUT)
--initialise moteur B
gpio.mode(pin_b_speed,gpio.OUTPUT)
gpio.write(pin_b_speed,gpio.LOW)
pwm.setup(pin_b_speed,1000,duty) --PWM 1KHz, Duty 1023
pwm.start(pin_b_speed)
pwm.setduty(pin_b_speed,0)
gpio.mode(pin_b_dir,gpio.OUTPUT)
-- timer personnelle
hvtimer1=tmr.create()
hvtimer2=tmr.create()
-- speed is 0 - 100
function motor(pin_speed, pin_dir, dir, speed)
gpio.write(pin_dir,dir)
pwm.setduty(pin_speed, (speed * duty) / 100)
end
function motor_a(dir, speed)
motor(pin_a_speed, pin_a_dir, dir, speed)
end
function motor_b(dir, speed)
motor(pin_b_speed, pin_b_dir, dir, speed)
end
--Robot avance, s'arrete, tourne à droite, tourne à gauche
function avance_robot()
t=math.random(1,2)
--print(t)
motor_a(FWD, 60)
motor_b(FWD, 60)
end
function stop_robot()
motor_a(FWD, 0)
motor_b(FWD, 0)
end
function turn_right_robot()
motor_a(FWD, 60)
motor_b(REV, 60)
end
function turn_left_robot()
motor_a(REV, 60)
motor_b(FWD, 60)
end
--start pulse10 us
function zmesure_pulse()
gpio.write(ztrig, gpio.HIGH)
tmr.delay(10)
gpio.write(ztrig, gpio.LOW)
end
-- mesure la distance et il s'arrete si < 20cm
function zmesure()
if gpio.read(zecho)==1 then
ztstart=tmr.now()
else
ztstop=tmr.now()
zlength=360*(ztstop-ztstart)/2/10000
if zlength>200 then zlength=0 end
--print("distance [cm]: "..math.floor(zlength))
if zlength<20 then
if t==1 then
turn_left_robot()
else
turn_right_robot()
end
tmr.alarm(hvtimer1, 1000, tmr.ALARM_SINGLE, avance_robot)
end
end
end
gpio.trig(zecho, "both", zmesure)
tmr.alarm(hvtimer2, 1000, tmr.ALARM_AUTO, zmesure_pulse)
avance_robot()

6
Hugo/start_EPSlorer.sh Executable file
View File

@@ -0,0 +1,6 @@
# !/bin/bash
# Script pour lancer ESPlorer
# hv 1807010.1538
#sudo chmod 666 /dev/ttyUSB0
java -jar "ESPlorer/ESPlorer.jar"

6
Hugo/start_screen.sh Executable file
View File

@@ -0,0 +1,6 @@
# !/bin/bash
# Script pour lancer l'émulateur de terminale
# hv 1807010.1555
sudo chmod 666 /dev/ttyUSB0
screen /dev/ttyUSB0 115200

13
Hugo/test_blink_1.lua Executable file
View File

@@ -0,0 +1,13 @@
-- Clignoter la led bleue. Vieille méthode, pas le faire
-- zf180709.2200
zpin=0 --led blue builting
gpio.mode(zpin, gpio.OUTPUT)
for i=1,20 do
print("Hello World "..i)
gpio.write(zpin, gpio.LOW)
tmr.delay(100000)
gpio.write(zpin, gpio.HIGH)
tmr.delay(100000)
end

19
Hugo/test_blink_2.lua Executable file
View File

@@ -0,0 +1,19 @@
-- Clignoter les leds. Vieille méthode. Pas le faire
-- zf180709.2200
zpin1=1--led rouge
zpin2=2--led verte
gpio.mode(zpin1, gpio.OUTPUT)
gpio.mode(zpin2,gpio.OUTPUT)
for i=1,10 do
print("Hello World "..i)
gpio.write(zpin1, gpio.LOW)
gpio.write(zpin2, gpio.HIGH)
tmr.delay(300000)
gpio.write(zpin1, gpio.HIGH)
gpio.write(zpin2, gpio.LOW)
tmr.delay(300000)
end
gpio.write(zpin2, gpio.HIGH)

18
Hugo/test_get_ip_1.lua Executable file
View File

@@ -0,0 +1,18 @@
-- Enclenche le mode configuration WIFI
print("\nzf180718.1107\n")
function get_ip()
if wifi.sta.getip() == nil then
print("Connecting to AP...")
else
tmr.stop(0)
print("Connected! IP: ",wifi.sta.getip())
tmr.alarm(0,3000,tmr.ALARM_SINGLE, function() node.restart() end)
end
end
wifi.sta.disconnect()
wifi.sta.clearconfig()
print("\nwifi config http://192.168.4.1\n")
tmr.alarm(0, 1000, tmr.ALARM_AUTO , get_ip)
enduser_setup.start()

26
Hugo/test_init_1.lua Executable file
View File

@@ -0,0 +1,26 @@
--Programme qui démarre le robot en appuyant sur le bouton flash et le redémarre si le bouton flash est appuyer pendant 3 secondes
--hv20180716.1349
zBTNflash = 3 -- GPIO0 button
function btn_clic()
t1=tmr.now()
tmr.alarm(0,100,tmr.ALARM_AUTO, btn_test)
end
function btn_test()
t2=tmr.now()
t3=(t2-t1)/1000000
print("t3: "..t3)
if gpio.read(zBTNflash)==1 then
tmr.stop(0)
gpio.trig(zBTNflash)
dofile("robot_1.lua")
end
if t3>2 then
tmr.stop(0)
gpio.trig(zBTNflash)
node.restart()
end
end
gpio.mode(zBTNflash,gpio.INT)
gpio.trig(zBTNflash, "down", btn_clic)

18
Hugo/test_press_button_1.lua Executable file
View File

@@ -0,0 +1,18 @@
-- lit le switch flash et allume la led bleue. Veille méthode, pas le faire
-- zf180710.1606
zledbleue=0 --led blue builting
zswitch=3 --switch flash
gpio.mode(zledbleue, gpio.OUTPUT)
gpio.mode(zswitch, gpio.INPUT)
for i=1,10 do
print("Hello World "..i)
if gpio.read(zswitch) == 1 then
gpio.write(zledbleue, gpio.HIGH)
else
gpio.write(zledbleue, gpio.LOW)
end
tmr.delay(1000000)
end

24
Hugo/test_web_1.lua Executable file
View File

@@ -0,0 +1,24 @@
--Connexion en mode client WIFI
--hv20180711.1501
print("Démarrage")
wifi.sta.disconnect()
wifi.setmode(wifi.STATION)
print("set mode=STATION (mode="..wifi.getmode()..")")
wifi.sta.config{ssid="Hugo", pwd="tototutu"}
tmr.alarm(0, 1000, tmr.ALARM_AUTO , function()
if wifi.sta.getip() == nil then
print("Connecting to AP...")
else
print("Connected! IP: ",wifi.sta.getip())
tmr.stop(0)
end
end)

15
Hugo/u_dir.lua Executable file
View File

@@ -0,0 +1,15 @@
-- fonction dir() pour afficher les fichiers dans la flash
-- zf180717.1542
function dir()
print("\n-------------------------------")
l=file.list() i=0
for k,v in pairs(l) do
i=i+v
print(k..string.rep(" ",19-string.len(k)).." : "..v.." bytes")
end
print("-------------------------------")
print('\nUsed: '..i..' bytes\nusage: dofile("file.lua")\n')
end
dir()

14
Hugo/u_get_ip.lua Executable file
View File

@@ -0,0 +1,14 @@
-- get_ip.lua
-- affiche l'adresse IP
-- zf180718.1103
wifi.sta.connect()
tmr.alarm(0, 1000, tmr.ALARM_AUTO , function()
if wifi.sta.getip() == nil then
print("Connecting to AP...")
else
print("Connected! IP: ",wifi.sta.getip())
tmr.stop(0)
end
end)

7
Hugo/u_start_job.lua Executable file
View File

@@ -0,0 +1,7 @@
--start job. Démarre le robot et le serveur web
print("\nstart job hv180718.1155\n")
dofile("wifi_robot_on_off.lua")
dofile("robot3.lua")

43
Hugo/u_telnet_srv.lua Executable file
View File

@@ -0,0 +1,43 @@
-- a simple telnet server
print("\nzf180718.1105\n")
-- restart server if needed
if telnet_srv ~= nil then
telnet_srv:close()
end
telnet_srv = net.createServer(net.TCP, 180)
telnet_srv:listen(23, 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)
print("Telnet server running...")

8
Hugo/u_web_stop.lua Executable file
View File

@@ -0,0 +1,8 @@
--Pour arrêter le petit serveur WEB
print("\nzf20180718.1049")
srv:close()
srv:listen(80, function(conn)
end)
print("\nWEB stopped\n")

View File

@@ -0,0 +1,49 @@
--Petit serveur WEB pour allumer/éteindre une LED en mode client WIFI
--hv20180711.1606
print("Démarrage")
wifi.sta.disconnect()
wifi.setmode(wifi.STATION)
print("set mode=STATION (mode="..wifi.getmode()..")")
wifi.sta.config{ssid="Hugo", pwd="tototutu"}
tmr.alarm(0, 1000, tmr.ALARM_AUTO , function()
if wifi.sta.getip() == nil then
print("Connecting to AP...")
else
print("Connected! IP: ",wifi.sta.getip())
tmr.stop(0)
end
end)
zLED=0
gpio.mode(zLED, gpio.OUTPUT)
gpio.write(zLED, gpio.HIGH)
srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
conn:on("receive", function(client, request)
local buf = ""
local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP")
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
buf = buf .. "<!DOCTYPE html><html><body><h1>Hello, this is NodeMCU.</h1><form src=\"/\">Turn PIN <select name=\"pin\" onchange=\"form.submit()\">"
local _on, _off = "", ""
if (_GET.pin == "ON") then
_on = " selected=true"
gpio.write(zLED, gpio.LOW)
elseif (_GET.pin == "OFF") then
_off = " selected=\"true\""
gpio.write(zLED, gpio.HIGH)
end
buf = buf .. "<option" .. _on .. ">ON</option><option" .. _off .. ">OFF</option></select></form></body></html>"
client:send(buf)
end)
conn:on("sent", function(c) c:close() end)
end)

75
Hugo/web_oled_decode_url.lua Executable file
View File

@@ -0,0 +1,75 @@
--Petit serveur WEB pour allumer/éteindre une LED en mode client WIFI
print("\nDémarrage hv20180711.1606\n")
hvtime=tmr.create()
wifi.sta.connect()
tmr.alarm(hvtime, 1000, tmr.ALARM_AUTO , function()
if wifi.sta.getip() == nil then
print("Connecting to AP...")
else
print("Connected! IP: ",wifi.sta.getip())
tmr.stop(hvtime)
end
end)
srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
conn:on("receive", function(client, request)
local buf = ""
local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP")
if (method == nil) then
_, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP")
end
local _GET = {}
print("\nNouvelle entrée !")
if (vars ~= nil) then
print("Input: "..vars)
for k, v in string.gmatch(vars, "(%w+)=([%w+-@%%]+)&*") do
_GET[k] = v
print(k..": "..v)
end
end
buf = buf .. "<!DOCTYPE html><html><body><h1>web_oled</h1></br><form name=\"hform\">"
if _GET.hinput=="Valider" then
print((string.gsub(unescape(_GET.htext),"+"," ")))
end
buf = buf .. "<textarea name=\"htext\">hello zuzu</textarea> </br> <input name=\"hinput\" type=\"submit\"></input></form></body></html>"
client:send(buf)
end)
conn:on("sent", function(c) c:close() end)
end)
--source: https://github.com/diegonehab/luasocket/blob/master/src/url.lua
function unescape(s)
return (string.gsub(s, "%%(%x%x)", function(hex)
return string.char(tonumber(hex, 16))
end))
end
--[[
--t1="hello+zuzu+%26+une+belle+%E9cole"
t1="hello+zuzu+%26+une+belle+%E9cole%5Cnun+b%E2teau"
print(string.char(tostring(tonumber("3F", 16))))
print(string.char(63))
print(unescape("%26"))
t3=string.gsub(unescape(t1),"+"," ")
print(t3)
t2="école\ntoto"
print(t2)
]]
--print( string.gsub("hello+zuzu+%26+une+belle+%E9cole%5Cun+b%E2teau","+"," ")
--[[ source OLED:
https://www.google.ch/search?q=nodemcu+lua+oled+display&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjG8ba8ra3cAhVDCpoKHedlDS4Q_AUICigB&biw=1536&bih=828
https://www.hackster.io/kayakpete/esp8266-oled-display-52ae50
http://blog.rl.cx/2017/01/08/bien-d%C3%A9buter-avec-nodemcu/
https://github.com/FredThx/nodemcu_iot/blob/master/i2c_display.lua
https://www.instructables.com/id/NODEMCU-LUA-ESP8266-With-I2C-LCD-128-X-64-OLED-Dis/
]]

53
Hugo/web_press_button_led.lua Executable file
View File

@@ -0,0 +1,53 @@
--Petit serveur WEB pour allumer/éteindre une LED en mode client WIFI
print("\nDémarrage hv20180711.1606\n")
--wifi.sta.disconnect()
--wifi.setmode(wifi.STATION)
--print("set mode=STATION (mode="..wifi.getmode()..")")
--wifi.sta.config{ssid="Hugo", pwd="tototutu"}
wifi.sta.connect()
tmr.alarm(0, 1000, tmr.ALARM_AUTO , function()
if wifi.sta.getip() == nil then
print("Connecting to AP...")
else
print("Connected! IP: ",wifi.sta.getip())
tmr.stop(0)
end
end)
zLED=0
gpio.mode(zLED, gpio.OUTPUT)
gpio.write(zLED, gpio.HIGH)
srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
conn:on("receive", function(client, request)
local buf = ""
local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP")
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
print(k..": "..v)
end
end
buf = buf .. "<!DOCTYPE html><html><body><h1>Hello, this is NodeMCU.</h1>Turn PIN : </br></br>"
local _on, _off = "", ""
if (_GET.pin == "ON") then
_on = " selected=true"
gpio.write(zLED, gpio.LOW)
elseif (_GET.pin == "OFF") then
_off = " selected=\"true\""
gpio.write(zLED, gpio.HIGH)
end
buf = buf .. "<a href=\"?pin=ON\"><button>ON</button></a> <a href=\"?pin=OFF\"><button>OFF</button></a>"
client:send(buf)
end)
conn:on("sent", function(c) c:close() end)
end)

49
Hugo/web_robot_on_off.lua Executable file
View File

@@ -0,0 +1,49 @@
--Petit serveur WEB pour allumer/éteindre une LED en mode client WIFI
print("\nDémarrage hv20180711.1606\n")
hvtime=tmr.create()
wifi.sta.connect()
tmr.alarm(hvtime, 1000, tmr.ALARM_AUTO , function()
if wifi.sta.getip() == nil then
print("Connecting to AP...")
else
print("Connected! IP: ",wifi.sta.getip())
tmr.stop(hvtime)
end
end)
zLED=0
gpio.mode(zLED, gpio.OUTPUT)
gpio.write(zLED, gpio.HIGH)
srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
conn:on("receive", function(client, request)
local buf = ""
local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP")
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
buf = buf .. "<!DOCTYPE html><html><body><h1>Faire avancer ou arreter le robot</h1></br></br>"
local _on, _off = "", ""
if (_GET.pin == "Forward") then
_on = " selected=true"
avance_robot()
gpio.write(zLED, gpio.LOW)
elseif (_GET.pin == "Backward") then
_off = " selected=\"true\""
stop_robot()
gpio.write(zLED, gpio.HIGH)
end
buf = buf .. "<a href=\"?pin=Forward\"><button>Forward</button></a> <a href=\"?pin=Backward\"><button>Backward</button></a>"
client:send(buf)
end)
conn:on("sent", function(c) c:close() end)
end)