Arduino Uno + ESP8266 reading server's response - arduino

I'm sending a GET request from Arduino Uno using ESP8266. The request is sent, but I'm unable to print the received response.
I'm using code from https://elementztechblog.wordpress.com/2015/05/13/esp8266-based-temperature-data-logger-using-arduino/
I have changed the code for connecting to my server and I can see the GET request is received on my server's log.
I tried putting
while (ser.available())
{
Serial.write(ser.read());
}
after the Serial.println("AT+CIPCLOSE"); statement.
BUT I'm not getting anything on Serial monitor after "AT+CIPCLOSE"
EDIT:
Here's my entire code:
// connect 10 to TX of Serial USB
// connect 11 to RX of serial USB
SoftwareSerial ser(10, 11); // TX, RX
// this runs once
void setup()
{
// enable debug serial
Serial.begin(9600);
// enable software serial
ser.begin(9600);
// reset ESP8266
ser.println("AT+RST");
}
// the loop
void loop()
{
// TCP connection
String cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += "192.168.0.25";
cmd += "\",3000";
ser.println(cmd);
if(ser.find("Error"))
{
Serial.println("AT+CIPSTART error");
return;
}
// prepare GET string
String getStr = "GET /api/myservice";
getStr += "\r\n\r\n";
// send data length
cmd = "AT+CIPSEND=";
cmd += String(getStr.length());
ser.println(cmd);
if(ser.find(">")){
ser.print(getStr);
}
else
{
ser.println("AT+CIPCLOSE");
// alert user
Serial.println("AT+CIPCLOSE");
// CODE I FOUND FOR READING THE REPLY FROM SERVER:
while (ser.available())
{
// char c = ser.read();
Serial.write(ser.read());
// if (c == '\r') Serial.print('\n');
}
}
delay(1000);
}
ESP Details:
ESP-01
AT version: 0.40.0.0

