Hold button more than 5 seconds, do something. Arduino - button

I have a hobby project that sends a string "1" or a string "0" to my webserver. My arduino work as a client, and It works, but now I want to add another statement.
If the button is held down 5 sec or longer, send string "5" to my webserver. I do not know how I can get the button to count the seconds I have hold the button. Can you please help?
Here is the code:
#include <SPI.h>
#include <WiFi.h>
byte mac[] = { 0xDE, 0xFD, 0xBE, 0xEF, 0xFE, 0xED }; // MAC adresse
char ssid[] = "test";
char pass[] = "123456789";
IPAddress ip(192, 168, 0, 143); // Klient IP
IPAddress server(192,168,0,100); // Server IP
int port = 2056;
boolean btnpressed = false;
int status = WL_IDLE_STATUS;
WiFiClient client;
unsigned long lastConnectionTime = 0;
boolean lastConnected = false;
const unsigned long postingInterval = 1000;
void setup() {
attachInterrupt(0, AlarmPressed, RISING);
// Opne serial port
Serial.begin(9600);
while (!Serial) {
;
}
while ( status != WL_CONNECTED) {
Serial.print(" SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
delay(1000); //
printWifiStatus();
Serial.println("Connecting to server");
}
}
void loop() {
if (client.available()) {
char c = client.read();
Serial.print(c);
client.stop();
}
if (!client.connected() && lastConnected) {
Serial.println("Disconnecting.");
Serial.println();
client.stop();
}
if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
SendData();
}
lastConnected = client.connected();
} // Slutten paa loop
void AlarmPressed() {
btnpressed = true;
}
void SendData() {
// if there's a successful connection:
if (client.connect(server, port)) {
Serial.println("Connecting...");
// Send data til server:
if (btnpressed == false){
client.write("0");
Serial.print("No Alarm");
Serial.println();
btnpressed = false;
}
else {
client.write("1");
Serial.print("Alarm !");
Serial.println();
}
// note the time that the connection was made:
lastConnectionTime = millis();
}
else {
// if you couldn't make a connection:
Serial.println("Connection failed");
Serial.println("Disconnecting.");
Serial.println();
client.stop();
}
}
void printWifiStatus() {
Serial.print(" SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("Signalstyrke til forbindelsen (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

Related

Node mcu esp8266 disconnects from MQTT broker

I have two node mcu modules connected to the same network, running the same code and powered the same way. Both of them are subscribed to the topic Terma but one of them randomly disconnects and then reconnects to the MQTT broker meanwhile it stayed connected to the wifi uninterruptedly, the other module stays connected with no problem. I don't know if it is a network issue or if the node mcu is damaged.
here is the code:
#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);
long lastMsg = 0;
char msg[50];
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.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(14, LOW);
client.publish("estado","1");
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(14, HIGH);
client.publish("estado","0");
}
}
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("terma", "hello world 1");
// ... and resubscribe
client.subscribe("terma");
} 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(14, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1884);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}

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);
}
}```

Error using thingspeak talk back to control arduino led

The error I'm facing is about using talkback function of thingspeak to control my Arduino LED. it cannot execute the talkback command to off the led. The error is in my void get talkback. Please help me
#include "ThingSpeak.h"
#include <Ethernet.h>
#define redLED 8
byte mac[] = {0x90, 0xA2, 0xDA, 0x10, 0x40, 0x4F};
const String channelsAPIKey = "";
const String talkBackAPIKey = "";
const String talkBackID = "";
const String talkCommandID = "";
const unsigned int getTalkBackInterval = 10 * 1000;
const unsigned int updateChannelsInterval = 15 * 1000;
String talkBackCommand;
long lastConnectionTimeChannels = 0;
boolean lastConnectedChannels = false;
int failedCounterChannels = 0;
long lastConnectionTimeTalkBack = 0;
boolean lastConnectedTalkBack = false;
int failedCounterTalkBack = 0;
char charIn;
// Arduino Ethernet Client is initialized
EthernetClient client;
void setup()
{
Ethernet.init(10); // Most Arduino Ethernet hardware
Serial.begin(9600); //Initialize serial
// start the Ethernet connection:
pinMode(redLED, OUTPUT);
digitalWrite(redLED, HIGH);
}
void loop()
{
getTalkBack();
}
void getTalkBack()
{
String tsData;
tsData = talkBackID + "/commands/execute?api_key=" + talkBackAPIKey;
if ((!client.connected() && (millis() - lastConnectionTimeTalkBack > getTalkBackInterval)))
{
if (client.connect("api.thingspeak.com", 80))
{
client.println("GET /talkbacks/" + tsData + " HTTP/1.0");
client.println();
lastConnectionTimeTalkBack = millis();
if (client.connected())
{
Serial.println("---------------------------------------");
Serial.println("GET TalkBack command");
Serial.println();
Serial.println("Connecting to ThingSpeak");
Serial.println();
Serial.println();
Serial.println("Server response");
Serial.println();
failedCounterTalkBack = 0;
while (client.connected() && !client.available()) delay(2000); //waits for data
while (client.connected() || client.available())
{
charIn = client.read();
talkBackCommand += charIn;
Serial.print(charIn);
if (talkBackCommand == "LED_ON")
{
digitalWrite(redLED, HIGH);
}
if (talkBackCommand == "LED_OFF")
{
digitalWrite(redLED, LOW);
}
}
if (talkBackCommand = talkBackCommand.substring(talkBackCommand.indexOf("_CMD_") + 5));
{
Serial.println();
Serial.println();
Serial.println("Disconnected");
Serial.println();
Serial.println("--------");
Serial.println();
Serial.println("talkback command was");
Serial.println();
Serial.println("--------");
Serial.println();
Serial.println(talkBackCommand);
Serial.println("--------");
Serial.println();
}
}
else
{
failedCounterTalkBack++;
Serial.println("Connection to ThingSpeak failed (" + String(failedCounterTalkBack, DEC) + ")");
Serial.println();
lastConnectionTimeChannels = millis();
}
}
}
if (failedCounterTalkBack > 3 )
{
startEthernet();
}
client.stop();
Serial.flush();
}
The below is a image from my serial monitor. It shows that I can capture the command but couldn't execute it.
Looks like you are reading and appending all the received bytes to talkBackCommand. So, talkBackCommand is "HTTP/1.1 200 OK Date...." and if (talkBackCommand == "LED_ON") would never be true.
I think you wanted to see if the received data contain your commands LED_ON or LED_OFF. You can do something like this:
if (talkBackCommand.indexOf("LED_ON") != -1)
indexOf() locates a String in a String and returns index or -1 if not found.
See more info about indexOf() here: https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/indexof/

Esp01 Wifi Hotspot + web server not working

I am trying to make a simple esp01 wifi hotspot + a simple webpage with 3 buttons that send ints(1,2,3) over serial when pressed. But the wifi hotspot isn't working.
Here is the code:
#include <ESP8266WiFi>;
#include <WiFiClient>;
#include <ESP8266WebServer>;
const char *ssid = "test";
const char *password = "password";
IPAddress local_IP(192,168,4,22);
IPAddress gateway(192,168,4,9);
IPAddress subnet(255,255,255,0);
WiFiServer server(80);
void setup() {
delay(1000);
Serial.begin(9600);
WiFi.softAPConfig(local_IP, gateway, subnet);
WiFi.softAP(ssid, password);
server.begin();
}
void loop() {
WiFiClient client = server.available();
if (!client)
{
return;
}
while(!client.available())
{
delay(1);
}
String request = client.readStringUntil('\r');
client.flush();
if (request.indexOf("/R1") != -1)
{
Serial.println("1");
}else if (request.indexOf("/R2") != -1)
{
Serial.println("2");
}else if (request.indexOf("/R3") != -1)
{
Serial.println("3");
}
client.println("Content-Type: text/html");
client.println("");
client.println("<!DOCTYPE html>");
client.println("<html>");
client.println("<head><title>ESP01 RELAY Control</title></head>");
client.println("<body>");
client.println("<br>");
client.println("<button href=\"/R1\">R:1</button>");
client.println("<button href=\"/R2\">R:2</button>");
client.println("<button href=\"/R3\">R:3</button>");
client.println("<br>");
client.println("<button href=\"/T1\">T:1</button>");
client.println("<button href=\"/T2\">T:2</button>");
client.println("<button href=\"/T3\">T:3</button>");
client.println("</body>");
client.println("</html>");
delay(1);
}
To program an ESP8622 it is best practice to use the Serial.println() command to debug your code. For setting up a working access point (AP) on a ESP8622 module, use the following code;
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
const char *ssid = "test";
const char *password = "password";
IPAddress local_IP(192,168,4,22);
IPAddress gateway(192,168,4,9);
IPAddress subnet(255,255,255,0);
WiFiServer server(80);
void setup() {
delay(1000);
Serial.begin(9600);
Serial.print("Setting soft-AP configuration ... ");
Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!");
Serial.print("Setting soft-AP ... ");
Serial.println(WiFi.softAP(ssid, password) ? "Ready" : "Failed!");
Serial.print("Soft-AP IP address = ");
Serial.println(WiFi.softAPIP());
server.begin();
}
void loop() {
WiFiClient client = server.available();
if(client){
while (client.connected()) {
if(client.available()){
Serial.println("Connected to client");
}
}
// close the connection:
client.stop();
}
}

There are no GPS data after connecting to the server

I'm trying to get GPS data and send it to the server via socket.
I'm using Arduino Uno and GPS/GSM module A7 Ai-Thinker.
And for Internet I use Ethernet shield connected to Wi-Fi router.
But I got trouble when I joined getting GPS data and sending it.
Separately that functions work fine. How I start A7, there is a loop where I type AT commands and send it to A7. About socket, I want to set connection at start function and keep it alive all the time.
But the problem is that when I initialized A7 and set socket connection, I go to the loop function and after first iteration there are no data at A7.
If I try to set connection with server first, and start A7 after it, A7 doesn't react to AT commands.
How can I keep connection with my server and don't lost connection with A7?
Code:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <SPI.h>
#include <Ethernet.h>
//-------------------------------------------------------
static const int RXPin = 10, TXPin = 11;
static const uint32_t GPSBaud = 4800;
const String START_GPS = "START_GPS";
TinyGPSPlus gps;
SoftwareSerial gps_serial(RXPin, TXPin);
//-------------------------------------------------------
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char server[] = "192.168.0.100";
int port = 8090;
IPAddress ip(192, 168, 0, 177);
EthernetClient client;
//-------------------------------------------------------
void initGpsConnection();
void startGps();
void initSocketConnection();
void sendData();
void setup()
{
Serial.begin(9600);
Serial.println();
initSocketConnection();
initGpsConnection();
sendData();
}
void loop()
{
while (gps_serial.available() > 0) {
if (gps.encode(gps_serial.read())) {
displayInfo();
//delay(1000);
}
}
if (millis() > 120000 && gps.charsProcessed() < 10)
{
Serial.println(F("No GPS detected: check wiring."));
//while(true);
}
if (!client.connected()) {
Serial.println();
Serial.println("Socket connection has been lost.");
client.stop();
//while (true);
}
}
void displayInfo()
{
Serial.print(F("Location: "));
if (gps.location.isValid())
{
Serial.print(gps.location.lat(), 6);
Serial.print(F(","));
Serial.print(gps.location.lng(), 6);
}
else
{
Serial.print(F("INVALID"));
}
Serial.print(F(" Date/Time: "));
if (gps.date.isValid()) {
Serial.print(gps.date.month() + "/" gps.date.day() + "/" + gps.date.year();
} else {
Serial.print(F("INVALID"));
}
Serial.print(F(" "));
if (gps.time.isValid()) {
Serial.print(gps.time.hour() + ":" + gps.time.minute() + ":" + gps.time.second());
} else {
Serial.print(F("INVALID"));
}
Serial.println();
}
void initGpsConnection() {
Serial.println("In init gps");
gps_serial.begin(GPSBaud);
Serial.println("after gps begin");
delay(1000);
startGps();
Serial.println("GPS connection has been set");
}
void startGps() {
Serial.println("Enter at commands, after that enter `start_gps`");
String response = "";
while (true) {
if (gps_serial.available()) {
Serial.write(gps_serial.read());
}
if (Serial.available()) {
char c = Serial.read();
response += c;
if (response.indexOf(START_GPS) > 0)
break;
gps_serial.write(c);
}
}
}
void initSocketConnection() {
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
Ethernet.begin(mac, ip);
}
delay(1000);
Serial.println("connecting...");
if (client.connect(server, port)) {
Serial.println("Connection with server has been set");
} else {
Serial.println("Connection with server has been failed");
}
}
void sendData(){
client.print("TEst ard");
}
The problem was at A7 connection. It was connected via 10, 11 pins at Ethernet shield. But 10-13 pins are reserved by A7. It's just needed connect A7 vie 8, 9 or others pins.

Resources