How do I run Lua script using Arduino IDE ? (Using an Arduino uno board as the serial provider for ESP8266) - lua

(I am a complete newbie to microcontrollers and I am a barely intermediate level programmer)
If I send these commands through the serial monitor everything works fine . But if I try it using the code below it just does't work and show errors and what not.
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 4); // RX, TX
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
Serial.println("Goodnight moon!");
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
mySerial.println("conn=net.createConnection(net.TCP, 0)");
mySerial.println("conn:on('receive', function(conn, payload) print(payload) end)");
mySerial.println("conn:connect(80,'50.87.151.128')");
mySerial.println("conn:send('GET /devashishproject/time.php HTTP/1.1\\r\\n')");
mySerial.println("conn:send('Host: kartikkhattar.com\\r\\n')");
mySerial.println("conn:send('Accept: */*\\r\\n')");
mySerial.println("conn:send('User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\\r\\n')");
mySerial.println("conn:send('\\r\\n')");
}
void loop() // run over and over
{
if (mySerial.available())
Serial.print((char)mySerial.read());
if (Serial.available())
mySerial.write((char)Serial.read());
}
It just shows garbled information .Where am I going wrong? Does it have to do the power supply? But it works normally when enter these commands through the serial monitor? Why won't it work when I put it in a code like above?

Related

How to connect a thermal printer to an ESP32?

I want to attach my GOOJPRT Thermal Printer (I believe model QR701, communication RS232) to my ESP32 but I cannot seem to get them working.
I tried all the Adafruit Thermal Printer library examples but get the same error each and every time:
"Error compiling for board ESP32 Dev Module."
I guess the libraries are not meant for the ESP32.
I also tried the "Thermal Printer Library" by Larry Bank (which should be compatible with the ESP32 according to its github docs) but there I cannot figure out how to connect the wires of thermal printer to the ESP32 correctly.
Of course, I do not ask for a specific solution, I am just looking for someone to point me in the right direction!
This is an image of the exact thermal printer I have
Full error message from Adafruit Thermal Printer examples:
C:\Users\Thomas\Documents\Arduino\libraries\SoftwareSerial-master\SoftwareSerial.cpp:41:27: fatal error: avr/interrupt.h: No such file or directory
compilation terminated.
Multiple libraries were found for "Adafruit_Thermal.h"
Used: C:\Users\Thomas\Documents\Arduino\libraries\Adafruit_Thermal_Printer_Library
Not used: C:\Users\Thomas\Documents\Arduino\libraries\Adafruit-Thermal-Printer-Library-master
Multiple libraries were found for "SoftwareSerial.h"
Used: C:\Users\Thomas\Documents\Arduino\libraries\SoftwareSerial-master
Not used: C:\Users\Thomas\Documents\Arduino\libraries\EspSoftwareSerial
exit status 1
Error compiling for board ESP32 Dev Module
You need to use the <HardwareSerial.h> library. SoftwareSerial is for Arduino boards.
"Thermal Printer Library" by Larry Bank is for GOOJPRT PT-210 and use Bluetooth. Won't work for qr-701.
Instead of using Adafruit Library, you can try with this:
ThermalPrinter
Quick start:
Import libraries:
#include "TPrinter.h"
#include <HardwareSerial.h>
Set baudrate and pins.
const int printerBaudrate = 9600; // or 19200 usually
const byte rxPin = 16; // check datasheet of your board
const byte txPin = 17; // check datasheet of your board
const byte dtrPin = 27; // optional
const byte rsePin = 4; // direction of transmission, max3485
You need to use boad with max3485(for 3V3 logic lvl) or similar, if you have printer with rs232.
Necessary in my case. I use board UART - RS485 3,3V - ARK/RJ11 - Waveshare 4777
Init
HardwareSerial mySerial(1);
Tprinter myPrinter(&mySerial, printerBaudrate);
void setup() {
micros();
mySerial.begin(printerBaudrate, SERIAL_8N1, rxPin, txPin); // must be 8N1 mode
pinMode(rsePin, OUTPUT); // optional
digitalWrite(rsePin, HIGH); // optional
// myPrinter.enableDtr(dtrPin, LOW); // optional
myPrinter.begin();
}

read and write on serial port with a lua script on raspberry

