ESP8266 stops connecting to NTP server when set up to run WiFi Manager - wifi

I have an ESP8266 that connects to WiFi and then calls an NTP server to get the time. Originally, I had set up the WiFi connection to work off a "config.h" file with SSID and password - the vanilla approach. Later, I set up a WiFi Manager with the AsyncWebServer library to avoid hardcoding credentials as shown in this tutorial by Rui Santos .
Now the user enters WiFi credentials on a web-page hosted by the ESP8266 which provides a Wireless Access Point. These credentials are stashed away in files on the local file-system (LittleFS) and accessed when making the WiFi connection from that point onwards. Upon connecting, the ESP8266 runs a web-server that hosts a static web-page.
This works fine and the ESP8266 connects to WiFi BUT the NTP service no longer works! I get a fixed time ~ 12:00 midnight from the NTP client. When I revert to connecting to WiFi the vanilla way, the NTP service works as expected.
Here is my code for making the WiFi connection in station mode. The class GuruWebServer has methods initializeaLittle(), readaLittle() and writeaLittle() for file-system operations. The key method, initializeWiFi(), returns true when connection is successfully made with the credentials stashed away in the file-system and returns false otherwise. The method has a loop with millis() in which the attempt to connect to WiFi is made until timeout (e.g. 60s).
I observe that the SSID and password are correctly recorded and WiFi connection is successfully made. Subsequently, using LanScan (on Mac), I can see the ESP8266 at the station IP address as configured. Using a browser, I can load the web-page it serves. However, I am no longer able to get the time-and-date from calling the NTP service.
bool GuruWebServer::initializeWiFi() {
/*
* Make WiFi connection when SSID and PWD are available
* and set up station for web-service.
*/
// Initialize LittleFS
this->initializeaLittle();
// Connect to WiFi
this->readaLittle(&SSID, Path2_SSID);
this->readaLittle(&PWD, Path2_PWD);
this->readaLittle(&IP, Path2_IP);
this->readaLittle(&Gateway, Path2_Gateway);
String conn_ack = (String)"SSID <" + SSID + "> | PWD <" + PWD + "> | IP <" + IP + "> | Gateway <" + Gateway + ">";
if (SSID == "" || PWD == "") { // Files not populated!
Serial.println("Found NO SSID or PWD!");
return false;
}
WiFi.mode(WIFI_STA);
localIP.fromString(IP.c_str());
localGateway.fromString(Gateway.c_str());
if (!WiFi.config(localIP, localGateway, subnet)) {
Serial.println("Configured NO station!");
return false;
}
WiFi.begin(SSID, PWD);
unsigned long _now = millis();
unsigned long _then = _now; // Marker for ticker
unsigned long _stop = _now; // Marker for timeout
unsigned long delta_minor = 0; // Time since last tick
unsigned long delta_major = 0; // Time since start
while (WiFi.status() != WL_CONNECTED) {
_now = millis();
delta_minor = _now - _then; // Time since last tick
delta_major = _now - _stop; // Time since start
if (delta_minor > 1000) { // Mark time and reset delta
_then = _now;
Serial.print (".");
}
if (delta_major > 60000) { // Stop attempting connection
String timely = (String)"Now " + _now + " Stop " + _stop + " Diff " + delta_major;
Serial.println(timely);
Serial.println("Made NO WiFi connection!");
return false; // Exit false
} // end IF
} // end WHILE WiFi
Serial.println(WiFi.localIP());
return true;
}
To get time, I have used NTPClient library in the main program as follows:
#include <NTPClient.h>
#include <WiFiUdp.h>
WiFiUDP NTP_UDP;
NTPClient timeClient(NTP_UDP, "us.pool.ntp.org");
and in the setup() function of "main.cpp", I have:
// Connect to the NTP client
delay(500);
timeClient.begin();
timeClient.setTimeOffset(-18000); // Central time GMT-5 ~ -5 x 3600
timeClient.update();
Serial.println(timeClient.getFormattedTime());
The github branch rev007 has the code with WiFi Manager and rev006 has the vanilla WiFi.
I have tried the following:
Used a different approach to get time on ESP8266 with "time.h" and configTime() function.
Configured the web-server to use a port other than 80 (e.g. 8211) in AsyncWebServer server(80);.
Grateful for any help figuring this out, thank you.
UPDATE
I have simplified the code to illustrate the problem. This single script sets up the ESP8266 as WiFi station. The device connects to WiFi successfully but is unsuccessful calling the NTP service.
#include <Arduino.h>
#include <time.h>
#include "LittleFS.h"
#include <ESP8266WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
WiFiUDP NTP_UDP;
NTPClient timeClient(NTP_UDP, "pool.ntp.org");
// Alt.
#include "config.h"
IPAddress localIP;
IPAddress localGateway;
IPAddress subnet(255, 255, 255, 0);
void setup() {
Serial.begin(9600);
WiFi.mode(WIFI_STA);
// Comment out from here --->
localIP.fromString(IP);
localGateway.fromString(Gateway);
if (!WiFi.config(localIP, localGateway, subnet)) {
Serial.println("Configured NO station!");
}
// <--- upto here!
WiFi.begin(SSID, PWD);
unsigned long _now = millis();
unsigned long _then = _now; // Marker for ticker
unsigned long _stop = _now; // Marker for timeout
unsigned long delta_minor = 0; // Time since last tick
unsigned long delta_major = 0; // Time since start
while (WiFi.status() != WL_CONNECTED) {
_now = millis();
delta_minor = _now - _then; // Time since last tick
delta_major = _now - _stop; // Time since start
if (delta_minor > 1000) { // Mark time and reset delta
_then = _now;
Serial.print (".");
}
if (delta_major > 60000) { // Stop attempting connection
String timely = (String)"Now " + _now + " Stop " + _stop + " Diff " + delta_major;
Serial.println(timely);
Serial.println("Made NO WiFi connection!");
} // end IF
} // end WHILE WiFi
Serial.println(WiFi.localIP());
// Connect to the NTP client
delay(3000);
timeClient.begin();
timeClient.setTimeOffset(-18000); // Central time GMT-5 ~ -5 x 3600
delay(3000);
timeClient.update();
Serial.println(timeClient.getFormattedTime());
}
void loop() {
// put your main code here, to run repeatedly:
}
When I comment out the code as shown so as not to configure the IP address from settings but let it be determined at run-time, then all is well.