If you are only struggling to read a response then the answer is simple;
You are closing the TCP connection before you try to read:
ser.println("AT+CIPCLOSE");
// alert user
Serial.println("AT+CIPCLOSE");
// CODE I FOUND FOR READING THE REPLY FROM SERVER:
while (ser.available())
{
Move the reading while into the above block just beneath ser.print(getStr); but add a delay between the two as well.

Related

Send data from ESP32 to Processing via wifi

I was trying to connect ESP32 (client)-Processing (server) and I think I made it work, but server doesn't receive or print anything. Why processing doesn't recognise when client is connected? I am new to Processing and trying to undrestand how it works.
Processing:
import processing.net.*;
Server myServer;
void setup() {
size(400, 400);
// Starts a myServer on port 5204
myServer = new Server(this, 5204);
println(Server.ip());
}
void serverEvent(Server someServer, Client someClient) {
println("We have a new client: " + someClient.ip());
}
ESP32:
#include <WiFi.h>
const char* ssid = "myNetwork";
const char* pass = "myPassword";
void setup()
{
Serial.begin(115200);
delay(10);
WiFi.begin(ssid,pass);
Serial.print("Connecting.");
while(WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.print("WiFi connected - IP address: ");
Serial.println(WiFi.localIP());
delay(500);
}
void loop()
{
const uint16_t port = 5204;
const char * host = "10.0.26.xx";
Serial.print("Connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (client.connect(host, port)){
Serial.println("Sending data"); // printed on serial monitor
client.print("Hello");
}
// This will send a request to the server
client.print("Send this data to the server");
Serial.println("Closing connection.");
client.stop();
}
EDITED
It gives the same prints even if I don't run the processing program. So is it connected somewhere else instead of the server?
At the processing I am getting only that "The value of parameter someServer is not used"
Well, I figured out. It was a firewall issue. I disable the firewall and then it worked. Also, before that I created a new rule for the Processing and the Port but for some reason it didn't work I don't undrestand why. Disabled it was the solution to my problem.
Your processing code is missing the part where you retrieve data from the client.
You need to add something like this:
void draw() {
// Get the next available client
Client thisClient = myServer.available();
// If the client is not null, and says something, display what it said
if (thisClient != null) {
String whatClientSaid = thisClient.readString();
if (whatClientSaid != null) {
println(thisClient.ip() + "t" + whatClientSaid);
}
}
}
Source
I don't see any other obvious issues but I cannot test something similar to your setup right now. Maybe you can give it a try.

arduino and esp8266 interface

I want to send some AT commands to esp8266 using arduino and get the reply from serial monitor. this is the code:(the purpose of this code is to update a thingspeak channel)
#include<SoftwareSerial.h>
SoftwareSerial esp8266(3,2);
#define ID "user"
#define PASS "pass"
String apiKey = "apikey";
void setup() {
Serial.setTimeout(5000);
Serial.begin(9600);
esp8266.begin(9600);
// delay(1000);
String command6="AT+RST";
esp8266.println(command6);
if(esp8266.available())
{
while(esp8266.available())
{
char c=esp8266.read();
Serial.write(c);
}
}
delay(2000);
}
void loop() {
delay(2000);
String command="\nAT";
esp8266.println(command);
if(esp8266.available())
{
while(esp8266.available())
{
char c=esp8266.read();
Serial.write(c);
}
}
String cmd = "\nAT+CIPSTART=\"TCP\",\"";
cmd += "144.212.80.11"; // api.thingspeak.com
cmd += "\",80";
esp8266.println(cmd);
if(esp8266.available())
{
while(esp8266.available())
{
char c=esp8266.read();
Serial.write(c);
}
}
delay(3000);
String command3="\nAT+CIPSEND=200";
esp8266.println(command3);
if(esp8266.available())
{
while(esp8266.available())
{
char c=esp8266.read();
Serial.write(c);
}
}
delay(1000);
String getStr = "GET /update?api_key=";
getStr += apiKey;
getStr += "&field1=10";
esp8266.println(getStr);
esp8266.println("\r\r\r\r\r\r\r\r");
if(esp8266.available())
{
while(esp8266.available())
{
char c=esp8266.read();
Serial.write(c);
}
}
delay(15000);
}
user and pass are my wifi username and password. the problem is, the esp8266 responds "ok" to at commands but when it gets to the last parts, it gives me this:
A))-R¤%%JHÕ¨TUPZ="TCP","144.212.80.11",80
CONNECT
OK
ERROR
AT+CIPSEND=200
OK
> GET /update?api_key=apikey&field1=10
CAT
AT+CIPSTART="TCP","144.212.80.11",80
AT+CIPSEND=200
GET /update?api_key=apikey&field1=10
AT
AT+CIPSTART="TCP","144.212.80.11",80
busy s...
i have put a few delays inside the code but after it inserts the GET it gets back to the loop runs the program again with no delays and then esp8266 resets itself.
Besides waiting for the OK, you also need to make sure that you are using the right IP address for ThingSpeak. The offical static IP for ThingSpeak is 184.106.153.149 found here (http://www.mathworks.com/help/thingspeak/channel-settings.html#endpoints).
Try using /n after the At command not before and also check the correct format for AT+CIPSEND
GET http://api.thingspeak.com/update?api_key=KTQXXXXXXXXXXXXX&field1=10 HTTP/1.0 \r\n\r\n
try this format
There are a few things to keep in mind when working with ESP8266 communicate over a network.
1 The response might not be received in a constant time i.e 100ms
or 1ms etc. there will always be random delay.
2 Check if the ESP is not running out of current while making a
GET/POST request.
3 Check for every character/escape sequence ('\r' '\n' etc.) and
place them into right place into your "Request" string.
This might help you: Arduino ESP8266 AT GET Request
Thank you. :)

Arduino + ESP8266, How can i send Continous Get Request?