i'm currently working on a project aiming at controlling a RS232 device by a Raspberry pi4. I'm forced by other softwares to use a lua script and i never coded in lua, even if i have already made the code in Python... I've searched on google far and wide for an answer but have not found anything helping me.
I want my raspberry to open the COM port, and then read and send messages through that port.
I've tried the lua user wiki and This post on stackoverflow (read and write on windows) but both can't be applied to raspberry.
If anyone could help that'd be awesome !
here's my code in python if that can help you.
import serial
def convertisseur(chemin):
Tableau = []
f = open(chemin)
for row in f:
Tableau.append(row)
f.close
return (Tableau)
def statut(ser):
ser.write(bytearray([0X53,0X07,0X01,0X01,0X41,0X60,0X00,0X73,0X45]));
lecture=ser.readline()
print(lecture);
return()
def main():
ser = serial.Serial('COM3', 115200, timeout=1)
ser.close()
ser.open()
Code=convertisseur('C:/Users/Ello/Desktop/CodePosition.txt')
statut(ser)
ser.write(bytearray([0X53,0X09,0X01,0X02,0X40,0X60,0X00,0X06,0X00,0X2C,0X45]));
ser.readline()
ser.write(bytearray([0X53,0X09,0X01,0X02,0X40,0X60,0X00,0X0F,0X00,0X25,0X45,0X53,0X08,0X01,0X02,0X60,0X60,0X00,0X01,0XF5,0X45]));
ser.readline()
statut(ser)
print('Engine move in cm ? - for trigo, STOP to stop')
Speed = input()
while Speed != "STOP":
speed = int(Speed)
if speed > 38:
speed = 38
if speed < -37:
speed = -37
speed = round(abs((speed-38)))
ser.write(bytearray(int(i, 16) for i in Code[speed-1].split(",")))
ser.write(bytearray([0X53,0X09,0X01,0X02,0X40,0X60,0X00,0X0F,0X00,0X25,0X45,0X53,0X09,0X01,0X02,0X40,0X60,0X00,0X7F,0X00,0X55,0X45]));
ser.readline()
statut(ser)
Speed = input()
print("Fin du programme, fermeture du port, passage du moteur sur OFF")
ser.write(bytearray(int(i, 16) for i in Code[60].split(",")))
statut(ser)
ser.close()
return 0
I want my raspberry to open the COM port, and then read and send messages through that port.
Hi, try vsergeev/lua-periphery: A Lua library for peripheral I/O (GPIO, LED, PWM, SPI, I2C, MMIO, Serial) in Linux
, especially Serial section.
Not sure the dev path for you.
In my case the periphery COM device connect to TTL-USB converter, then USB of Pi, so path is '/dev/ttyUSBx'.
As I know, GPIO has UART serial support too.

Lua ESP8266 script expecting extra =

I am trying to test a proximity sensor with my ESP8266, however the test code I am using keeps failing.
Whenever I run the code, I get an error: motion sensor.lua:1: '=' expected near 'int'
I should also mention I am using ESPlorer v0.2.0
const int PIRSensorOutPin = 2; //PIR Sensor OUT Pin
void setup() {
Serial.begin(9600);
pinMode(PIRSensorOutPin, INPUT);
}
void loop()
{
if (digitalRead(PIRSensorOutPin) == LOW)
{
Serial.println("Person detected!"); //Print to serial monitor
}
else {;}
}
What am I doing wrong?
The Lua interpreter doesn't understand C++.
You're running NodeMCU firmware which runs Lua files. But you're trying to run Arduino C++ code. That's not going to work. To run this code you would have to add ESP8266 support to your Arduino IDE, compile your code and flash it onto the ESP.
Alternatively write your code in Lua.
https://github.com/esp8266/Arduino
https://www.nodemcu.com/index_en.html
What am I doing wrong?
Using the wrong programming language.
NodeMCU wants to run Lua code and you're giving it C code instead, which just can't work.
How do I fix it? (implied)
You can use the arduino IDE to write C++ code for ESP8266, but since you already seem to have everything set up to run Lua code, I suggest just using that instead.
The C code you provided could be rewritten into Lua using the NodeMCU api like this:
local pin = 2 -- The number of the I/O Pin
local type = "down" -- Trigger on falling edge
-- https://nodemcu.readthedocs.io/en/master/modules/gpio/#gpiotrig
gpio.trig(pin, type, function()
print("Movement detected, proceding to exterminate!")
end)

