Can't commute a relay with Arduino wifi shield + Xively - arduino

I’m trying to turn on and off an LED light bulb connected to a Tinterkit Relay.
I’m using an Arduino UNO r3 connected to internet thanks to an official Arduino Wifi shield.
I’ve done a simple website with two buttons to send a 1 (on) or a 0 (off) to my Xively account.
I’ve written a code to detect the last posted channel value. The code is working fine and I’m able to detect a 1 or a 0 every 3 seconds approximately. The problem is that the relay doesn’t commute.
Please please, I would appreciate a lot your help to solve this problem.
Here is the code:
#include <SPI.h>
#include <WiFi.h>
#include <HttpClient.h>
#include <Xively.h>
#include <TinkerKit.h>
char ssid[] = "XXXXXX";
char pass[] = "XXXXXX";
int state;
int status = WL_IDLE_STATUS;
char myIntStream[]="LED";
char xivelyKey[] = "XXXXXX";
#define FEED_ID XXXXXX
TKMosFet relay(O0);
XivelyDatastream datastreams[] = {
XivelyDatastream(myIntStream, strlen(myIntStream), DATASTREAM_INT),
};
XivelyFeed feed(FEED_ID,datastreams,1);
WiFiClient client;
XivelyClient xivelyclient(client);
void printWifiStatus() {
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
void setup() {
Serial.begin(9600);
Serial.println("LED light bulb");
Serial.println();
while ( status != WL_CONNECTED) {
Serial.println("Connecting to internet ...");
status = WiFi.begin(ssid, pass);
Serial.println("");
delay(5000);
}
Serial.println("Connected to wifi");
printWifiStatus();
}
void loop() {
Serial.println();
Serial.print("Datastream is:");
Serial.println(datastreams[0]);
Serial.print("LED value = ");
state = datastreams[0].getInt();
Serial.print(state);
if(state == 0){
relay.off();
Serial.println(" => Light is on.");
}
else if(state == 1){
relay.on();
Serial.println(" => Light is off.");
}
xivelyclient.get(feed, xivelyKey);
}

Related

WiFi Status 1 on ESP8266

I'm trying to connect my Arduino Uno R3 + ESP8266 to a WiFi connection, and it returned a status of 1 when I printed out WiFi.status(), does anyone now what does it really mean and what's the solution? Here's my ESP8266 code:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
// WiFi CREDENTIALS
const char *ssid = "xxxx";
const char *password = "xxxx";
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println();
Serial.println("Connect to: ");
Serial.println(ssid);
}
void loop(){
delay(5000);
WiFi.mode(WIFI_STA);
Serial.println();
Serial.println("Connect to: ");
Serial.println(ssid);
Serial.println(WiFi.status());
Serial.println(WL_CONNECTED);
if (WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, password);
delay(15000);
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("From ESP Connected!");
}
else {
Serial.println("From ESP Not Connected!");
}
}
=== UPDATE ===
I've tried using my smartphone's hotspot and it worked on the first try.
I found this in Arduino Forum. I hope it is useful for you. And status 1 means no ssid according to enum below.
typedef enum {
WL_NO_SHIELD = 255, // for compatibility with WiFi Shield library
WL_IDLE_STATUS = 0,
WL_NO_SSID_AVAIL = 1,
WL_SCAN_COMPLETED = 2,
WL_CONNECTED = 3,
WL_CONNECT_FAILED = 4,
WL_CONNECTION_LOST = 5,
WL_DISCONNECTED = 6
} wl_status_t;
I'm not sure myself, but when I start over using the cleaner code:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
// WiFi CREDENTIALS
const char *ssid = "xxxx";
const char *password = "xxxx";
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) {
Serial.println("From ESP Connected!");
}
delay(5000);
}
My gut is telling me that maybe WiFi.mode(WIFI_STA) is causing the error?
By the way, it worked already, thanks Juraj and cbalakus for the help!

ESP8266 is not able to connect to mosquitto broker. "Attempting MQTT connection...failed, rc=-2 try again in 5 seconds"