I'm curious enough to try your code. The issue is without the proper DNS setup, the NTP(UDP) won't be able to resolve the NTP name "pool.ntp.org", I tested your code with slightly modification and simplification. Without specifying the DNS with WiFi.config(localIP, localGateway, subnet), the timeClient.update() simply can't establish a NTP connection, by adding a DNS IP to WiFi.config(localIP, localGateway, subnet, dns), the following code works like a charm.
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
WiFiUDP NTP_UDP;
NTPClient timeClient(NTP_UDP, "pool.ntp.org");
#include "config.h"
IPAddress localIP(192, 168, 0, 120); // my local ip
IPAddress localGateway(192, 168, 0, 1); // my local gateway
IPAddress subnet(255, 255, 255, 0);
IPAddress dns(1, 1, 1, 1); // CloudFlare DNS server
void setup() {
Serial.begin(9600);
while (!Serial);
WiFi.mode(WIFI_STA);
WiFi.begin(SSID, PWD);
WiFi.config(localIP, localGateway, subnet, dns);
int count = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(500);
if (count++ > 20) ESP.restart(); //timeout, reboot
}
Serial.println(WiFi.localIP());
// Connect to the NTP client
timeClient.begin();
timeClient.setTimeOffset(8*3600); //my timezone
if (timeClient.update())
Serial.println(timeClient.getFormattedTime());
}
void loop() {
}

If you want using WiFiManager just leave wifiManager.setSTAStaticIPConfig and use this after wifiManager.autoConnect
WiFi.begin();
WiFi.config(IPAddress(192, 168, 1, 148), IPAddress(192, 168, 1, 1), IPAddress(192, 168, 1, 1), IPAddress(255, 255, 255, 0));
It working for me on ESP8266.

