Esp8266 Http communication over Wifi - http

Goal
I am trying to send temperature data between two Esp8266 modules.
The Server reads a temperature value from the analog pin and is supposed to host this data on a website (I don´t know the correct term for that) over a wifi access point that also runs on the Esp. The Client is supposed to receive the temperature value and output it via serial.
What works
I can connect my phone to the access point and access the data on the IP of the access point. I also can connect the client Esp to my home wifi and it outputs code from different websites.
Problem
But when I try to connect it to the Esp wifi, the wifi login/connection works, but the http.GET function outputs -1 which corresponds to the error message "HTTPC_ERROR_CONNECTION_FAILED".
While the client is connected to the wifi of the Esp my phone displays a similar error message.
I also had the problem that the esp could not continually read A0 while using the Wifi, so I had to build in a delay.
Server Code
// Import required libraries
#include "ESPAsyncWebServer.h"
#include "WiFi.h"
#include <math.h>
#include <ESP8266WiFi.h>
//Constants for temperature calculation
double T;
float V_0 = 5.02;
float R_1 = 99700.0;
float a = 283786.2;
float b = 0.06593;
float c = 49886.0;
float set = 30;
int sensorValue;
float voltage;
// Set your access point network credentials
const char* ssid = "ESP32-Access-Point";
const char* password = "123456789";
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
String readTemp() {
return String((-1.0/b)*(log(((R_1*voltage)/(a*(V_0-voltage)))-(c/a)))); //Function to calculate temperature from Voltage
}
void setup(){
Serial.begin(115200);
Serial.println();
// Setting the ESP as an access point
Serial.print("Setting AP (Access Point)…");
// Remove the password parameter, if you want the AP (Access Point) to be open
WiFi.softAP(ssid, password);
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(IP);
server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/plain", readTemp().c_str());
});
// Start server
server.begin();
}
void loop()
{
//reading of A0
Serial.println(voltage);
Serial.println(readTemp().c_str());
sensorValue = analogRead(0); //?Wifi not working, when reading A0?
delay(10);
voltage = sensorValue * (3.3 / 1023.0);
}
Client Code
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti WiFiMulti;
const char* ssid = "ESP32-Access-Point";
const char* password = "123456789";
void setup () {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting..");
}
Serial.print("Connected to ");
Serial.println(ssid);
}
void loop() {
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
HTTPClient http; //Declare an object of class HTTPClient
http.begin("http://192.168.4.1/temperature"); //Specify request destination
int httpCode = http.GET(); //Send the request
if (httpCode > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
Serial.println("/////////////////////////////////////////////////////////////");
Serial.println(payload); //Print the response payload
}
else{Serial.println("Error");}
http.end(); //Close connection
}
delay(30000); //Send a request every 30 seconds
}
I would really appreciate it if anybody could help me with this because I have been tearing my hair out for weeks over this. Thanks in advance and sorry for any grammatical or spelling mistakes in advance.

Related

Why is esp8266 client not connected to server?

