DHT22 (sensor) to Pachube via Arduino with Ethernet shield error - networking

I'm trying to connect a DHT22 sensor to the Pachube online service.
I am understanding the code and have everything wired up correctly but I get this error:
DHT22 Library Demo
Requesting data at 6335
Sync Timeout
What does sync timeout mean? Is is a network problem?
How could I fix this?
Here is my code anyway:
/* Feed temperature and humidity to Pachube.
Based on the following examples:
Sample code from nethoncho's DHT22 library:
https://github.com/nethoncho/Arduino-DHT22
Tom Igoe's PachubeClient:
http://arduino.cc/en/Tutorial/PachubeCient
*/
#include <DHT22.h>
#include <SPI.h>
#include <Ethernet.h>
// Data wire is plugged into port 7 on the Arduino
// Connect a 4.7K resistor between VCC and the data pin (strong pullup)
#define DHT22_PIN 2
// Setup a DHT22 instance
DHT22 myDHT22(DHT22_PIN);
static unsigned long lWaitMillis;
// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
// assign an IP address for the controller:
byte ip[] = {
192,168,0,30 };
byte gateway[] = {
192,168,1,2};
byte subnet[] = {
255, 255, 255, 0 };
// The address of the server you want to connect to (pachube.com):
byte server[] = {
173,203,98,29 };
// initialize the library instance:
Client client(server, 80);
boolean lastConnected = false; // state of the connection last time through the main loop
const long postingInterval = 180000; //delay between updates to Pachube.com
int backoff = 0;
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("DHT22 Library Demo");
// start the ethernet connection:
Ethernet.begin(mac, ip);
// give the ethernet module time to boot up:
delay(1000);
lWaitMillis = millis() + 5000;
}
void loop() {
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
while(client.status() != 0) {
Serial.print("Client status: ");
Serial.println(client.status());
delay(5);
}
}
// if you're not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected() && (long)( millis() - lWaitMillis ) >= 0 ) {
if (readData()) {
int temp = myDHT22.getTemperatureC();
int humidity = myDHT22.getHumidity() + .5;
sendData(temp, humidity);
}
lWaitMillis += postingInterval;
if (lWaitMillis < millis()) {
lWaitMillis = millis() + postingInterval;
}
Serial.print("Next attempt at ");
Serial.println(lWaitMillis);
Serial.println();
}
// store the state of the connection for next time through
// the loop:
lastConnected = client.connected();
}
boolean readData()
{
DHT22_ERROR_t errorCode;
Serial.print("Requesting data at ");
Serial.println(millis());
errorCode = myDHT22.readData();
switch(errorCode)
{
case DHT_ERROR_NONE:
Serial.print("Got Data ");
Serial.print(myDHT22.getTemperatureC());
Serial.print("C ");
Serial.print(myDHT22.getHumidity());
Serial.println("%");
return true;
break;
case DHT_ERROR_CHECKSUM:
Serial.print("check sum error ");
Serial.print(myDHT22.getTemperatureC());
Serial.print("C ");
Serial.print(myDHT22.getHumidity());
Serial.println("%");
break;
case DHT_BUS_HUNG:
Serial.println("BUS Hung ");
break;
case DHT_ERROR_NOT_PRESENT:
Serial.println("Not Present ");
break;
case DHT_ERROR_ACK_TOO_LONG:
Serial.println("ACK time out ");
break;
case DHT_ERROR_SYNC_TIMEOUT:
Serial.println("Sync Timeout ");
break;
case DHT_ERROR_DATA_TIMEOUT:
Serial.println("Data Timeout ");
break;
case DHT_ERROR_TOOQUICK:
Serial.println("Polled too quick ");
break;
}
return false;
}
// this method makes a HTTP connection to the server:
void sendData(int temp, int humidity) {
// if there's a successful connection:
if (client.connect()) {
backoff = 0;
Serial.println("connecting...");
// send the HTTP PUT request.
// fill in your feed address here:
client.print("PUT /v2/feeds/36800.csv HTTP/1.1\n");
client.print("Host: api.pachube.com\n");
// fill in your Pachube API key here:
client.print("X-PachubeApiKey: a6714b6a217827edadfd003843c03c259a08add554eda3871b844612eddc6819\n");
client.print("Content-Length: ");
// calculate the length of the sensor reading in bytes:
int thisLength = 2 + getLength(temp) + 2 + 2 + getLength(humidity);
client.println(thisLength, DEC);
// last pieces of the HTTP PUT request:
client.print("Content-Type: text/csv\n");
client.println("Connection: close\n");
// here's the actual content of the PUT request:
client.print(0, DEC);
client.print(",");
client.println(temp, DEC);
client.print(1, DEC);
client.print(",");
client.println(humidity, DEC);
}
else {
// if you couldn't make a connection:
Serial.println("connection failed, resetting.");
Ethernet.begin(mac, ip);
delay(1000);
client.stop();
delay(1000);
}
}
// This method calculates the number of digits in the
// sensor reading. Since each digit of the ASCII decimal
// representation is a byte, the number of digits equals
// the number of bytes:
int getLength(int someValue) {
// there's at least one byte:
int digits = 1;
// continually divide the value by ten,
// adding one to the digit count for each
// time you divide, until you're at 0:
int dividend = someValue /10;
while (dividend > 0) {
dividend = dividend /10;
digits++;
}
// return the number of digits:
return digits;
}