Related

memory error: "conn.connect(server_addr, 3306, user, password)"

Recently I dived into making an Arduino project. I use Arduino IDE 2.0.3 and the board, LILYGO T-PICOC3.
When I tried to let my board connect to the MySQL server, I encountered an issue...
This is my sketch. I uploaded it to the board successfully
#include <WiFiEspAT.h>
#include <TFT_eSPI.h>
#include <SPI.h>
#include <Button2.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"
//#include "MAX30105.h"
#include <Wire.h>
//#include "heartRate.h"
//#define I2C_SDA 12
//#define I2C_SCL 13
byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress server_addr(xxx, xxx, xx, xxx);
char user[] = "project" ;
char password[] = "1234";
WiFiClient client;
MySQL_Connection conn((Client *)&client);
char ssid[] = "Home3";
char pass[] = "12341234";
// max30102 setup ----
//MAX30105 particleSensor;
//long lastbeat;
// max30102 setup ----
void setup() {
Serial.begin(115200);
// power supply ----
pinMode(22, OUTPUT);
digitalWrite(22,HIGH);
// power supply ----
// esp32 setup ----
Serial2.setTX(8);
Serial2.setRX(9);
Serial2.begin(115200);
// esp32 setup ----
// max30102 segment ----
//if (particleSensor.begin(Wire, I2C_SPEED_FAST) == false){
// Serial.println("MAX30102 was not found");
// while(true);
//}
//particleSensor.setup();
//particleSensor.setPulseAmplitudeRed(0x0A);
//Serial.print("max30102 is online!");
// max30102 segment ----
// WiFi start ----
WiFi.init(Serial2);
WiFi.begin(ssid, pass);
Serial.println("connecting to wifi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1600);
}
Serial.println("Connected to network");
pinMode(29, OUTPUT);
digitalWrite(29, HIGH);
IPAddress ip = WiFi.localIP();
Serial.print("My IP address is: ");
Serial.println(ip);
// WiFi start ----
// connect to database ----
Serial.println("Connecting to the database");
if (conn.connect(server_addr, 3306, user, password)){
delay(1000);
}
Serial.println("unSuccessfully connect!");
conn.close();
// connect to database ----
}
void loop() {
//long irvalue = particleSensor.getIR();
//if (checkForBeat(irvalue) == true){
// long delta = millis() - lastbeat;
// lastbeat = millis();
// float beatsperminute = 60 / (delta/1000.0);
//}
}
And I got the message from Output :
Sketch uses 340796 bytes (16%) of program storage space. Maximum is 2093056 bytes.
Global variables use 69008 bytes (26%) of dynamic memory, leaving 193136 bytes for local variables. Maximum is 262144 bytes.
Resetting COM5
Converting to uf2, output size: 714240, start address: 0x2000
Flashing G: (RPI-RP2)
Wrote 714240 bytes to G:/NEW.UF2
Everything seems fine so far... but as I check out the Serial Monitor, I receive a Memory error when the process reaches the code " conn.connect(server_addr, 3306, user, password) "
12:33:29.765 -> Connected to network
12:33:29.810 -> My IP address is: 192.168.0.159
12:33:29.810 -> Connecting to the database
12:33:29.810 -> ...trying...
12:33:31.116 -> Memory error.
12:33:32.481 -> Memory error.
12:33:32.481 -> Error: -1 = unSuccessfully connect!
I was originally trying to integrate the Max30102 module into my board, but after the error occurred, I uncommented the code associated with Max30102 and try it again. In the end, It turned out the same. In addition, I change the “server_addr” for the other MySQL server and restart Arduino IDE and nothing changed too. Perhaps the problem is derived from the hardware, the libraries, or the potentially incomplete uploading?

cannot publish data to my local mqtt server