I am new to Arduino and I am not so familiar with it. I am not sure why the client cannot connect to the server and I have been looking at it for hours. Any solution to this would be a great help.
So I successfully establish a server with the code below. But...
// server.ino
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
const char* ssid = "WifiName"; // Wifie name
const char* password = "WifiPassword"; // Wifi password
float sensor_value = 0.0;
String Website;
ESP8266WebServer server(80);
void setup(){
Serial.begin(115200);
WiFi.mode(WIFI_AP);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while(WiFi.status()!=WL_CONNECTED){
Serial.print(".");
delay(500);
}
Serial.println("Server started at port 80.");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.print("URL=http://");
Serial.println(WiFi.localIP());
server.on("/", handleIndex); //use the top root path report last sensor value
server.on("/update",handleUpdate); // use this route to update sensor value
server.begin();
}
void loop(){
server.handleClient();
}
void handleIndex(){
Website = "<html><body onload ='process()'><div id='div1'>"+ String(sensor_value) +"</div></body></html>";
server.send(200," text/html",Website);
}
void handleUpdate(){
sensor_value = server.arg("value").toFloat();
Serial.println(sensor_value);
server.send(200,"text/plain","Updated");
}
I try to connect a client to the server so it could send data to the server, but a connection between the client and the server cannot be established and I don't know why. I check the IP address and it is all correct I just don't get why the client fails to connect to the server
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <HX711.h>
#include "Wire.h"
#define DOUT D5
#define CLK D6
HX711 scale;
const char* ssid = "WifiName";
const char* password = "Wifipassowrd";
float calibration_factor = 107095;
float val_Weight;
const char* host = "192.168.0.167"; // Server host IP.
const int port = 80;
WiFiClient client;
void setup() {
Serial.begin(115200); //set baud rate
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);//millisecond
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected & connect to client");
}
void loop() {
//connect to the server and send the data as URL parameter
if(client.connect(host, port)){
String url = "update?value=";
url+=String(25.0);
client.print(String("GET /") + url + "HTTP/1.1\r\n" + "Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
delay(10);
Serial.println("Response: ");
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
}
}else{
Serial.println("fail");
}
}
Any help would be great thanks!!!
Check the passwords, you have a typo.
const char* password = "Wifipassowrd";

HTTP get Request using ESP8266

Why I am unable to send get request. It always response 400.The URL are okay there is no problem in it. Actually I need to send data using get request. I have tried my best to find the solution but I didn't get any idea about it. Please anyone can help me with the code
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>//this header is used to send get request and see response
#include <WiFiClient.h>
const char* ssid = "myssid";
const char* password = "mypswd";
String host_url="https://api-test.technofield.net";
String url1="/api/data?token=TEST_TOKEN_123&data=";
int httpPort=80;
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, password); //Connect to my WiFi router
Serial.println("");
Serial.print("Connecting"); //initiall step just displaying connecting
// Wait for connection
while (WiFi.status() != WL_CONNECTED) { //the llop wiil execute till wifi is not connected
delay(500);
Serial.print(".");
}
//If connection successful show IP address in serial monitor
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);// connected to given ssid
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
}
void loop(){
if(WiFi.status()==WL_CONNECTED){ //we will perform action if wifi is connected
HTTPClient http; //intialize object of HTTPclient which is importent
String data="Sunil Kumar Yadav";
//String token="TEST_TOKEN_123";
url1=url1+data;
//full APi url is created you can manipulate those above data and token vaiable.
http.begin(host_url,httpPort,url1);//specify the request,begin the request
int httpCode=http.GET(); //Send the request
// if (httpCode>0){ //lets see the response from server
// String payload = http.getString();//store response on payload variable
// Serial.print("==============");//just for seperating the wifi connection status and server response
// Serial.println(payload);//print the response payload
// }
Serial.print(httpCode);
http.end();//if there is begin there will be end ,it will Close the connection
}
delay(500); //send the request in every 2sec, you can change it according to your need
//you can also specify the time so that it will be easy to identify on which time data is send
}
Following is the output:
301
==============<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx</center>
</body>
</html>
I dont know how to solve this.
There's one (of several) example how to do this with HTTPs here: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecure.h>
const char* ssid = "myssid";
const char* password = "mypswd";
String url = "https://api-test.technofield.net/api/data?token=TEST_TOKEN_123&data=";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
WiFiClientSecure client;
client.setInsecure();
HTTPClient https;
String data = "Sunil%20Kumar%20Yadav";
String fullUrl = url + data;
Serial.println("Requesting " + fullUrl);
if (https.begin(client, fullUrl)) {
int httpCode = https.GET();
Serial.println("============== Response code: " + String(httpCode));
if (httpCode > 0) {
Serial.println(https.getString());
}
https.end();
} else {
Serial.printf("[HTTPS] Unable to connect\n");
}
}
delay(5000);
}
import WiFiClientSecure.h
note how I set client.setInsecure(); which you shouldn't in your real code, rather us the root certificate of your end point as shown here https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/HTTPSRequest/HTTPSRequest.ino#L29
you should URL-encode the data parameter like so String data = "Sunil%20Kumar%20Yadav"