You're running into DHT_ERROR_SYNC_TIMEOUT sensor error, that means that the DHT sensor is running into some sync problem, I guess.
What arduino are you using? Is your board's frequence 8 or 16Mhz?
Give a try to the edit described here, too. If it still doesn't work, I would try using sensor itself (i.e. without connecting to patchube) with some test sketch you can easily find for DHT22, just to make sure the sensor is working properly.

I had similar problem when using Arduino Nano v3.0 + ENC28J60 Ethernet shield. I tried to connect RF receiver to digital PIN #2 but this never worked.
Then I used different pin for the RF module (PIN #4 in my case) and everything worked fine.

Related

can't recieve a msg on node red published from arduino using mqtt protocol

i have a problem in my arduino code, i'm using esp8266 to get data from a sensor, and i have to send this data to node red dashboard using mqtt protocol. The problem is that i couldn't publish a "string".
this is my code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#define Potentiometer A0
char ssid[] = "Fixbox-71CD43"; // your network SSID (name)
char pass[] = "ZTA0NWY2"; // your network password (use for WPA, or use as key for WEP)
//int keyIndex = 0; // your network key Index number (needed only for WEP)
const char* mqtt_server = "192.168.0.4";
int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the static IP instead of the name for the server:
// IPAddress server(74,125,232,128); // static IP for Google (no DNS)
//char server[] = "www.google.com"; // name address for Google (using DNS)
WiFiClient espclient;
PubSubClient client(espclient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
//char msg[MSG_BUFFER_SIZE];
//char message[50];
int sensorValue;
float VWC, Threshold1, Threshold2 , SubCalSlope, SubCalIntercept;
void setup() {
//*********************//*********************
// Declare variables for four 10HS sensors
//*********************//*********************
//*********************//*********************
unsigned long lastMsg = 0;
//*********************//*********************
//*********************//*********************
// SUBSTRATE CALIBRATION: You have to convert the voltage to VWC using soil or substrate specific calibration. Decagon has generic calibrations (check the 10HS manual at http://manuals.decagon.com/Manuals/13508_10HS_Web.pdf) or you can determine your own calibration. We used our own calibration for Fafard 1P (peat: perlite, Conrad Fafard, Inc., Agawam, MA)
SubCalSlope = 1.1785;
SubCalIntercept = -0.4938;
// IRRIGATION THRESHOLDS: Values used to trigger irrigation when the sensor readings are below a specific VWC (in units of m3/m3 or L/L)
Threshold1 = 0.4;
Threshold2 = 0.6;
//*********************//*********************
Serial.begin(115200);
// Configure digital pins D2 and D3 as outputs to apply voltage to all four sensors (D2: sensor 1 and 2; D3, sensor 3 and 4)
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
// client.setCallback(callback);
// initialize serial communication:
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// initialize the WiFi module:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi module not detected");
// don't continue:
while (true);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to WiFi network ");
Serial.println(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);
}
Serial.println("Connected.\nWiFi network status:");
printWifiStatus();
Serial.println("\nStarting connection to MQTT server...");
client.setServer(mqtt_server, 1883);
// if you get a connection, report back via serial:
}
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 (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("GW_sensor/humidity", "hello world");
client.publish("GW_sensor/salinity", "hello world");
// ... and resubscribe
client.subscribe("GW_sensor/#");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi device's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
char msg[10];
char msgtext[25];
String themsg;
// if there are incoming bytes available
// from the server, read them and print them:
// if the server's disconnected, stop the client:
if (!client.connected()) {
reconnect();
}
client.loop();
//*********************
// Apply power to 10HS sensor
// Wait 10 ms,
delay(10);
// Measure the analog output from sensor #1 and #2 (red wires connected to analog pins A0 and A1)
sensorValue = analogRead(0);
// And turn the power to the sensors off
digitalWrite(2, LOW);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 1.1V) that is used to calculate the VWC using a calibration equation
VWC = sensorValue * (1.1/1023.0) * SubCalSlope + SubCalIntercept;
//*********************//*********************
// Print the VWC
Serial.print("VWC (m3/m3): ");
Serial.print(" = ");
Serial.print(VWC);
//*********************//*********************
unsigned long now = millis();
//send data every 6 second
if (now - lastMsg > 500) {
lastMsg = now;
// Check to see if the VWC reading is below Threshold1
if (VWC < Threshold1) {
// If so, write an error message to the screen
Serial.print("WARNING:(too low) Irrigation needed. ");
sprintf(msgtext,"Irrigation needed",VWC);
}
// If the measured VWC is > Threshold2
if (VWC > Threshold2) {
// Write an error message to the screen
Serial.print("WARNING:(too high) Irrigation not needed. ");
sprintf(msgtext,"Irrigation not needed",VWC);
}
sprintf(msg,"%i",VWC);
//publish sensor data to MQTT broker
client.publish("GW_sensor/VWC_msg", msgtext);
client.publish("GW_sensor/VWC_val", msg);
}
please can you help me to fix my code? it can only send the values to the broker and the msg.
thank you all!
Payload isn't a "String", its a char buffer.
You need something like this:
snprintf (msg, BUF_SIZE, "msg: %i", VWC)
client.publish("GW_sensor/VWC_msg", msg)
The PubSubClient repo even has an ESP8266 example: https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_esp8266/mqtt_esp8266.ino

BME680 gas sensor's value keeps increasing

I've been trying to get the BME680 to work and for the most part it seems to be working great. I do have one issue and that is with the gas sensor.
I write all the contents of the BME680 out to a webpage and all of the other values remain consistent.
Temperature: 77.29 *F
Humidity: 59.12 %
Pressure: 1010.45 millibars
Air Quality: 3.24 KOhms
On every refresh of the page the values for Temperature, Humidity, and Pressure all remain close to their values. They correct for a little while and show the minor fluctuations correctly. When it starts to rain the pressure goes down, the humidity goes up, etc... The issue is the Gas Sensor. On ever refresh the value keeps increasing. Regardless of whether I refresh it once per minute or per hour it keeps increasing. I'm clearly doing something wrong.
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_BME680.h"
#include <WiFi101.h>
#include <WiFiUdp.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID; // your network SSID (name)
char pass[] = SECRET_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(80);
#define SEALEVELPRESSURE_HPA (1023.03)
Adafruit_BME680 bme; // I2C
void setup() {
//Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT); // set the LED pin mode
bme.begin();
// Set up oversampling and filter initialization
bme.setTemperatureOversampling(BME680_OS_8X);
bme.setHumidityOversampling(BME680_OS_2X);
bme.setPressureOversampling(BME680_OS_4X);
bme.setIIRFilterSize(BME680_FILTER_SIZE_3);
bme.setGasHeater(320, 150); // 320*C for 150 ms
// 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) {
// 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
}
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();
if (! bme.performReading()) {
client.print("Failed to perform reading :(<br>");
return;
}
// the current weather condidtions
client.print("Temperature: ");
client.print((bme.temperature * 9/5) + 32);
client.print(" *F<br>");
client.print("Humidity: ");
client.print(bme.humidity);
client.print(" %<br>");
client.print("Pressure: ");
client.print(bme.pressure / 100.0);
client.print(" millibars<br>");
client.print("Air Quality: ");
client.print(bme.gas_resistance / 1000.0);
client.print(" KOhms<br>");
delay(2000);
// 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
}
}
}
// close the connection:
client.stop();
//Serial.println("client disonnected");
}
}
I see two important points. Two for the beginning. Missing the ambient temperature and the sea-level.
Default ambient is: 25deg.C
Default sea-level is: 500 meter
Add this with correct values to your code. Then you have todo some automatic calibrations after burn in time. My own experience is that 2 weeks 24/7 is needed to get the sensor much old as needed. Next step look in the BOSCH original library and example code. Then start over again. Currently i'm rewriting the driver for the BME and BMP series for Tasmota (github). Lot's of work believe me. And i'm from the physics and chemical side. So some research helps always.