Please i wish somebody could help me with this. I've been struggling into it since a couple of weeks, i am so new to that.
I want to send data from ESP32 SIM800L to a mqtt broker.
The mqtt server is running on my local machine and the ESP32 SIM800 can perfectly connect to APN.
I saw many tutorials doing it with WIFI connection but not GPRS(what i am using).
I finally find this: tinyGSM and this :arduino mqtt mongodb
And i adapted it as follows, but still getting connection failed:
// Your GPRS credentials (leave empty, if not needed)
const char apn[] = "internet.tn"; // APN (example: internet.vodafone.pt) use https://wiki.apnchanger.org
const char gprsUser[] = ""; // GPRS User
const char gprsPass[] = ""; // GPRS Password
// SIM card PIN (leave empty, if not defined)
const char simPIN[] = "";
uint32_t lastReconnectAttempt = 0;
// TTGO T-Call pins
#define MODEM_RST 5
#define MODEM_PWKEY 4
#define MODEM_POWER_ON 23
#define MODEM_TX 27
#define MODEM_RX 26
#define I2C_SDA 21
#define I2C_SCL 22
// Set serial for debug console (to Serial Monitor, default speed 115200)
#define SerialMon Serial
// Set serial for AT commands (to SIM800 module)
#define SerialAT Serial1
// Configure TinyGSM library
#define TINY_GSM_MODEM_SIM800 // Modem is SIM800
#define TINY_GSM_RX_BUFFER 1024 // Set RX buffer to 1Kb
#include <Wire.h>
#include <TinyGsmClient.h>
#include <PubSubClient.h>
#ifdef DUMP_AT_COMMANDS
#include <StreamDebugger.h>
StreamDebugger debugger(SerialAT, SerialMon);
TinyGsm modem(debugger);
#else
TinyGsm modem(SerialAT);
#endif
// I2C for SIM800 (to keep it running when powered from battery)
TwoWire I2CPower = TwoWire(0);
const char* broker = "localhost";
const char* topicInit = "GsmClientTest/init";
// Function prototypes
void subscribeReceive(char* topic, byte* payload, unsigned int length);
// TinyGSM Client for Internet connection
// gsm and MQTT related objects
TinyGsmClient client(modem);
PubSubClient mqtt(client);
long mqtttimer = 0; // Timer for counting 5 seconds and retrying mqtt connection
byte mqtttarea = 1;
#define uS_TO_S_FACTOR 1000000 /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP 3600 /* Time ESP32 will go to sleep (in seconds) 3600 seconds = 1 hour */
void mqttCallback(char* topic, byte* payload, unsigned int len) {
SerialMon.print("Message arrived [");
SerialMon.print(topic);
SerialMon.print("]: ");
SerialMon.write(payload, len);
SerialMon.println();}
boolean mqttConnect() {
SerialMon.print("Connecting to ");
SerialMon.print(broker);
// Connect to MQTT Broker
boolean status = mqtt.connect("GsmClientTest");
// Or, if you want to authenticate MQTT:
//boolean status = mqtt.connect("GsmClientName", "mqtt_user", "mqtt_pass");
if (status == false) {
SerialMon.println(" fail");
return false;
}
SerialMon.println(" success");
mqtt.publish(topicInit, "GsmClientTest started");
// mqtt.subscribe(topicLed);
return mqtt.connected();}
void setup() {
SerialMon.begin(9600);
// Start I2C communication
I2CPower.begin(I2C_SDA, I2C_SCL, 400000);
// Set modem reset, enable, power pins
pinMode(MODEM_PWKEY, OUTPUT);
pinMode(MODEM_RST, OUTPUT);
pinMode(MODEM_POWER_ON, OUTPUT);
digitalWrite(MODEM_PWKEY, LOW);
digitalWrite(MODEM_RST, HIGH);
digitalWrite(MODEM_POWER_ON, HIGH);
// Set GSM module baud rate and UART pins
SerialAT.begin(9600, SERIAL_8N1, MODEM_RX, MODEM_TX);
delay(3000);
// Restart SIM800 module, it takes quite some time
// To skip it, call init() instead of restart()
SerialMon.println("Initializing modem...");
modem.restart();
// use modem.init() if you don't need the complete restart
// Unlock your SIM card with a PIN if needed
if (strlen(simPIN) && modem.getSimStatus() != 3 ) {
modem.simUnlock(simPIN);
}
SerialMon.print("Connecting to APN: ");
SerialMon.print(apn);
if (!modem.gprsConnect(apn, gprsUser, gprsPass)) {
SerialMon.println(" fail");
}
else {
SerialMon.println(" OK");
}
// MQTT Broker setup
mqtt.setServer(broker, 1883);
mqtt.setCallback(mqttCallback);
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
}
void loop() {
// This is needed at the top of the loop!
if (!mqtt.connected()) {
SerialMon.println("=== MQTT NOT CONNECTED ===");
// Reconnect every 10 seconds
uint32_t t = millis();
if (t - lastReconnectAttempt > 10000L) {
lastReconnectAttempt = t;
if (mqttConnect()) {
lastReconnectAttempt = 0;
}
}
delay(100);
return;
}
mqtt.publish(topicInit, "Hello");
mqtt.loop();
}
You set the broker's name to localhost:
const char* broker = "localhost";
localhost and the IP address 127.0.0.1 mean "the host that this code is running on". When you're typing commands on the computer running the broker, localhost will mean that computer. There's no way it will work on the ESP32.
You need to name or IP address of the computer running the broker. How you find that will depend on the operating system you're running.
If that computer is on your local network it's probably using a private IP address like 10.0.1.x or 192.168.1.x. If that's the case you'll need to either use port forwarding in your router to forward packets to it (and then you'll use your router's IP address and not your broker's).
If you're using your router's IP address, that can change without warning, so you'll need to use something like Dynamic DNS to keep up to date with its current IP address.
You'll likely be better off running the broker outside of your network on a cloud-based virtual server or by using one of the several commercial MQTT services out there. Most of them have a free tier which will allow a reasonable amount of traffic per month.
Regardless, localhost will never work here. You need the real, public IP address or name of your broker.