Arduino MKRGSM 1400 crashes when connecting to MQTT

I have a question concerning the Arduino MKRGSM 1400 and MQTT.
I use the code below to connect my MKRGSM to the internet via a SIM-card, then connect it to a HiveMQ-broker I have installed on Docker. Even though the code is compiled without any errors, once I upload it to my board, it crashes. Once it has crashed, I have to reset my board entirely. I've tried this code with the Arduino IDE and Platform.io on VS Code, both give the same result.
Before I put in the MQTT-connection, the board connected successfully to the internet and the DHT11-sensor was able to read humidity and temperature values without problems.
I'm not great with Arduino and this is the first time I'm trying to use MQTT myself.
Does anyone know why the code not only doesn't work, but also makes my board crash?
Thanks in advance!
//Includes
#include <PubSubClient.h>
#include <MKRGSM.h>
#include "DHT.h"
#include <Adafruit_Sensor.h>
//Var declaration
//SIM-internet connection
GSMClient net;
GPRS gprs;
GSM gsmAccess;
const char pin[] = "my pin";
const char apn[] = "my apn";
const char login[] = "my login";
const char password[] = "my password";
//MQTT connection
PubSubClient client;
const String serialNumber = "1";
const String mqtt_server = "server_ip";
const String topic = "/prototype/" + serialNumber;
//DHT sensor PIN declaration
#define DHTPIN 2 //DHT is pinned on 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void connect() {
//SIM not connected
bool connected = false;
Serial.print("Connecting to cellular network.");
//SIM connecting
while (!connected) {
if ((gsmAccess.begin(pin) == GSM_READY) &&
(gprs.attachGPRS(apn, login, password) == GPRS_READY)) {
//SIM connected
connected = true;
Serial.print("Connected to cellular network.");
}
else {
//If SIM doesn't connect
Serial.print(".");
delay(1000);
}
}
}
void setup() {
Serial.begin(9600);
//Connect to Docker MQTT
client.setServer(mqtt_server.c_str(), 8086);
client.connect(serialNumber.c_str());
Serial.print("MQTT connection state: ");
Serial.println(client.state());
//Start DHT 11
dht.begin();
}
void loop() {
delay(10000);
//Get DHT values
float humidty = dht.readHumidity();
float temperature = dht.readTemperature();
//Create JSON out of values and send it.
const String json = "{\"temperature\": " + String(temperature, 2) + ", \"humidity\": " + String(humidty) + " }";
Serial.println(json);
client.publish(topic.c_str(), json.c_str());
//Check if MQTT connection is holding.
Serial.print("MQTT connection state: ");
Serial.println(client.state());
//Reconnect if MQTT connection is lost.
if (!client.connected()) {
Serial.println("MQTT disconnected! Trying reconnect.");
client.connect("whatever");
}
}
As hashed out in the comments
You never called the connect() function so the GSM network was never setup.
You then probably need to use the GSMClient to initialise the PubSubClient so it knows how to access the network.

Set parameters of ESP8266 through Arduino

The problem is that I want to execute the code below, but when ESP8266 is shut down, then I start it again, everything is gone.
So, is there a solution that I can make this ESP8266 work the same controlled by my Arduino Uno.
My program blow is to control the GPIO2 through web browser.
Thanks a lot to all of you!!
My Codes:
#include <ESP8266WiFi.h>
#include <aREST.h>
// Create aREST instance
aREST rest = aREST();
// WiFi parameters
const char* ssid = "Protect Big Dragon 4";
const char* password = "18717772056";
// The port to listen for incoming TCP connections
#define LISTEN_PORT 80
// Create an instance of the server
WiFiServer server(LISTEN_PORT);
void setup(void)
{
// Start Serial
Serial.begin(115200);
// Give name and ID to device
rest.set_id("2");
rest.set_name("lamp_control");
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.println(WiFi.localIP());
}
void loop() {
// Handle REST calls
WiFiClient client = server.available();
if (!client) {
return;
}
while(!client.available()){
delay(1);
}
rest.handle(client);
}
So your ESP8266 loses your code when it is rebooted.
Sounds like the memory is faulty.
Try a different ESP8266 and let us know what occurs.