ESP8266 Fatal exception (0) using NodeMCU

When i boot ESP8266 i'm getting on my arduino MEGA serial monitor.
Fatal exception (0): e2= 0d00l(xp00v0xao1,00e0c pe80c00d0x:2= 0d00l(xp00v0xao1,00e0c pe80c00d0x:2= 0d00l(xp00v0xao1,00e0c e 0xp0= 0e)02,0d00a 0e00c00Fic00= 0p0e 0xp0= 0e)02
If i do a hard reset than it prints
Jan 8 2013,rst cause:4, boot mode:(3,6) wdt reset load 0x40100000, len 28740, room 16 tail 4 chksum 0xcd load 0x3ffe8000, len 2888, room 4 tail 4 0xeotail 0 chks
I used NodeMcu flasher nodemcu_integer_0.9.5_20150318.bin and NodeMCU 0.9.5 build 20150318 powered by Lua 5.1.4. I'm using arduino UART (serial monitor) to talk to ESP8266. BAUD RATE : 115200 FLASH SIZE : 4MB FLASH SPEED : 40MHz SPI : DIO Module is powered with apt power (separate power supply)
Here's my connections:
//////////////////////////////////////////////////////////////////////////////
/////// CONNECTIONS ////////
/////////////////////////////////////////////////////////////////////////////
/*
ESP8266 VCC -> BeagleBone 3.3
ESP8266 GND -> Common GND (Arduino & BeagleBone)
ESP8266 CH_PD -> 3K resistor -> VCC
ESP8266 RST -> VCC or pin 13(arduino)
GPIO CAB BE LEFT OPEN OR TIED HIGH
ESP8266 Tx -> pin2 (Arduino software serial Rx)
ESP8266 Rx <- Voltage Divider <- pin3 (Arduino software serial Tx)
*/
Here's my code
#define esp8266 Serial2
#define CH_PD Vcc // but needs a narrow low pulse
#define speed8266 9600 // This is the speed that worked with my ESP8266
void setup()
{
esp8266.begin (speed8266);
Serial.begin(9600);
reset8266(); // Pin CH_PD need a reset before start communication
}
void loop()
{
while(esp8266.available())
{ Serial.write(esp8266.read()); }
while(Serial.available())
{ esp8266.write(Serial.read()); }
}
/*************************************************/
// Reset funtion to accept communication
void reset8266 ()
{
pinMode(CH_PD, OUTPUT);
digitalWrite(CH_PD, LOW);
delay(300);
digitalWrite(CH_PD, HIGH);
}
Here are some snaps of the configuration i did in NodeMCU ( i had already tried with different baud rates)
Advanced Configuration
Configuration
If you are getting fatal error exception like this:
Exception (3):
epc1=0x401003e9 epc2=0x00000000 epc3=0x00000000 excvaddr=0x4000cbd9 depc=0x00000000
In infinite loop in your serial monitor of arduino IDE .
then goto this link download the software and follow the procedure and erase the flash memory to solve the error.
This does not solve fatal error that occurs due to your program but in case your device goes in such condition that it can’t be able to access program memory then it will work and try atleast one time to solve the problem.
This is the procedure to hard reset the nodemcu
( https://www.youtube.com/watch?v=MHrm7axsImI&t=146s )
Step :
Install latest python version in you pc.(https://www.python.org/downloads )
Open cmd prompt as administrator .
Go to c/program files or program files (x86)->python (your version)->Script. For this type (cd c/program files (x86)/python(your version)/Script) then press enter .
Now type (pip install esptool).
Now download ESPlorer ( https://esp8266.ru/esplorer/ ) version(Download ESPlorer.zip (v 0.2.0-rc6)) and extract the file and open executable jar file .
Now goto nodemcu firmware site (https://github.com/nodemcu/nodemcu-firmware/releases ) and from download file (nodemcu_float_0.9.6-dev_20150704.bin ) and copy this file into the c/program files (x86)/python(your version)/Script folder .
Now in cmd prompt just type.
esptool.py --port COM(your port no.) --baud 115200 erase_flash
And press enter.
Note : you can see your port no. into the device manager .
For NODEMCU users who face this issue
This needs to be done only once (first time you connect nodemcu to PC)
Download and run the 32 or 64 bit flasher*:
32 bit: https://github.com/nodemcu/nodemcu-flasher/blob/master/Win32/Release/ESP8266Flasher.exe
64 bit: https://github.com/nodemcu/nodemcu-flasher/blob/master/Win64/Release/ESP8266Flasher.exe
Select the download button on github and open file once downloaded.
Select the chip port from the previous step (Com 6 for me), and then select flash (this should only have to be done once) close flash program once completed. Process is completed when you get the green checkmark in the bottom left hand corner.
PS: make sure you disconnect and re-connect the nodemcu once done
REFERENCE: https://www.instructables.com/NodeMcu-ESP8266-First-Time-Setup-With-Arduino-IDE/

UART data error when using uart.alt(1)

I am trying to acquire rs232 data from a device connected to the ESP8266 (data will then be sent our via http/wifi).
I am using max3232 IC to provide the necessary 3.3v TTL to the ESP8266.
I have have connected the max3232 (pin 12) to GPIO pin 13 (rx) on the ESP8266 (I am only receiving data not sending data, so only the rx pin is connected).
The code i am using:
--
--file: test2.lua
--
tst2 = require "tst2"
tst2.start()
--tst2.lua (testing script)
local module = {}
function module.start()
print("in tst2.start")
uart.alt(1) --use alt GPIO pin 13 (Rx)
uart.setup(0, 9600,8, uart.PARITY_NONE, uart.STOPBITS_1,0)
uart.on("data",10,
function(data)
file.open("data.tmp", "w+")
file.writeline("starting")
for i=1,10 do
file.writeline(string.byte(string.sub(data,i,i)) )
end
file.writeline("from uart: ", data)
file.writeline("finished")
file.close()
end, 0)
uart.alt(0) --switch back to standard Rx/Tx pins
end
return module
The rs232 device connected to the ESP8266 is putting out a single alphabetic character every 3 seconds, however the data written to file (data.tmp) is as follows
starting
10
13
10
13
10
13
10
13
10
13
from uart:
finished
file.close()
Problems:
1- The rs232 device is not issuing any newln or cr characters, but these are appearing in the data file.
2- the string "file.close()" is being written to the data file, and looks like it is the actual lua command that follows the final file.writeline command.
3- the alphabetic data is not appearing in the data file.
4- switching back to the standard uart pins via uart.alt(0) does not work (the ESP8266 must be rebooted - this is not a major issue as the standard uart pins are only used during debugging).
I am writing the rs232 data to a file instead of simply printing it out on the screen (I am using ESPlorer v0.2.0) because the uart.alt(1) command redirects the serial port to the alternative ESP8266 gpio pins.
I think I am doing something fundamentally wrong with the uart set up, but i can't tell what it is.
SOLVED:
It appears that you can't connect the ESP8266 to both the serial port for debugging (e.g. the serial port on a pc running ESPlorer) and also have the alternate serial pins (ESP8266 GPIO 13 and 15) connected (to an external serial device) at the same time.
The nodemcu uart.alt() function does not appear to "turn off" the standard serial i/o pins.
Disconnecting the pc from the standard serial i/o pins solved the problem (debugging becomes an issue, but there are work-arounds to resolve this).
(updated) one workaround is to use a simple telnet server to interact with the lua interpreter. you can either connect the ESP8266 to your wifi router or, even better, set it up as an access point (AP) so that all you have to do is to connect your computer to it and then simply telnet in (to the gateway's IP). so, in addition to the telnet code, you'll need set up the AP in your init.lua. full code for the telnet server and the AP setup is below. A nice benefit is that I can program and monitor the ESP8266 from my phone using an off-the-shelf telnet app!
jj = [[
sock = 22 -- just a placeholder, so it stays global. may not be needed.
-- use sock:send("hello") to insert your own custom output to the client.
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
sock = socket -- make the socket globally available.
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)
]]
file.open("telnet.lua", "w")
file.write(jj)
file.close()
jj = [[
wifi.setmode(wifi.STATIONAP);
wifi.ap.config({ssid="ESPtest",pwd=""});
print("Server IP Address:",wifi.ap.getip())
dofile("telnet.lua")
]]
file.open("init.lua","w")
file.write(jj)
file.close()
node.restart()
output:
Server IP Address: 192.168.4.1 255.255.255.0 192.168.4.1
>

Resources