Arduino can't show out respond get from mqtt server through esp8266

I'm trying to let my Arduino and esp8266 send data to thingsboard and then subscribe to thingsboard's mqtt channel and get a timestamp from it but for some unknown reason, it just doesn't work. Checked server-side and it was ok, tried postman to simulate request and also getting the correct response from the server.
Also, I had read the documentation about esp8266 and it somehow did state that it only can have 1 connection simultaneously. But tried to let my Arduino to only subscribe to channel but it still doesn't work.
My code:(I'm using Arduino Mega for this)
#include "DHT.h"
#include <WiFiEspClient.h>
#include <WiFiEsp.h>
#include <WiFiEspUdp.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <TimeLib.h>
#define WIFI_AP "CEC"
#define WIFI_PASSWORD "#CEC#2017#CEC#"
#define TOKEN "A1_TEST_TOKEN"
// DHT
#define DHTPIN 2
#define DHTTYPE DHT22
char thingsboardServer[] = "192.168.0.250";
// Initialize the Ethernet client object
WiFiEspClient espClient;
// Initialize DHT sensor.
DHT dht(DHTPIN, DHTTYPE);
PubSubClient client(espClient);
int status = WL_IDLE_STATUS;
unsigned long lastSend;
unsigned long lastSync;
void setup() {
// initialize serial for debugging
Serial.begin(9600);
Serial1.begin(9600);
Serial2.begin(9600);
//serial pin
pinMode(LED_RUN_pin, OUTPUT);
//dht.begin();
InitWiFi();
lastSend = 0;
lastSync = 0;
//client subscribe thingsboard rpc PUBLISH msg
client.setServer( thingsboardServer, 1883 );
client.setCallback(on_message);
}
void loop() {
status = WiFi.status();
if ( status != WL_CONNECTED) {
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(WIFI_AP);
// Connect to WPA/WPA2 network
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
delay(500);
}
}
if ( !client.connected() ) {
reconnect();
}
if ( millis() - lastSend > 30000 ) { // Update and send after 30 seconds
getAndSendTemperatureAndHumidityData();
lastSend = millis();
}
client.loop();
}
void getAndSendTemperatureAndHumidityData()
{
Serial.println("Collecting temperature data.");
// Reading temperature or humidity takes about 250 milliseconds!
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
String temperature = String(t);
String humidity = String(h);
// Prepare a JSON payload string
String payload = "{";
payload += "\"temperature\":"; payload += temperature; payload += ",";
payload += "\"humidity\":"; payload += humidity;
payload += "}";
// Send payload
char attributes[100];
payload.toCharArray( attributes, 100 );
client.publish( "v1/devices/me/rpc/request/1", attributes , 1);
//Serial.println( attributes );
}
// Prepare a JSON payload string
String payload = "{method: getTime, params:{}}";
// Send payload
char attributes[100];
payload.toCharArray( attributes, 100 );
client.publish( "v1/A1_TEST_TOKEN/rpc", attributes );
//Serial.println( attributes );
}
void InitWiFi()
{
// initialize serial for ESP module
Serial1.begin(9600);
// initialize ESP module
WiFi.init(&Serial1);
// check for the presence of the shield
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue
while (false);
}
Serial.println("Connecting to AP ...");
// attempt to connect to WiFi network
while ( status != WL_CONNECTED) {
// Connect to WPA/WPA2 network
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
delay(500);
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
//Serial.print("Connecting to Thingsboard node ...");
// Attempt to connect (clientId, username, password)
if ( client.connect("Arduino Uno Device", TOKEN, NULL) ) {
Serial.println( "[DONE]" );
delay(500);
// Serial.println("Subscribing RPC");
client.subscribe("v1/devices/me/rpc/request/+");
} else {
Serial.print( "[FAILED] [ rc = " );
Serial.print( client.state() );
Serial.println( " : retrying in 20 seconds]" );
// Wait 20 seconds before retrying
delay( 20000 );
}
}
}
void printDigits(int digits){
// utility function for digital clock display: prints preceding colon and leading 0
Serial.print(":");
if(digits < 10)
Serial.print('0');
Serial.print(digits);
}
// The callback for when a PUBLISH message is received from the server.
void on_message (char* topic, byte* payload, unsigned int length) {
//Serial.println("On message");
char json[length + 1];
strncpy (json, (char*)payload, length);
json[length] = '\23';
Serial.print("Topic: ");
Serial.println(topic);
Serial.print("Message: ");
Serial.println(json);
// Decode JSON request
StaticJsonBuffer<200> jsonBuffer;
JsonObject& data = jsonBuffer.parseObject((char*)json);
if (!data.success())
{
Serial.println("parseObject() failed");
return;
}
}
Probably a stupid remark, but is your TOKEN a valid Thingsboard device token? I assume you entered the value A1_TEST_TOKEN to hide your real authentication token.
I also assume you are trying to send sensor data (telemetry) to Thingsboard. Why did you decide to use the RPC API for sending data? I think it might be easier to use the MQTT Device API instead.
I don't have any experience in developing for Arduino. I am using Thingsboard together with a Raspberry PI to write and display sensor data. Hope you find a solution for your problem!

