Sending data to TELNET app with ESP8266 and arduino uno - esp8266

I started to test the ESP8266 module, i wrote in the serial port this commands: AT, AT+RST, AT+CWMODE=1(station mode), AT+CWLAP, AT+CWJAP="My network name","password", AT+CIPMUX=1, AT+CIPSERVER=1,80, AT+CIPSEND=0,"numer of char of my string", "MyMessage", AT+CIPCLOSE=0 and it work, its sends the message to my phone.
Now I try to do some function that sends automatically those commands, but when i get to the sending message part it gives me an error.
I post my code below:
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(9, 10); // RX | TX
void setup()
{
Serial.begin(9600); // communication with the host computer
// Start the software serial for communication with the ESP8266
ESPserial.begin(9600);
delay(1000);
Serial.println("");
Serial.println("Remember to to set Both NL & CR in the serial monitor.");
Serial.println("Ready");
Serial.println("");
trimiteDate("AT+IPR=9600",1000);
trimiteDate("AT",1000);
trimiteDate("AT+RST",1000);
trimiteDate("AT+CWMODE=1",1000);
trimiteDate("AT+CWLAP",1000);
trimiteDate("AT+CWJAP=\"DIGI_d61430\",\"ddcc29eb\"",1000);
trimiteDate("AT+CIFSR",1000);
trimiteDate("AT+CIPMUX=1",1000);
trimiteDate("AT+CIPSERVER=1,80",1000);
scrie("Sir de caractere",1000);
}
void loop()
{
// listen for communication from the ESP8266 and then write it to the serial monitor
if ( ESPserial.available() ) { Serial.write( ESPserial.read() ); }
// listen for user input and send it to the ESP8266
if ( Serial.available() ) { ESPserial.write( Serial.read() ); }
}
void trimiteDate(String comanda, const int timp ){
ESPserial.println(comanda);
while ( ESPserial.available() ) { Serial.write( ESPserial.read() ); }
while ( Serial.available() ) { ESPserial.write( Serial.read() );}
delay(timp);
}
void scrie(String sir, const int timp){
int lungimeSir = sir.length();
String startTransmisie = "AT+CIPSEND=1,";
String stopTransmisie = "AT+CIPCLOSE=0";
String sirDate = startTransmisie + lungimeSir;
trimiteDate(sirDate,1000);
ESPserial.println(sir);
trimiteDate(stopTransmisie,1000);
delay(timp);
}

Related

MQTT NodeMCU servo can react only on decimal array payload

I'm creating a fish feeder with SG90 servo and NodeMCU
I used this sketch:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Servo.h>
// Update these with values suitable for your network.
const char* ssid = "your_wifi_hotspot";
const char* password = "your_wifi_password";
const char* mqtt_server = "broker.mqttdashboard.com";
//const char* mqtt_server = "iot.eclipse.org";
Servo myservo; // create servo object to control a servo
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(100);
// We start by connecting to a WiFi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Command from MQTT broker is : [");
Serial.print(topic);
for(int i=0;i<length;i++)
{
if((int)payload[i]>194||(int)payload[i]<0)
break;
myservo.write((int)payload[i]); // tell servo to go to position in variable '(int)payload[i]'
}
}//end callback
void reconnect() {
// Loop until we're reconnected
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
//if you MQTT broker has clientID,username and password
//please change following line to if (client.connect(clientId,userName,passWord))
if (client.connect(clientId.c_str()))
{
Serial.println("connected");
//once connected to MQTT broker, subscribe command if any
client.subscribe("OsoyooCommand");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 6 seconds before retrying
delay(6000);
}
}
} //end reconnect()
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
myservo.attach(D1); // attaches the servo on pin D1 to the servo object
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
The servo is working when I use MQTTBox in order to send a payload as "Decimal Array", it is however is giving me a hard time when I send payload as JSON string.
If I send "Decimal Array" 1 it does turn Servo to position 1, however if I simply send 1 as a payload as a string it moves Servo to position 49.
If I send payload as 2 it moves to position 50.
If I send payload as 10 then position is 4948
looks like position of 1 and position of 0 at the same time.
My ultimate goal is to send those payloads via HomeAssistant which are sent as string or JSON, however I don't find a correct solution at the moment.
I would highly appreciate any help or solution.
MQTT payloads are UTF-8 encoded so the Arduino PubSubClient library treats the payload as an array of uint8_t.
If you want to send and receive JSON then you can use the ArduinoJson library to parse a JSON payload. So assuming a JSON payload like:
{
"position": 123
}
Then you can implement a callback such as:
#include <ArduinoJson.h>
// Assuming a fixed sized JSON buffer
StaticJsonBuffer<200> jsonBuffer;
void callback(char* topic, byte* payload, unsigned int length)
{
JsonObject& root = jsonBuffer.parseObject(payload);
if (root.success() && root.is<JsonObject>())
{
int position = root.as<JsonObject>().get<int>("position");
myservo.write(position);
}
}
Looks like the motor is taking the position of the ASCII equivalent of the number when you send it as a string.
i.e.
ASCII equivalent of the character '1' in 49 in decimal
ASCII equivalent of the character '2' in 50 in decimal
Try sending the character 'a', the motor will go to 97.
If you want to send a string, you will have to change the following code:
for(int i=0;i<length;i++)
{
if((int)payload[i]>194||(int)payload[i]<0)
break;
myservo.write((int)payload[i]); // tell servo to go to position in variable '(int)payload[i]'
}
to:
int location=String((char*)payload).toInt()
if((location>194)||(location<0))
return;
myservo.write(location);