Not able to Receive subscribed Message with PubSubClient.h in Arduino Uno R3

#include "SPI.h"
#include “WiFiEsp.h”
#include <WiFiEspClient.h>
#include “SoftwareSerial.h”
#include <PubSubClient.h>
#include <WiFiEspUdp.h>
float temp=0;
int tempPin = 0;
int isClientConnected = 0;
char data[80];
char ssid[] = “SSID”; // your network SSID (name)
char pass[] = “PASSWORD”; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio’s status
char deviceName = “ArduinoClient1”;
IPAddress server(xxx,xxx,xxx,xxx); //MQTT server IP
IPAddress ip(192,168,43,200);
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print(“Message arrived [“);
Serial.print(topic);
Serial.print(“] “);
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println("-");
}
// Emulate Serial1 on pins 6/7 if not present
WiFiEspClient espClient;
PubSubClient client(espClient);
SoftwareSerial Serial1(6,7); // RX, TX
void setup(){
Serial.begin(9600);
Serial1.begin(9600);
WiFi.init(&Serial1);
WiFi.config(ip);
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while (true);
}
while ( status != WL_CONNECTED) {
Serial.print("Attemptingonnect to WPA SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
Serial.print("WiFius : ");
Serial.println(status);
}
//connect to MQTT server
client.setServer(server, 1883);
client.setCallback(callback);
isClientConnected = client.connect(deviceName);
Serial.println("+++++++");
Serial.print("isClientConnected;
Serial.println(isClientConnected);
Serial.print("client.state");
Serial.println(client.state());
if (isClientConnected) {
Serial.println("Connected…..");
client.publish("status","Welcome to ISG");
client.subscribe("isg/demoPublish/rpi/ardTempWarn");
//Not able to recieve for this subscribed topic on Arduino Uno Only if I
//print it returns 1
}
}
void loop() {
temp = (5.0 * analogRead(tempPin) * 100.0) / 1024;
Serial.print(" temp : " );
Serial.println(temp);
Serial.print("client.connected);
Serial.println(client.connected());
if (!client.connected()) {
reconnect();
}
client.publish("isg/demoPublish/ard1/tempLM35",String(temp).c_str());
// able to receive data at other
// clients like RPI,Web using Mosquitto broker
client.loop();
delay(5000);
}
void reconnect() {
Serial.println("Device is trying to connect to server ");
while (!client.connected()) {
if (client.connect(deviceName)) {
} else {
delay(5000);
}
}
}
I am using Arduino Uno R3 and ESP8266-01 as wifi connector.
I have to read temperature data and send to Mosquitto ,MongoDB and Raspberry Pi and receive a data on specific condition for that i have subscribed a topic in Arduino.
I am able to receive data from Arduino to all other clients but I am not able to receive data on Subscribed topic in Arduino. But all other deviced like MongoDB able to receive data from Raspberry Pi.
I have used Arduino Uno R3, ESP8266-01 devices and liberary for to connect and send/receive data WiFiEsp.h, WiFiEspClient.h, WiFiEspUdp.h, SoftwareSerial.h, PubSubClient.h
client.subscribe("topic"); returns 1
Also callback function implemented but not able to get call.
So can any one help me why I am not getting subscribed topic message in Arduino?
I have follow https://sonyarouje.com/2016/03/15/mqtt-communication-with-arduino-using-esp8266-esp-01/#comment-111773
The library that you are using has bug in callback hence it would be better that you use other library my preference would be
https://github.com/vshymanskyy/TinyGSM
this library include almost all variants of SIM800(A,C,L,H,808), variants of SIM900(A,D,908,968), ESP8266 (mounted on arduino), Ethernet shield etc. It worked for me, as same issue bugged me for almost 1-2 weeks but latter was able to receive all subscribed message irrespective of mode of communication(GSM,Ethernet,WiFi)

Resources