fatal error: ESP8266WiFi.h: No such file or directory

I'm trying to make a "home weight" with my ESP32 and display the value using IBMCloud, however I'm running into some issues with the Arduino IDE and my code.
I get this error:
Arduino:1.8.5 (Windows 10), Tarjeta:"ESP32 Dev Module, QIO, 80MHz, 4MB (32Mb), 921600, None"
C:\Users\XX\Documents\Arduino\IBM_Watson_Connect\IBM_Watson_Connect.ino:8:25: fatal error: ESP8266WiFi.h: No such file or directory
compilation terminated.
exit status 1
Compiling error for the ESP32 Dev Module card.
I'm using a ESP32 dev board. My code is this:
#include <ESP8266WiFi.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient/releases/tag/v2.3
#include "HX711.h" //Load Cell Amplifier
HX711 cell(D2, D4); //Amplifier is connected to these pins on the NodeMCU ESP8266 Board
#define WLAN_SSID "XXXXX"
#define WLAN_PASS "XXXXX"
#define ORG "XXXXX"
#define DEVICE_TYPE "XXXXXX"
#define DEVICE_ID "XXXXX"
#define TOKEN "XXXXXXXX"
char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char topic[] = "iot-2/evt/status/fmt/json";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
WiFiClient wifiClient;
PubSubClient client(server, 1883, NULL, wifiClient);
void setup() {
Serial.begin(115200);
Serial.println();
// Connect to WiFi access point.
Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());
}
int counter = 0;
void loop() {
if (!!!client.connected()) {
Serial.print("Reconnecting client to ");
Serial.println(server);
while (!!!client.connect(clientId, authMethod, token)) {
Serial.print(".");
delay(500);
}
Serial.println();
}
//----------Get data from load cell and amplifier
long valCalibrated = 0;
long val = 0;
float count = 0;
count = count + 1;
val = 0.5 * val + 0.5 * cell.read();
valCalibrated = (val - 4137240) / 234.20;
//----------Send data to IBM Waton IoT Service
String payload = "{\"d\":{\"weight\":";
payload += valCalibrated;
payload += "}}";
Serial.print("Sending payload: ");
Serial.println(payload);
if (client.publish(topic, (char*) payload.c_str())) {
Serial.println("Publish ok");
} else {
Serial.println("Publish failed");
}
++counter;
delay(100); //adjust delay to send more or less reads per unit time
}
Some places mentioned that the library was missing, that the board wasn't properly selected, the library wasn't updated.. I checked them all.. Arduino is updated, libraries are installed and updated, proper board is selected (I actually have tried all the other Esp32 related boards with the same result)
You're building a program for the ESP32, not the ESP8266. There are a lot of similarities but they're entirely different chips with different software.
So you don't use ESP8266WiFi.h with the ESP32. On the ESP32, the header file is just called WiFi.h (keeping more in line with WiFi support on Arduinos - the ESP32 Arduino Core is intended to be more compatible with the normal Arduino Core than the ESP8266 version was).
You need to
#include <WiFi.h>
instead of ESP8266WiFi.h
You can find the code for these files in the official repository for the Arduino SDK for the ESP32.
(It doesn't help that WiFi.h for the ESP32 identifies itself as ESP8266.h in its own comments...)

Cannot upload data get xivelyclient.put returned -1

Background:
I am trying to upload data from a simple on off sensor to learn the Xively methods. I am using an Arduino Uno with a WiFi Shield. I made some simple alterations to an example sketch from the Xively library to keep it very simple. I have read the documentation and the FAQ's plus searched the web. There was a similar question (Can't connect to Xively using Arduino + wifi shield, "ret = -1 No sockets available) and the answer was to reduce the number of libraries loaded. I'm using the same library list recommended in that post.I have also updated my Arduino IDE and downloaded the latest xively and HTTP library. The code compiles without error. I re-loaded my device on the xively website and got a new API key and number as well. Plus, I ensured the channel was added with the correct sensor name. I have also checked my router and ensured the WiFi shield was connecting properly.
Problem: I can't see the data on the Xively website and I keep getting the following error messages on the serial monitor from the Arduino:
xivelyclint.put returned -1
also, after several tries, I get "No socket available"
Question: Is there an problem with the code or is it something else?
Current Arduino code (actual ssid, password and API key and number removed):
#include <SPI.h>
#include <WiFi.h>
#include <HttpClient.h>
#include <Xively.h>
char ssid[] = "ssid"; // your network SSID (name)
char pass[] = "password"; // 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;
// Your Xively key to let you upload data
char xivelyKey[] = "api_key";
// Analog pin which we're monitoring (0 and 1 are used by the Ethernet shield)
int sensorPin = 2;
// Define the strings for our datastream IDs
char sensorId[] = "sensor_id";
XivelyDatastream datastreams[] = {
XivelyDatastream(sensorId, strlen(sensorId), DATASTREAM_INT),
};
// Finally, wrap the datastreams into a feed
XivelyFeed feed(feed no., datastreams, 1 /* number of datastreams */);
WiFiClient client;
XivelyClient xivelyclient(client);
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");
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Starting single datastream upload to Xively...");
Serial.println();
// attempt to connect to Wifi 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);
}
Serial.println("Connected to wifi");
printWifiStatus();
}
void loop() {
int sensorValue = digitalRead(sensorPin);
datastreams[0].setInt(sensorValue);
Serial.print("Read sensor value ");
Serial.println(datastreams[0].getInt());
Serial.println("Uploading it to Xively");
int ret = xivelyclient.put(feed, xivelyKey);
Serial.print("xivelyclient.put returned ");
Serial.println(ret);
Serial.println();
delay(15000);
}