ESP8266 disconnects immediately after connecting to server

`I am new to ESP8266.
I have created a website hosted on 000webhost, however whenever I connect to the server using the ESP8266's AT command set the connection closes instantly. I am trying to send some data from my Arduino board to the website via the ESP8266
Therefore I can not send any message to the website.
Any ideas on how to handle this issue? Thanks!
Output on the serial monitor
Arduino Code
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); //RX,TX
int LEDPIN = 13;
void setup()
{
pinMode(LEDPIN, OUTPUT);
Serial.begin(9600); // communication with the host computer
//while (!Serial) { ; }
// Start the software serial for communication with the ESP8266
mySerial.begin(9600);
Serial.println("");
Serial.println("Remember to to set Both NL & CR in the serial monitor.");
Serial.println("Ready");
Serial.println("");
}
void loop()
{
digitalWrite(13,1);
// listen for communication from the ESP8266 and then write it to the serial
monitor
if ( mySerial.available() ) { Serial.write( mySerial.read() ); }
// listen for user input and send it to the ESP8266
if ( Serial.available() )
// { mySerial.write( mySerial.print("AT+CWMODE=1") ); }
{ mySerial.write( Serial.read() ); }
}
PHP Code:
<?php
if(isset($_GET['stat'])){
$status=$_GET['stat'];
$a2="<!DOCTYPE html><br><html><br>" . $status ."<br><html>";
$fp = fopen("a2.php", "w");
fwrite($fp, $a2);
fclose($fp);
echo $status;
}
else {echo "house";}
?>

Arduino ESP8266 01 MQTT Raspberry pi

I want to use ESP 8266 01 and arduino uno as client in MQTT. The code For ESP8266 01 is successfully compiled and I'M getting errors in Arduino uno
The error is 'messageTemp' was not declared in this scope
Amd also I have a thought of using stm32xx in client.
If I compile for that
exit status 1
ISO C++ forbids comparison between pointer and integer [-fpermissive]
above is the error I'm getting
1)ESP code
// Loading the ESP8266WiFi library and the PubSubClient library
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Change the credentials below, so your ESP8266 connects to your router
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
const char* mqtt_server = "YOUR_RPi_IP_Address";
// Initializes the espClient
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}
if(topic=="home/office/esp1/gpio2"){
Serial.print("Changing GPIO 2 to ");
if(messageTemp == "1"){
// digitalWrite(ledGPIO2, HIGH);
Serial.print("On");
}
else if(messageTemp == "0"){
// digitalWrite(ledGPIO2, LOW);
Serial.print("Off");
}
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
client.subscribe("home/office/esp1/gpio2");
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
Code for Arduino UNO
void setup(){
Serial.begin(9600);
pinMode(12, OUTPUT);
digitalWrite(12, HIGH);
String messageTemp;
}
void callback(String topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
}
void loop ()
{
if (Serial.available()){
char topic = Serial.read();
{
if (topic=="home/office/esp1/gpio2")
{
Serial.print("Changing GPIO 2 to ");
if(messageTemp == "1"){
digitalWrite(12, HIGH);
Serial.print("On");
}
else if(messageTemp == "0")
{
digitalWrite(12, LOW);
Serial.print("Off");
}
}}}}
ESP code doesn't look the whole source code you provided. In case of Arduino UNO, if you're intending to use messageTemp as a global variable, then you need to declare it only one time outside of functions. In the above code, you declared it twice in setup() and callback(), then those are considered as local variables. Even in loop(), there's no declaration, this should create the compile error.

GET request in LUA - ">>" after send request

I send my Lua code by Arduino IDE.
My sketch in Arduino:
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(2, 3); // RX | TX
void setup()
{
Serial.begin(9600); // communication with the host computer
//while (!Serial) { ; }
// Start the software serial for communication with the ESP8266
ESPserial.begin(9600);
Serial.println("");
Serial.println("Remember to to set Both NL & CR in the serial monitor.");
Serial.println("Ready");
Serial.println("");
delay(1000);
}
void loop()
{
// listen for communication from the ESP8266 and then write it to the serial monitor
if ( ESPserial.available() ) { Serial.write( ESPserial.read() ); }
// listen for user input and send it to the ESP8266
if ( Serial.available() ) { ESPserial.write( Serial.read() ); }
}
I open serial port and send my code:
conn=net.createConnection(net.TCP, 0)
conn:on("receive", function(conn, payload) print(payload) end)
conn:connect(8080, "192.168.0.100")
conn:send("GET /json.htm?type=command&param=udevice&idx=3&nvalue=0&svalue=69 HTTP/1.1\r\nHost: 192.168.0.100\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
But my ESP return ">>" after last command.. there is screen
When I replace conn:send on this:
conn:send("GET / HTTP/1.1\r\nHost: 192.168.0.100\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
All is correct, I take respond from server...
Thanks for help!

Android to Arduino Uno + Wi-Fi shield string communication

I am trying to make a wireless light control device (on/off/dimming) using an Arduino, an Android app, and a router.
I am setting the Arduino to a static IP 192.168.1.2 using the router. I am sending strings ("1"-off, "2"-decrease brightness, "3"-increase brightness, "4"-on) from the Android app to the IP address 192.168.1.2. I have connected the Arduino to the Internet using the Arduino Wi-Fi shield and set up the WifiServer using the following code:
char ssid[] = "NAME"; // Your network SSID (name)
char pass[] = "PASS"; // Your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // Your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(23);
boolean alreadyConnected = false; // Whether or not the client was connected previously.
void setup() {
// Start serial port:
Serial.begin(9600);
// Attempt to connect to Wi-Fi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
// Wait 10 seconds for connection:
delay(10000);
}
// Start the server:
server.begin();
// You're connected now, so print out the status:
printWifiStatus();
}
The main problem I am having is how to accept and print out the strings from the Android device. The current code I have to do this is:
// Listen for incoming clients
WiFiClient client = server.available();
if (client) {
// An HTTP request ends with a blank line
boolean newLine = true;
String line = "";
while (client.connected() && client.available()) {
char c = client.read();
Serial.print(c);
// If you've gotten to the end of the line (received a newline
// character) and the line is blank, the HTTP request has ended,
// so you can send a reply.
if (c == '\n' && newLine) {
// Send a standard HTTP response header
//client.println("HTTP/1.1 200 OK");
//client.println("Content-Type: text/html");
//client.println();
}
if (c == '\n') {
// You're starting a new line
newLine = true;
Serial.println(line);
line = "";
}
else if (c != '\r') {
// You've gotten a character on the current line
newLine = false;
line += c;
}
}
Serial.println(line);
// Give the web browser time to receive the data
delay(1);
// Close the connection:
//client.stop();
}
}
I am basing this code off of the blog post Android Arduino Switch with a TinyWebDB hack, but this code is for an Ethernet shield. The Android app was made using the MIT App Inventor, which is similar to the one found the blog post.
TLDR, how can I get the strings using the Arduino Wi-Fi shield?
You can read the characters into a full string instead of reading each individual character into the serial monitor as in your example above.
In your example, this bit of code would read each character from the client TCP session and print it to the serial monitor, thus displaying the HTTP requests in the serial console.
char c = client.read();
Serial.print(c);
Try something like this instead. Declare a string named "readString" before your setup() function in the Arduino sketch like this:
String readString;
void setup() {
//setup code
}
void loop() {
// Try this when you're reading inside the while client.connected loop instead of the above:
if (readString.length() < 100) {
readString += c;
Serial.print(c);
}
Here is a working example of the loop():
void loop() {
// Listen for incoming clients
WiFiClient client = server.available();
if (client) {
Serial.println("new client");
// An HTTP request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
//Serial.write(c);
// If you've gotten to the end of the line (received a newline
// character) and the line is blank, the HTTP request has ended,
// so you can send a reply.
if (readString.length() < 100) {
readString += c;
Serial.print(c);
}
if (c == '\n' && currentLineIsBlank) {
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connnection: close");
client.println();
client.println("<!DOCTYPE HTML>");
//send the HTML stuff
client.println("<html><head><title>Admin Web</title><style type=\"text/css\">");
client.println("body { font-family: sans-serif }");
client.println("h1 { font-size: 14pt; }");
client.println("p { font-size: 10pt; }");
client.println("a { color: #2020FF; }");
client.println("</style>");
client.println("</head><body text=\"#A0A0A0\" bgcolor=\"#080808\">");
client.println("<h1>Arduino Control Panel</h1><br/>");
client.println("<form method=\"link\" action=\"/unlockdoor\"><input type=\"submit\" value=\"Unlock Door!\"></form>");
client.println("<br/>");
client.println("</body></html>");
break;
}
if (c == '\n') {
// You're starting a new line.
currentLineIsBlank = true;
}
else if (c != '\r') {
// You've gotten a character on the current line.
currentLineIsBlank = false;
}
}
}
// Give the web browser time to receive the data.
delay(1);
// Close the connection:
client.stop();
Serial.println("client disonnected");
if (readString.indexOf("/unlockdoor") > 0)
{
unlockdoor();
Serial.println("Unlocked the door!");
}
readString = "";
}

Resources