esp8266 based project using xampp - xampp

I've tried uploading the below code into NodeMCU for sending data into MySQL using Xampp Webserver. I want to send values from sensors to the MySQL database through ESP8266. This is the code I have tried
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#define sensorPin1 analogRead(A0)
WiFiServer server(301);
const char *ssid = "internet";
const char *pass = "abcdefghi";
const char* host = "x.x.x.x";
byte mac[6];
WiFiClient client;
MySQL_Connection conn((Client *)&client);
char INSERT_SQL[] = "INSERT INTO test.tester(id,sensor) VALUES ('', %d)";
char query[128];
IPAddress server_addr(x,x,x,x); // MySQL server IP
char user[] = "root"; // MySQL user
char password[] = ""; // MySQL password
void setup() {
Serial.begin(9600);
delay(10);
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
WiFi.macAddress(mac);
Serial.print("MAC: ");
Serial.print(mac[5],HEX);
Serial.print(":");
Serial.print(mac[4],HEX);
Serial.print(":");
Serial.print(mac[3],HEX);
Serial.print(":");
Serial.print(mac[2],HEX);
Serial.print(":");
Serial.print(mac[1],HEX);
Serial.print(":");
Serial.println(mac[0],HEX);
Serial.println("");
Serial.print("Assigned IP: ");
Serial.print(WiFi.localIP());
Serial.println("");
Serial.println("Connecting to database");
while (conn.connect(server_addr, 3306, user, password) != true) {
delay(5);
Serial.print ( "." );
}
Serial.println("");
Serial.println("Connected to SQL Server!");
}
void loop() {
int sensor = sensorPin1;
delay(10000); //10 sec
sprintf(query, INSERT_SQL, sensor);
Serial.println("Data Recorded.");
Serial.println(query);
MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
cur_mem->execute(query);
delete cur_mem;
}
But when I execute this program, the chip is getting connected to WiFi but is is not getting connected to the database.
Any solutions please!?

Related

Posting data from esp8266 to a webapi

I want to send data from my esp8266 to a webapi but it fails.
I tried this code to send my data like sensor status but it fails and returns error 400. I searched a lot about this problem and I tried so many things but it didn't work.
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
const char *ssid = "VRU";
const char *password = "";
const char *host = "192.168.174.71";
WiFiClient wifiClient;
void setup() {
delay(1000);
Serial.begin(115200);
WiFi.mode(WIFI_OFF);
delay(1000);
WiFi.mode(WIFI_STA);
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() {
HTTPClient http;
http.begin(wifiClient,"http://192.168.174.71:100/api/StatusReport/AddStatus");
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST("{\"status\":\"1\"}");
String payload = http.getString();
Serial.println(httpCode);
Serial.println(payload);
http.end();
delay(5000);
}
Here is my code. It connects to the wifi without any problem and when it wants to post the data it returns an error.
400
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-862f434a8be85865c871ea45b89544d1-cea4232cafaa5cc1-00","errors":{"status":["The status field is required."]}}
And it's the error.
The api receives the data when I do it by myself but the esp can't send the data.
What should I do to prevent this error from happening. Is it from the api that can't receive data or from the esp?

ESP8266 not connecting to websocket server

I have created and deployed a websocket to the heroku. I am able to use the websocket on postman but I can't connect it with my node mcu. I could connect the node mcu to the wifi but not with the websocket.
I am not sure about the port number which should be used for begin() method for websocketsclient object.
Below is my code to connect with my websocket:
#include "ESP8266WiFi.h"
#include "WebSocketsClient.h"
// WiFi parameters to be configured
const char* ssid = "<wifi_ssid>"; // Write here your router's username
const char* password = "<password>"; // Write here your router's passward
int LED_STATUS = 0;
const char* host = "<project_name>.herokuapp.com";
const uint16_t port = 3000;
const char* url = "/";
WebSocketsClient webSocketsClient = WebSocketsClient();
void handleMessage(char * message){
Serial.println("message...");
Serial.println(message);
}
void webSocketCallback(WStype_t type, uint8_t * payload, size_t length){
toggleLED();
switch(type){
case WStype_DISCONNECTED:
offLED();
break;
case WStype_TEXT:
onLED();
handleMessage((char*) payload);
break;
case WStype_CONNECTED:
default:
onLED();
break;
}
}
void toggleLED(){
LED_STATUS = (LED_STATUS + 1)%2;
digitalWrite(LED_BUILTIN, LED_STATUS);
}
void offLED(){
LED_STATUS = 1;
digitalWrite(LED_BUILTIN, LED_STATUS);
}
void onLED(){
LED_STATUS = 0;
digitalWrite(LED_BUILTIN, LED_STATUS);
}
void setup(void)
{
Serial.begin(9600);
// Connect to WiFi
WiFi.begin(ssid, password);
//setting the led pin
pinMode(LED_BUILTIN, OUTPUT);
// while wifi not connected yet, print '.'
// then after it connected, get out of the loop
while (WiFi.status() != WL_CONNECTED) {
toggleLED();
delay(500);
Serial.print(".");
}
//WiFi connected, IP address
Serial.println("");
Serial.println("WiFi connected");
Serial.println(WiFi.localIP());
offLED();
//websocket connection
webSocketsClient.begin(host, port, url);
webSocketsClient.onEvent(webSocketCallback);
webSocketsClient.setReconnectInterval(5000);
}
void loop() {
// Nothing
webSocketsClient.loop();
}
Solutions(few mistakes in the code):
Since my websocket supports secured connection : wss, so instead of begin() need to use beginSSL()
since wss is used, port number for secured connections is 443

Why have I connection failed when I try to connect to my localhost?

I have an esp32 with one sensor(BMP280) connected and one database where I want to storage three parameters: temperature, atmospheric pressure and altitude. The database is on localhost with 8080 port. I cannot to connect at my localhost and I have connection failed. I have tried to put at host the ip address 0.0.0.0 or localhost:8080 and it doesn't work. What is the problem?
I attach my code below:
#include <BMP280_DEV.h>
#include <WiFi.h>
float temperature, pressure, altitude;
BMP280_DEV bmp280;
const char * ssid = "*******";
const char * password = "*********";
const char * host = "127.0.0.1";
const int port = 8080;
const int watchdog = 5000;
unsigned long previousMillis = millis();
void init_wifi() {
//We start by connecting to a Wi-Fi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void setup() {
Serial.begin(115200);
bmp280.begin(BMP280_I2C_ALT_ADDR);
//bmp280.setPresOversampling(OVERSAMPLING_X4);
//bmp280.setTempOversampling(OVERSAMPLING_X1);
//bmp280.setIIRFilter(IIR_FILTER_4);
bmp280.setTimeStandby(TIME_STANDBY_2000MS);
bmp280.startNormalConversion();
init_wifi();
}
void loop() {
if (bmp280.getMeasurements(temperature, pressure, altitude)) {
Serial.print(temperature);
Serial.print(F("*C "));
Serial.print(pressure);
Serial.print(F("hPa "));
Serial.print(altitude);
Serial.println(F("m"));
delay(20000);
}
unsigned long currentMillis = millis();
if (currentMillis - previousMillis > watchdog) {
previousMillis = currentMillis;
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("Connection Failed");
return;
}
String url = "/test_bmp280/index.php?temp=";
url += temperature;
url += "&pres=";
url += pressure;
url += "&alt=";
url += altitude;
client.print(String("GET ") + url + "HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>>Client Timeout !");
client.stop();
return;
}
}
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
}
}