Can the Arduino's LiquidCrystal library interfere with the Wi-Fi library?

One day I was playing around with my Arduino and had a cool idea. Maybe I could do a wireless connection WITHOUT the serial monitor! I could use an LCD display instead! So, I went to work. I replaced all of the serial stuff with LCD stuff.
Finally I had no errors in my code (according to the Arduino client, that is).
Here is my code:
#include <LiquidCrystal.h>
#include <WiFi.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
char ssid[] = "Fake Network"; // Your network SSID (name)
char key[] = "1"; // your network key
int keyIndex = 0; // Your network key Index number
int status = WL_IDLE_STATUS; // The Wi-Fi radio's status
void setup() {
lcd.begin(16, 2);
// Check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
lcd.println("WiFi shield not present");
// Don't continue:
while(true);
}
// Attempt to connect to Wi-Fi network:
while ( status != WL_CONNECTED) {
lcd.print("Attempting to connect to WEP network, SSID: ");
lcd.println(ssid);
status = WiFi.begin(ssid, keyIndex, key);
// Wait 10 seconds for connection:
delay(10000);
}
// Once you are connected:
lcd.print("You're connected to the network");
printCurrentNet();
printWifiData();
}
void loop() {
// Check the network connection once every 10 seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// Print your Wi-Fi shield's IP address:
IPAddress IPaddr = WiFi.localIP();
lcd.print("IP Address: ");
lcd.println(IPaddr);
lcd.println(IPaddr);
// Print your MAC address:
byte MACaddr[6];
WiFi.macAddress(MACaddr);
lcd.print("MAC address: ");
lcd.print(MACaddr[5],HEX);
lcd.print(":");
lcd.print(MACaddr[4],HEX);
lcd.print(":");
lcd.print(MACaddr[3],HEX);
lcd.print(":");
lcd.print(MACaddr[2],HEX);
lcd.print(":");
lcd.print(MACaddr[1],HEX);
lcd.print(":");
lcd.println(MACaddr[0],HEX);
}
void printCurrentNet() {
// Print the SSID of the network you're attached to:
lcd.print("SSID: ");
lcd.println(WiFi.SSID());
// Print the MAC address of the router you're attached to:
byte bssid[6];
WiFi.BSSID(bssid);
lcd.print("BSSID: ");
lcd.print(bssid[5],HEX);
lcd.print(":");
lcd.print(bssid[4],HEX);
lcd.print(":");
lcd.print(bssid[3],HEX);
lcd.print(":");
lcd.print(bssid[2],HEX);
lcd.print(":");
lcd.print(bssid[1],HEX);
lcd.print(":");
lcd.println(bssid[0],HEX);
// Print the received signal strength:
long rssi = WiFi.RSSI();
lcd.print("signal strength (RSSI):");
lcd.println(rssi);
// Print the encryption type:
byte encryption = WiFi.encryptionType();
lcd.print("Encryption Type:");
lcd.println(encryption,HEX);
lcd.println();
}
And the result was....... Nothing. Nothing displayed.
Then I went and did my version of debugging. Note that I started at the bottom of the code.
lcd.print("bug");
I put this under every line of my code. Finally, I got to the top, under this line:
lcd.begin(16, 2);
AND GUESS WHAT! No display in any of the lines! I looked everywhere and I checked the display pins.
FINALLY, I found the problem!
It's a horrible bug that I can't get rid of! The display won't show with the WiFi.h library! I don't know why, But if I even #include <WiFi.h> into my program (or any program with the LiquidCrystal library... Things go exactly the same way!
What is the reason for this problem and how can I fix it? I haven't got any luck yet.
According to the documentation:
Arduino communicates with both the Wifi shield's processor and SD card using the SPI bus (through the ICSP header). This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On Uno 11 is MOSI, and 12 is MISO.
According to your code
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
you are using pins 11 and 12 for the LCD. Now if the LCD was using SPI, then the LCD could share pins 11 and 12 with the Wi-Fi shield, because the same set of pins used for SS (Slave Select) function would tell the peripherals which one of them should be listening. However, the LiquidCrystal library uses its first two argument pins for RS and Enable respectively, making it incompatible with SPI. The solution: move your LCD onto different pins.

Resources