I have a code that was available on this website https://hackaday.io/project/3072/instructions . I made the code work by modifying it a little but the main problem is that it serves the GET request only once. What i want is continuous page fetch and there should be no TCP connection closing.
I have tried different methods but the connection always breaks after 1 GET request.
Moreover, if i do not send any GET request then it serves the domain's index page continuously without breaking TCP connection.
This is the original code http://dunarbin.com/esp8266/retroBrowser.ino.
And this is mine.
#define SSID "vivek"
#define PASS "bustedparamour21"
#define DEST_HOST "www.electronics2work.com"
#define DEST_IP "31.170.161.234"
#define TIMEOUT 10000 // mS
#define CONTINUE false
#define HALT true
#define ECHO_COMMANDS // Un-comment to echo AT+ commands to serial monitor
// Print error message and loop stop.
void errorHalt(String msg)
{
Serial.println(msg);
Serial.println("HALT");
while(true){};
}
// Read characters from WiFi module and echo to serial until keyword occurs or timeout.
boolean echoFind(String keyword)
{
byte current_char = 0;
byte keyword_length = keyword.length();
// Fail if the target string has not been sent by deadline.
long deadline = millis() + TIMEOUT;
while(millis() < deadline)
{
if (Serial1.available())
{
char ch = Serial1.read();
Serial.write(ch);
if (ch == keyword[current_char])
if (++current_char == keyword_length)
{
Serial.println();
return true;
}
}
}
return false; // Timed out
}
// Read and echo all available module output.
// (Used when we're indifferent to "OK" vs. "no change" responses or to get around firmware bugs.)
void echoFlush()
{while(Serial1.available()) Serial.write(Serial1.read());}
// Echo module output until 3 newlines encountered.
// (Used when we're indifferent to "OK" vs. "no change" responses.)
void echoSkip()
{
echoFind("\n"); // Search for nl at end of command echo
echoFind("\n"); // Search for 2nd nl at end of response.
echoFind("\n"); // Search for 3rd nl at end of blank line.
}
// Send a command to the module and wait for acknowledgement string
// (or flush module output if no ack specified).
// Echoes all data received to the serial monitor.
boolean echoCommand(String cmd, String ack, boolean halt_on_fail)
{
Serial1.println(cmd);
#ifdef ECHO_COMMANDS
Serial.print("--"); Serial.println(cmd);
#endif
// If no ack response specified, skip all available module output.
if (ack == "")
echoSkip();
else
// Otherwise wait for ack.
if (!echoFind(ack)) // timed out waiting for ack string
if (halt_on_fail)
errorHalt(cmd+" failed");// Critical failure halt.
else
return false; // Let the caller handle it.
return true; // ack blank or ack found
}
// Connect to the specified wireless network.
boolean connectWiFi()
{
String cmd = "AT+CWJAP=\""; cmd += SSID; cmd += "\",\""; cmd += PASS; cmd += "\"";
if (echoCommand(cmd, "OK", CONTINUE)) // Join Access Point
{
Serial.println("Connected to WiFi.");
return true;
}
else
{
Serial.println("Connection to WiFi failed.");
return false;
}
}
// ******** SETUP ********
void setup()
{
Serial.begin(9600); // Communication with PC monitor via USB
Serial1.begin(9600); // Communication with ESP8266 via 5V/3.3V level shifter
Serial1.setTimeout(TIMEOUT);
Serial.println("ESP8266 Demo");
delay(2000);
Serial.println("Module is ready.");
echoCommand("AT+GMR", "OK", CONTINUE); // Retrieves the firmware ID (version number) of the module.
echoCommand("AT+CWMODE?","OK", CONTINUE);// Get module access mode.
// echoCommand("AT+CWLAP", "OK", CONTINUE); // List available access points - DOESN't WORK FOR ME
echoCommand("AT+CWMODE=1", "", HALT); // Station mode
echoCommand("AT+CIPMUX=1", "", HALT); // Allow multiple connections (we'll only use the first).
//connect to the wifi
boolean connection_established = false;
for(int i=0;i<5;i++)
{
if(connectWiFi())
{
connection_established = true;
break;
}
}
if (!connection_established) errorHalt("Connection failed");
delay(5000);
//echoCommand("AT+CWSAP=?", "OK", CONTINUE); // Test connection
echoCommand("AT+CIFSR", "", HALT); // Echo IP address. (Firmware bug - should return "OK".)
//echoCommand("AT+CIPMUX=0", "", HALT); // Set single connection mode
}
// ******** LOOP ********
void loop()
{
// Establish TCP connection
String cmd = "AT+CIPSTART=0,\"TCP\",\""; cmd += DEST_IP; cmd += "\",80";
if (!echoCommand(cmd, "OK", CONTINUE)) return;
delay(2000);
// Get connection status
if (!echoCommand("AT+CIPSTATUS", "OK", CONTINUE))
return;
// Build HTTP request.
cmd = "GET /";
cmd +="iot/graphing.php?a=1&b=ldr&c=41 ";
cmd += "HTTP/1.1\r\nHost: ";
cmd += DEST_HOST;
cmd += ":80\r\n\r\n";
// Ready the module to receive raw data
if (!echoCommand("AT+CIPSEND=0,"+String(cmd.length()), ">", CONTINUE))
{
echoCommand("AT+CIPCLOSE", "", CONTINUE);
Serial.println("Connection timeout.");
return;
}
// Send the raw HTTP request
echoCommand(cmd, "OK",CONTINUE ); // GET
// Loop forever echoing data received from destination server.
while(true)
while (Serial1.available())
Serial.write(Serial1.read());
errorHalt("ONCE ONLY");
}
This code makes get request only once. How can i make it serve GET request Continously without closing TCP connection?
THANKS in Advance!!
You need to close your connection using AT+CIPCLOSE and then start a new connection again.
For example, if you need to make two connections everytime(like making connection with 2 websites) , you can make 1 connection, then close this connection. Now make another connection and close it.
I made 2 connections in my loop() function using above logic and it is working fine.