I'm running a mosquitto broker and a node-red server in my PC , node-red is able to connect to mosquitto. The ESP8266 is able to connect to the WiFi but not to the broker a "Attempting MQTT connection...failed, rc=-2 try again in 5 seconds" message is displayed in the serial monitor. I'm also using MQTT explorer I don't know if it has something to do with it.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "Milagros";
const char* password = "18095381";
const char* mqtt_server = "192.168.1.133";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
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();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
}
}
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("data", "hello world");
// ... and resubscribe
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("data", msg);
}
}```

Can't get ws2812b SMD LED to light up with NodeMCU using Blynk and FastLED

Wiring Diagram:
Sorry for the lame diagram, I am new to this.
I have a 5V input with 2.2A (checked using multimeter), with my data pin wired inline with a 220Ω resistor.
I'm able to successfully connect to my WiFi network and Blynk's cloud server, but am unable to get the LED to turn on or change color. The LED turned on for a little while when I was looking at code, which I have no idea why, but haven't been able to get it to turn on since.
Currently I am only driving 1 ws2812b LED.
Main.cpp:
#define BLYNK_PRINT Serial
#include <BlynkSimpleEsp8266.h>
#define FASTLED_ESP8266_RAW_PIN_ORDER
#include "FastLED.h"
#define NUM_LEDS1 60
#define LED_TYPE WS2812
#define COLOR_ORDER GRB
CRGB leds1[NUM_LEDS1];
char auth[] = "xxxxx";
char ssid[] = "xxx";
char pass[] = "xxxx";
#define PIN1 D2
int data=255;
int r,g,b;
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Blynk.begin(auth, ssid, pass);
Blynk.connect(3333);
while (Blynk.connect() == false) {
// Wait until connected
}
Serial.println("Connected to Blynk server");
FastLED.addLeds<LED_TYPE, PIN1, COLOR_ORDER>(leds1, NUM_LEDS1).setCorrection( TypicalLEDStrip );
}
void static1(int r, int g, int b, int brightness) {
FastLED.setBrightness(brightness);
for (int i = 0; i < NUM_LEDS1; i++) {
leds1[i] = CRGB(r, g, b);
}
FastLED.show();
}
BLYNK_WRITE(V3) {
r = param[0].asInt();
g = param[2].asInt();
b = param[2].asInt();
static1(r, g, b,data);
}
void loop() {
Blynk.run();
}
BLYNK_WRITE(V2) {
data = param.asInt();
static1(r, g, b, data);
}
Solved... The 220 Ohm Resistor was unnecessary because there's a resistor on-board.

NodeMCU gets strange IP address

Today I got my NodeMCU and I instantly started with coding. I wanted to connect to my WiFi and to my MQTT server.
I used the PubSub example for this.
In the serial monitor I get the message that I connected successfully with the WiFi, but I get the IP 172.20.10.6. However we have a 192.168... network.
Then when I try to reach my MQTT server it doesn't find it. When I try to give the NodeMCU a static IP it also says connected successfully and shows up the static IP I gave it, but I still can't connect to my MQTT server.
I can't ping the NodeMCU and don't find it in my Smartphone app "Fing".
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "myssid";
const char* password = "mypw";
const char* mqtt_server = "192.168.42.131";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup() {
pinMode(BUILTIN_LED, OUTPUT);
// Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
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 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();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(BUILTIN_LED, LOW);
// Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(BUILTIN_LED, HIGH);
// Turn the LED off by making the voltage HIGH
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Once connected, publish an announcement...
//client.publish("outTopic", "hello world");
// ... and resubscribe
client.subscribe("mathistest");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, 75, "hello world #%ld", value);
}
}
You are most likely having a DHCP failure.
A 172.20.x.x address is a non-routable IP address (see: https://www.lifewire.com/what-is-a-private-ip-address-2625970) and the DHCP code is (likely) using that address when the address assignment fails.
Stepping back, DHCP is most likely failing because you are failing to connect to the Wifi network with the correct SSID and password.

Multi-file arduino esp8266 sketch sharing a reference to server

As my sketches get bigger, the code looks awful as one file and the number of global variables is too high.
For the webconfig part of my sketch the device attempts to get online and if it fails it scans for available wifi networks, goes into Access Point Mode, starts a server, sends the list of ssid's and listens for a response of an ssid/passwd pair. The server is only for the configuration.
Ideally I'd like the cleaned up main.ino file to look like
#include "config.h"
void setup(){
Serial.begin(115200);
Serial.println();
Serial.println("--------------------------");
Serial.println("ESP8266 multifile");
Serial.println("--------------------------");
getOnline();
}
void loop(){
if(IN_CONFIG_MODE){
server.handleClient();
}
}
with a config.h something like..
#ifndef config_h
#define config_h
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
ESP8266WebServer server;
void getOnline();
#endif
and then a config.cpp where it does all stuff described above yet gives the main.ino program access to the server instance so it can listen in the main loop.
#include "config.h"
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
char *espssid = "espAPsb";
char *ssid = "street_no_vale2";
char *pwd = "jjjjjjjjx";
char ssids[300];
extern server(80);
void handleRoot(){
server.send(200, "text/html", "<h1>root of espAPsb AP server</h1>");
//send json of available ssids
}
void scan(){
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
int n = WiFi.scanNetworks();
Serial.println("scan done");
if (n == 0)
Serial.println("no networks found");
else
{
Serial.print(n);
Serial.println(" networks found");
for (int i = 0; i < n; ++i)
{
// Print SSID and RSSI for each network found
Serial.print(i + 1);
Serial.print(": ");
Serial.print(WiFi.SSID(i));
Serial.print(" (");
Serial.print(WiFi.RSSI(i));
Serial.print(")");
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
delay(10);
}
}
Serial.println("");
}
void setupAP(){
WiFi.softAP(espssid);
server.on("/", handleRoot);
server.begin();
Serial.println();
Serial.print("connected as AP ");
Serial.println(espssid);
Serial.print("IP address: ");
Serial.println(WiFi.softAPIP());
}
void getOnline(){
WiFi.begin(ssid, pwd);
int tries =0;
int success=1;
while (WiFi.status() != WL_CONNECTED ) {
delay(500);
Serial.print(".");
tries++;
if (tries==15){
success=0;
Serial.println("WiFi not connected");
scan();
setupAP();
break;
}
}
if (success){
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
}
You can make an own library from your networking code, which you can easily reuse.
https://www.arduino.cc/en/Hacking/LibraryTutorial
Alternatively, you can use multiple "tabs" in Arduino IDE which works like a standard multi-source project. http://arduino.land/FAQ/content/7/43/en/breaking-a-sketch-into-multiple-files.html
(Btw, StackExchange hosts a dedicated Ardunio microsite here: https://arduino.stackexchange.com/ Have fun there :)

Resources