RC522 with ESP8266 not working Arduino uno

I have written below code for Arduino Uno to scan an RFID card using a RC522 module and an ESP8266 module to connect to my router.
Now when I scan any card it should read the card number and send a request to my server's IP address and get the response.
But after successfully reading the RFID card, the connection to the server via TCP does not work:
esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.
So I am not able to send a request to my server.
But when I remove the RC522 code (for testing) it is working!
What is the problem using the RC522 and the ESP8266 together?
#include <SPI.h>
#include <MFRC522.h>
#include "SoftwareSerial.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
//I2C pins declaration
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
#define SS_PIN 9
#define RST_PIN 7
#define mainLock 2
String ssid = "MYSSID";
String password = "PASSWORD";
SoftwareSerial esp(2, 3);// RX, TX
String server = "192.168.1.102"; //Your Host
String uri = "/get_data.php?rfid_key=";
//#define LED_G 4 //define green LED pin
//#define LED_R 5 //define red LED
#define BUZZER 6 //buzzer pin
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
String rfidUid = "";
#define DEBUG true
void setup()
{
// Serial.begin(9600); // Initiate a serial communication
esp.begin(9600);
Serial.begin(9600);
SPI.begin(); // Initiate SPI bus
mfrc522.PCD_Init(); // Initiate MFRC522
connectWifi();
httpget();
delay(1000);
Serial.println("Put your card to the reader...");
Serial.println();
pinMode(mainLock, OUTPUT);
lcd.begin(16, 2); //Defining 16 columns and 2 rows of lcd display
lcd.backlight();//To Power ON the back light
}
void connectWifi() {
sendData("AT+RST\r\n", 2000, DEBUG); //This command will reset module to default
sendData("AT+CWMODE=3\r\n", 1000, DEBUG);
String cmd = "AT+CWJAP=\"" + ssid + "\",\"" + password + "\"";
esp.println(cmd);
delay(4000);
if (esp.find("OK")) {
Serial.println("Connected!");
}
else {
Serial.println("Cannot connect to wifi ! Connecting again...");
connectWifi();
}
}
/////////////////////////////GET METHOD///////////////////////////////
void httpget() {
// // Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
{
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
{
return;
}
//Show UID on serial monitor
Serial.print("UID tag :");
String content = "";
byte letter;
rfidUid = "";
for (byte i = 0; i < mfrc522.uid.size; i++)
{
Serial.print(mfrc522.uid.uidByte < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte, HEX);
content.concat(String(mfrc522.uid.uidByte < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte, HEX));
rfidUid += String(mfrc522.uid.uidByte < 0x10 ? "0" : "");
rfidUid += String(mfrc522.uid.uidByte, HEX);
}
Serial.println();
content.toUpperCase();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(rfidUid);
esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.
if ( esp.find("OK")) {
Serial.println("TCP connection ready");
} delay(1000);
if ( esp.find("OK")) {
Serial.println("TCP connection ready");
} delay(1000);
String getRequest =
"GET " + uri + rfidUid + " HTTP/1.0\r\n" +
"Host: " + server + "\r\n" +
"Accept: *" + "/" + "*\r\n" +
"Content-Type: text/plain\r\n" +
"\r\n";
String sendCmd = "AT+CIPSEND=";
esp.print(sendCmd);
esp.println(getRequest.length());
delay(500);
if (esp.find(">")) {
Serial.println("Sending..");
esp.print(getRequest);
if (esp.find("SEND OK")) {
Serial.println("Packet sent");
while (esp.available()) {
String response = esp.readString();
Serial.println("response.." + response);
}
esp.println("AT+CIPCLOSE");
}
}
}
void loop()
{
httpget();
}
String sendData(String command, const int timeout, boolean debug) // Function to send the data to the esp8266
{
String response = "";
esp.print(command); // Send the command to the ESP8266
long int time = millis();
while ( (time + timeout) > millis()) // ESP8266 will wait for some time for the data to receive
{
while (esp.available()) // Checking whether ESP8266 has received the data or not
{
char c = esp.read(); // Read the next character.
response += c; // Storing the response from the ESP8266
}
}
if (debug)
{
Serial.print(response); // Printing the response of the ESP8266 on the serial monitor.
}
return response;
}
Forum link - https://forum.arduino.cc/index.php?topic=538180.0
Unfortunately you are not showing the differences between the code that is working (partially, TCP connection) and the one that is not (at all, or just the TCP connection?).
when i remove the Rc522 code testing then it is working !
Just try to describe what is working and what isn't a little more in detail. You could also provide your debug output and add some comments.
Also I'd try removing more non-essential code (like the display) to help narrow down the cause. This might already get you on the right track to fix it yourself, but it would also make your code here easier to read (also see How to create a Minimal, Complete, and Verifiable example though I doubt many will have the exact parts to reproduce your problem - but you might get lucky).
But, from the code you've provided, here's just a guess:
The Arduino might not be receiving data from the ESP8266 module because you are reconfiguring the RX pin as output (but you're not using it!?):
#define mainLock 2
...
pinMode(mainLock, OUTPUT);
conflicts with
SoftwareSerial esp(2, 3);// RX, TX
So I'd recommend double-checking your pin use and connections (also, providing this information would increase your chances of somebody spotting an error).

Arduino servo control over wi-fi doesn't work

Hi I'm using arduino uno and wifi shield. I'm trying to create using the wifi shield to connect to a servo motor through webserver. To be honest I dont really know what im doing. This code is able to control the servo motor once and the whole system is shutdown.
can someone look into my codes and see what is wrong? If can I hope the code is able to control the servo multiple time without stopping.
#include <SPI.h>
#include <WiFi.h>
#include <Servo.h>
char ssid[] = "wifi"; // your network SSID (name)
char pass[] = "asdfghjkl"; // your network password
int keyIndex = 0;
// your network key Index number (needed only for WEP)
Servo myservo;
int status = WL_IDLE_STATUS;
WiFiServer server(80);
void setup() {
Serial.begin(9600); // initialize serial communication
myservo.attach(9);
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while (true); // don't continue
}
String fv = WiFi.firmwareVersion();
if (fv != "1.1.0") {
Serial.println("Please upgrade the firmware");
}
// 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(1000);
}
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 Open the door <br>");
client.print("Click here turn the Close the door <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")) {
// scale it to use it with the servo (value between 0 and 180)
myservo.write(800); // sets the servo position according to the scaled value
delay(15); // GET /H turns the LED on
}
if (currentLine.endsWith("GET /L")) {
// scale it to use it with the servo (value between 0 and 180)
myservo.write(2500); // sets the servo position according to the scaled value
delay(15); // GET /L turns the LED off
}
}
}
}
}
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);
}

Resources