Can't reliably get Arduino Ethernet shield to accept connections

I have been playing with the Arduino Ethernet shield. I can't get it to reliably accept connections when running a webserver type application. When I can't connect to it, I can't ping it. The message I get is "Reply from 192.168.1.14: Destination host unreachable.". Where 192.168.1.14 is the ip of the computer I am trying to connect from. Why would an ip on my local subnet be unreachable? Is the shield not correctly identifying itself on the network? Is there anything I can do in Arduino code?
Here is my code. If you see anything wrong, please let me know.
Update: I plugged it into my main home router instead of a switch and it worked immediately there. At any rate, once I can connect to it, it keep working as long as its powered on.
#include <WString.h>
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDA, 0x02 };
IPAddress ip(192,168,1,177);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
#define DOOR_BUTTON 2
String readString = String(100); //string for fetching data from address
void setup()
{
Serial.begin(9600);
digitalWrite(DOOR_BUTTON, LOW);
pinMode(DOOR_BUTTON, OUTPUT);
// start the Ethernet connection and the server:
Serial.println("Initiaizing ethernet...");
// this uses a fixed address
Ethernet.begin(mac, ip);
// get an address with DHCP
//if (Ethernet.begin(mac) == 0)
// Serial.println("Failed to configure Ethernet using DHCP");
// give the card a second to initialize
delay(1000);
server.begin();
Serial.print("Garage Door Opener Control Ready at IP address ");
Serial.println(Ethernet.localIP());
}
void loop()
{
// command received (one character) '1' - activate garage door button
char cmd = 0; // 1 - pulse button
boolean done = false; // set to indicate that response is complete
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
readString = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
//int i = c;
//Serial.print("(");
//Serial.print(i);
//Serial.print(")");
// store character received in receive string
if (readString.length() < 100) {
readString += (c);
}
// check for end of line
if (c == '\n') {
//Serial.print("Receved line: ");
//Serial.print(readString);
// process line if its the "GET" request
// a request looks like "GET /?1" or "GET /?2"
if (readString.indexOf("GET") != -1) {
if (readString.indexOf("?1") != -1)
cmd = '1';
// check for other commands here. ie turn on light, etc.
//if (readString.indexOf("?2") != -1)
// cmd = '2';
}
// if a blank line was received (just cr lf, length of 2), then its the end of the request
if (readString.length() == 2) {
if (cmd == '1'){
Serial.println("Activate Button");
digitalWrite(DOOR_BUTTON, HIGH);
delay(1000);
digitalWrite(DOOR_BUTTON, LOW);
}
// add other commands here
// send web page back to client
Serial.println("sending web page");
SendWebPage(client);
Serial.println("web page sent");
cmd = 0;
// break out and disconnect. This will tell the browser the request is complete without having to specify content-length
break;
} // end of request reached
// start line over
readString = "";
} // end of line reached
} // end data is available from client
} // end cient is connected
// give the web browser time to receive the data
Serial.println("delay before disconnect");
delay(100);
// close the connection:
client.stop();
Serial.println("client disonnected");
} // end client has been created
}
// send web page
void SendWebPage(EthernetClient client)
{
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
// to specify the length, wooul have to construct the entire string and then get its length
//client.println("Content-Length: 1234");
client.println("Connnection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<head>");
client.println("<title>Garage Door Control</title>");
client.println("<style type='text/css'>");
client.println(".label {font-size: 40px; text-align:center;}");
client.println("button {width: 200px; height: 100px; font-size: 40px; -webkit-appearance: none; background-color:white; }");
client.println("</style>");
client.println("<script type='text/javascript'>");
client.println("function OnButtonClicked(parm) { window.location.href=\"X?\" + parm; }");
client.println("</script>");
client.println("</head>");
client.println("<body style=\"background-color:orange\">");
client.println("<div class=\"label\">");
client.println("Garage Door Control<br/><br/>");
// future idea: could read a limit switch on the garage door here and tell the user if the door is currently open or closed
/*
if (digitalRead(DOOR_OPEN_INPUT) == HIGH)
client.println("Door is Open");
else
client.println("Door is Closed");
client.println("<br>");
*/
// door open / close button
client.println("<button onclick=\"OnButtonClicked('1');\">Activate</button><br/>");
// add more buttons here
// button separator
//client.println("<div style=\"height:20px\"></div>");
//client.println("<button onclick=\"OnButtonClicked('2');\">Off</button>");
client.println("</div>");
client.println("</body>");
client.println("</html>");
client.println("");
}
The code specifies IPAddress ip(192,168,1,177); but in the question post you refer to the address 192.168.1.14. sS this a typo or are you just pinging the wrong address?