esp8266 NodeMCU client cant connect to esp8266 NodeMCU server with static ip

Hello...
My code is working perfect with using dynamic IP's, the LED is connected to server and a push button is connected to client, it work perfect with dynamic IP's addresses of both devices. But when i make static IP addresses, the client can not connect to server, and it always says connection failed.
Client code is:
#include <ESP8266WiFi.h>
//IPAddress staticIP612_61(192,168,100,59);
//IPAddress gateway612_61(192,168,100,1);
//IPAddress subnet612_61(255,255,255,0);
const char* ssid = "GravixarATD"; // Your wifi Name
const char* password = "TheRedMonster79"; // Your wifi Password
const char * host = "192.168.100.23"; // IP Server
const int httpPort = 80;
const char* Commands; // The command variable that is sent to the server
int button = 5; // push button is connected
bool btn_press = true; // The variable to detect the button has been pressed
int con = 0; // Variables for mode
void setup() {
// put your setup code here, to run once:
pinMode(button, INPUT_PULLUP); // initialize the pushbutton pin as an input:
Serial.begin(115200); // initialize serial:
Serial.println("");
Serial.println("Client-------------------------------");
Serial.print("Connecting to Network");
WiFi.mode(WIFI_STA); // Mode Station
WiFi.begin(ssid, password); // Matching the SSID and Password
delay(1000);
// Waiting to connect to wifi
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("Successfully Connecting");
Serial.println("Status : Connected");
//WiFi.config(staticIP612_61, gateway612_61, subnet612_61);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("-------------------------------------");
Serial.println("");
}
void loop() {
// put your main code here, to run repeatedly:
if (digitalRead(button) == LOW) {
Serial.println("Client-------------------------------");
Serial.print("Send Command = ");
if (btn_press == true){
if (con >= 2) {
con=0;
}
con++;
switch (con){
case 1:
Commands="LED_On";
Serial.println(Commands);
send_commands();
break;
case 2:
Commands="LED_Off";
Serial.println(Commands);
send_commands();
break;
}
btn_press = false;
}
}
else {
btn_press = true;
}
delay(100);
}
void send_commands(){
Serial.println("Sending command...");
Serial.println("Don't press the button for now...");
Serial.println("");
Serial.print("Connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, httpPort)) {
Serial.println("Connection failed");
return;
}
// We now create a URI for the request
Serial.print("Requesting URL : ");
Serial.println(Commands);
// This will send the request to the server
client.print(String("GET ") + Commands + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: Close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
Serial.print("Server Reply = ");
// Read all the lines of the reply from server and print them to Serial
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println("Now you can press the button ...");
Serial.println("-------------------------------------");
Serial.println("");
}
Server code is:
#include <ESP8266WiFi.h>
//IPAddress staticIP612_60(192,168,100,60);
//IPAddress gateway612_60(192,168,100,1);
//IPAddress subnet612_60(255,255,255,0);
int led = 5; // the pin the LED is connected to
const char* ssid = "GravixarATD"; // Your wifi Name
const char* password = "TheRedMonster79"; // Your wifi Password
const char* Commands_Reply; // The command variable that is sent to the client
const char * host = "192.168.100.21"; // IP Client
WiFiServer server(80);
void setup() {
// put your setup code here, to run once:
pinMode(led, OUTPUT); // Declare the LED as an output
Serial.begin(115200); // initialize serial:
delay(10);
Serial.println("");
Serial.println("Server-------------------------------");
Serial.print("Configuring access point");
WiFi.begin(ssid, password);
// Waiting to connect to wifi
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// WiFi.config(staticIP612_60, gateway612_60, subnet612_60);
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
Serial.println("-------------------------------------");
Serial.println("");
}
void loop() {
// put your main code here, to run repeatedly:
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("Server-------------------------------");
Serial.println("New client");
Serial.print("From client = ");
while(!client.available()){
delay(1);
}
// Read the first line of the request -------------------------------------
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
//Command LED -------------------------------------------------------------
if (req.indexOf("LED_On") != -1){
Commands_Reply = "LED Status : On";
Serial.print("Server send = ");
Serial.println(Commands_Reply);
client.print(String("GET ") + Commands_Reply + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
digitalWrite(led, HIGH);
}
else if (req.indexOf("LED_Off") != -1){
Commands_Reply = "LED Status : Off";
Serial.print("Server send = ");
Serial.println(Commands_Reply);
client.print(String("GET ") + Commands_Reply + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
digitalWrite(led, LOW);
}
else {
Serial.println("invalid request");
client.stop();
return;
}
client.flush();
Serial.println("Client disonnected");
Serial.println("-------------------------------------");
Serial.println("");
}
NOTE I have commented all the static IP lines, when i comment them and using dynamic ips, client connect to server perfectly and when i use static ips instead of dynamic ips client fails to connect with server. any help will be appreciated.

nodeMCU connect refused with XMAPP localhost

My project is about using nodeMCU measure value from sensor DHT11 and sent value to database Mysql. I use xampp for server. I cannot sent value to database.
nodeMCU can read value and sent value.But HTTP GET is fail.And return connect refused. I think maybe have problems with port for listening.
this is my code
#include <Arduino.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include "DHT.h"
#define DHTPIN 2 // what digital pin the DHT22 is conected to
#define DHTTYPE DHT11 // there are multiple kinds of DHT sensors
DHT dht(DHTPIN, DHTTYPE);
ESP8266WiFiMulti WiFiMulti;
const char* ssid = "something";
const char* password = "something";
int EP =5;
void setup() {
Serial.begin(115200);
pinMode(EP, INPUT);
for (uint8_t t = 4; t > 0; t--) {
Serial.printf("[SETUP] WAIT %d...\n", t);
Serial.flush();
delay(1000);
}
WiFiMulti.addAP(ssid, password); // ssid , password
randomSeed(50);
}
int timeSinceLastRead = 0;
void loop() {
if ((WiFiMulti.run() == WL_CONNECTED)) {
HTTPClient http;
float temp = dht.readTemperature();
float humi = dht.readHumidity();
long meas =TP_init();
Serial.println(WiFi.localIP());
//int temp = random(25,35);
String url = "localhost:8012/add2.php?temp="+String(temp)+"&humi="+String(humi)+"&meas=0";
Serial.println(url);
http.begin(url); //HTTP
int httpCode = http.GET();
if (httpCode > 0) {
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
delay(3000);
}
long TP_init(){
delay(10);
long meas=pulseIn (EP, HIGH); //wait for the pin to get HIGH and returns measurement
return meas;
}
I changed Apache port from 80 to 8012
I use PHPMyadmin for store database . File php's name add2.php for insert value from sensor DHT11
enter image description here
This is result from serial port.
String url = "localhost should be replaced with String url = "<IP-address-of-your-webserver> as the webserver clearly isn't running on the ESP8266.

Resources