simple web server nort working with arduino wifi shield

I have recently bought an arduino wifi shield(Atmal chip 32UC3A1512-U), which I connected with
my Arduino Mega ADK R3 board)...It is getting connected to my wifi network, But when I run the
SimpleWebServer Example provided in the library to on/off the LED is not working. The code is given below...
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "belkin.E33"; // your network SSID (name)
char pass[] = "abc123cde456"; // your network password
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(80);
void setup() {
Serial.begin(9600); // initialize serial communication
pinMode(9, OUTPUT); // set the LED pin mode
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while(true); // don't continue
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
server.begin(); // start the web server on port 80
printWifiStatus(); // you're connected now, so print out the status
}
void loop() {
WiFiClient client = server.available(); // listen for incoming clients
if (client) { // if you get a client,
Serial.println("new client"); // print a message out the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
// the content of the HTTP response follows the header:
client.print("Click here turn the LED on pin 9 on<br>");
client.print("Click here turn the LED on pin 9 off<br>");
// The HTTP response ends with another blank line:
client.println();
// break out of the while loop:
break;
}
else { // if you got a newline, then clear currentLine:
currentLine = "";
}
}
else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
// Check to see if the client request was "GET /H" or "GET /L":
if (currentLine.endsWith("GET /H")) {
digitalWrite(9, HIGH); // GET /H turns the LED on
}
if (currentLine.endsWith("GET /L")) {
digitalWrite(9, LOW); // GET /L turns the LED off
}
}
}
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
// print where to go in a browser:
Serial.print("To see this page in action, open a browser to http://");
Serial.println(ip);
}
The result that I am getting in the serial monitor is
Attempting to connect to Network named: belkin.E33
SSID: belkin.E33
IP Address: 192.168.2.5
strength (RSSI):-56 dBm
To see this page in action, open a browser to http://192.168.2.5
But When I am opening the browser with the specified IP address, It is showing
Could not Connect to 192.168.2.5
I have tried this in mozilla and chrome from my ubuntu machine...also tried from some other machines in the same network but with the same result. But when I am pinging to 192.168.2.5 it is pinging...What went wrong??? . My friend adviced to change the firmware...Is it an issue,bcas as told earlier simple examples for establishing the connection are working...Please guide me
I've got the same problem after upgrading Arduino IDE to lastest version (v2) from v1.0.8 which is doing fine with the wifi shield tests (client and server).
Going to try the nightly build now and see if it's fixed.
Edit: Yeap, Nightly build solves this issue.

Resources