Arduino error expected primary-expression before ‘)’ token - arduino

I was running this code on a nodemcu board I kept getting errors in
//Google Assistant Home Automation
#include < ESP8266WiFi.h >
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#define Relay1 D1
#define Relay2 D2
#define Relay3 D3
#define Relay4 D4
#define WLAN_SSID " ---- " // Your SSID
#define WLAN_PASS " ---- " // Your password
/************************* Adafruit.io Setup
*********************************/
#define AIO_SERVER "io.adafruit.com" //Adafruit Server
#define AIO_SERVERPORT 1883
#define AIO_USERNAME " ----- " // Username
#define AIO_KEY " ------------ " // Auth Key
//WIFI CLIENT WiFiClient client;
Adafruit_MQTT_Client mqtt(& client, AIO_SERVER, AIO_SERVERPORT,
AIO_USERNAME, AIO_KEY);
Adafruit_MQTT_Subscribe Light1 = Adafruit_MQTT_Subscribe(& mqtt,
AIO_USERNAME"/feeds/Relay1"); // Feeds name should be same everywhere
Adafruit_MQTT_Subscribe Light2 = Adafruit_MQTT_Subscribe(& mqtt,
AIO_USERNAME "/feeds/Relay2"); Adafruit_MQTT_Subscribe Light3 =
Adafruit_MQTT_Subscribe(& mqtt, AIO_USERNAME "/feeds/Relay3");
Adafruit_MQTT_Subscribe Light4 = Adafruit_MQTT_Subscribe(& mqtt,
AIO_USERNAME "/feeds/Relay4");
void MQTT_connect();
void setup() {
Serial.begin(115200);
pinMode(Relay1, OUTPUT); pinMode(Relay2, OUTPUT);
pinMode(Relay3, OUTPUT); pinMode(Relay4, OUTPUT);
// 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());
mqtt.subscribe(& Light1); mqtt.subscribe(& Light3); mqtt.subscribe(& Light2); mqtt.subscribe(& Light4);
}
void loop() {
MQTT_connect();
Adafruit_MQTT_Subscribe * subscription; while ((subscription =
mqtt.readSubscription(20000))) {
if (subscription == & Light1) {
Serial.print(F("Got: "));
Serial.println((char *)Light1.lastread);
int Light1_State = atoi((char *)Light1.lastread);
digitalWrite(Relay1, Light1_State);
}
if (subscription == & Light2) {
Serial.print(F("Got: "));
Serial.println((char *)Light2.lastread);
int Light2_State = atoi((char *)Light2.lastread);
digitalWrite(Relay2, Light2_State);
}
if (subscription == & Light3) {
Serial.print(F("Got: "));
Serial.println((char *)Light3.lastread);
int Light3_State = atoi((char *)Light3.lastread);
digitalWrite(Relay3, Light3_State);
}
if (subscription == & Light4) {
Serial.print(F("Got: "));
Serial.println((char *)Light4.lastread);
int Light4_State = atoi((char *)Light4.lastread);
digitalWrite(Relay4, Light4_State);
}
}
}
void MQTT_connect() {
int8_t ret;
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) {
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000);
retries--;
if (retries == 0) {
while (1);
}
} Serial.println("MQTT Connected!");
}
It also popped an error in the first few lines #define Relay1 D1
https://i.stack.imgur.com/yyfqP.png
after I deleted those D1, D2, D3, and D4 I got error
expected primary-expression before ')' tokenerror
for this line
digitalWrite(Relay4, Light4_State);

Related

I want to make LoRa receiver where LoRa messages will be sent to Firebase, but I always fail

Here's my code. I failed so many times. I managed to send the message between the LoRa receiver and the LoRa transmitter, but failed to upload to Firebase. It's said that I need primary expression, but when I look at other code and follow that, it doesn't use the code recommended by Arduino IDE.
I'm using and ESP32 and RFM95 SX1276.
#include <SPI.h>
#include <LoRa.h>
#include <WiFi.h>
#include <WiFiClient.h>
const char* ssid = "*******";
const char* password = "******";
#include <Firebase.h>
#define FIREBASE_HOST "************************"
#define FIREBASE_AUTH "************"
#define ss 5
#define rst 14
#define dio0 2
#define BAND 915E6
// Initialize variables to get and save LoRa data
int rssi;
String loRaMessage;
String temperature;
String humidity;
String readingID;
String suhu;
String lembab;
FirebaseData data;
String processor(const String& var){
//Serial.println(var);
if(var == "TEMPERATURE"){
return temperature;
}
else if(var == "HUMIDITY"){
return humidity;
} else if (var == "RRSI") {
return String(rssi);
}
return String();
}
void startLoRA(){
int counter;
LoRa.setPins(ss, rst, dio0);
while (!LoRa.begin(BAND) && counter < 10) {
Serial.print(".");
counter++;
delay(500);
}
if (counter == 10) {
// Increment readingID on every new reading
Serial.println("Starting LoRa failed!");
}
Serial.println("LoRa Initialization OK!");
}
void setup(){
Serial.begin(115200);
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
//WIFI
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() !=WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("Connected to the Network");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
startLoRA();
}
void loop(){
// Check if there are LoRa packets available
int packetSize = LoRa.parsePacket();
if (packetSize){
String LoRaData = LoRa.readString();
while (LoRa.available()){
Serial.print((char)LoRa.read());
}
// Get RSSI
rssi = LoRa.packetRssi();
Serial.print("With RSSI ");
Serial.println(rssi);
int pos1 = LoRaData.indexOf('/');
int pos2 = LoRaData.indexOf('&');
readingID = LoRaData.substring(0,pos1);
temperature = LoRaData.substring(pos1 + 1, pos2);
humidity = LoRaData.substring(pos2 + 1, LoRaData.length());
if (readingID =="001"){
suhu= temperature;
Serial.print(F("Suhu :"));
Serial.println(suhu);
Serial.println(F("C"));
lembab= humidity;
Serial.print(F("Kelembaban : "));
Serial.print(lembab);
Serial.println("%");
String fbsuhu = String (suhu) + String("C");
String fblembab = String (lembab) + String("%");
Firebase.setString (FirebaseData, "Suhu :", fbsuhu);
Firebase.setString (FirebaseData, "Lembab :", fblembab);
}
}
}
As far as I understand the Firebase library, it's Firebase.setString(key, value);. So only two arguments. You are passing three.

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

Unable to establish connection to mosquitto broker from Arduino+ESP8266

I am using Arduino Uno and ESP8266 for WIFI connectivity. My Laptop on which mosquitto broker is running and Arduino(through ESP8266) is are both connected to wifi network. But I am unable to establish a connection to mqtt server.
I am using the follwing code.
#define FASTLED_INTERNAL
#include <SoftwareSerial.h>
#include <DHT.h>
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>
#include <PubSubClient.h>
#include <FastLED.h>
#define DHTPIN 2
#define DHTTYPE DHT11
#define ESP_RX 9
#define ESP_TX 8
#define WIFI_AP "Anurag"
#define WIFI_PASSWORD "qwerty12345"
#define NUM_LED 64
#define DATA_PIN 5
#define CLOCK_PIN 13
static const int RXPin = 4, TXPin = 3;
static const uint32_t baudRate = 9600;
static const int rainSensorMin = 0;
static const int rainSensorMax = 1024;
WiFiEspClient espClient;
PubSubClient mqttClient(espClient);
IPAddress broker(192,168,43,235);
SoftwareSerial ESP8266(ESP_RX, ESP_TX);
DHT dht(DHTPIN, DHTTYPE);
int status = WL_IDLE_STATUS;
char *ID = "uno";
char *TOPIC = "weatherStats";
int AT_cmd_time;
boolean AT_cmd_result = false;
CRGB leds[NUM_LED];
void setup() {
//pinMode(13, OUTPUT);
//FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LED);
Serial.begin(9600);
//ss.begin(baudRate);
initWiFi();
dht.begin();
mqttClient.setServer(broker,1883);
Serial.println("GPS, DHT11, and, Raindrop detector started.");
}
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);
}
Serial.println("Connected to AP");
}
delay(3000);
float h = dht.readHumidity();
float t = dht.readTemperature();
int rainReading = analogRead(A0);
int range = map(rainReading, rainSensorMin, rainSensorMax, 0, 2);
if(!mqttClient.connected()){
reconnect_mqtt();
}
mqttClient.loop();
mqttClient.publish(TOPIC,"one step forward");
//Serial.println("Satellites: " + String(gps.satellites.value()));
if (!isnan(h) || !isnan(t))
Serial.print("Temparture: " + String(t) + "°C | " + " Humidity: " + String(h) + " | ");
else {
Serial.println("Failed to obtain temparature and humidity data");
}
switch (range) {
case 0:
Serial.print("Rain Warning : 1");
break;
case 1:
Serial.print("Rain Warning : 0");
break;
}
Serial.println(" | Lat: 22.716191217468406 Lon: 72.44229199663788");
}
void initWiFi(){
ESP8266.begin(9600);
WiFi.init(&ESP8266);
// check for the presence of the shield
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue
while (true) {
}
}
// attempt to connect to WiFi network
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);
}
}
void reconnect_mqtt(){
while(!mqttClient.connected()){
Serial.println("Attempting MQTT Connection");
if(mqttClient.connect(ID)){
Serial.println("MQTT connection established.");
Serial.print("Publishing to: ");
Serial.println(TOPIC);
}
else{
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
Runnig this code I keep getting output "try again in 5 seconds". Please help.

Arduino MQTT disconnect

I have a ESP32 board with 2 relays and a DHT22 sensor and the bellow code in Arduino running on the ESP32
MQTT Broker is running on Pi4 with mosquitto and node-red dashboard.
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
#define DHTTYPE DHT22
const char* ssid = "MY SSID";
const char* password = "1234";
const char* mqtt_server = "192.168.1.118";
WiFiClient espClient;
PubSubClient client(espClient);
const int DHTPin = 14;
const int lamp = 25;
const int lamp1 = 26;
DHT dht(DHTPin, DHTTYPE);
long now = millis();
long lastMeasure = 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);
delay(1000);
WiFi.disconnect();
delay(1000);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
String message;
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
char c = (char)payload[i];
message += c;
}
Serial.println();
if ((char)payload[0] == '0' || message == "false") {
digitalWrite(lamp, HIGH);
delay(100);
digitalWrite(lamp1, LOW);
Serial.println("lamp, HIGH si lamp1, LOW");
} else if ((char)payload[0] == '1' || message == "true") {
digitalWrite(lamp1, HIGH);
delay(100);
digitalWrite(lamp, LOW);
Serial.println("lamp, LOW si lamp1, HIGH");
} else if ((char)payload[0] == '2') {
digitalWrite(lamp, HIGH);
digitalWrite(lamp1, HIGH);
Serial.println("lamp, LOW si lamp1, LOW > STOP");
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Subscribe or resubscribe to a topic
// You can subscribe to more topics (to control more LEDs in this example)
client.subscribe("room/lamp");
client.subscribe("room/lamp1");
} 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(lamp, OUTPUT);
pinMode(lamp1, OUTPUT);
pinMode(LED,OUTPUT);
dht.begin();
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
// For this project, you don't need to change anything in the loop function. Basically it ensures that you ESP is connected to your broker
void loop() {
if (!client.connected()) {
reconnect();
}
if(!client.loop())
client.connect("ESP8266Client");
now = millis();
// Publishes new temperature and humidity every 30 seconds
if (now - lastMeasure > 5000) {
lastMeasure = now;
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
// float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
//if (isnan(h) || isnan(t) || isnan(f))
if (isnan(h) || isnan(t)){
Serial.println("Failed to read from DHT sensor!");
return;
}
// Computes temperature values in Celsius
float hic = dht.computeHeatIndex(t, h, false);
static char temperatureTemp[7];
dtostrf(t, 6, 2, temperatureTemp);
static char test[7];
dtostrf(hic, 6, 2, test);
static char humidityTemp[7];
dtostrf(h, 6, 2, humidityTemp);
client.publish("room/temperature", temperatureTemp);
client.publish("room/humidity", humidityTemp);
client.publish("room/test", test);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t Temperature: ");
Serial.print(t);
Serial.print(" *C ");
//Serial.print(f);
Serial.print(" *F\t Heat index: ");
Serial.print(hic);
Serial.println(" *C ");
delay(500);
digitalWrite(LED,HIGH);
delay(500);
digitalWrite(LED,LOW);
}
}
The 2 relays are controlling a window in my bathroom. If I plug the ESP32 to power all is working, and I can open/close the window and sensor readings are ok.
But after ~24hours I can still see realtime sensor readings but when I try to open/close the window nothing is happening. On the MQTT broker I can see the mqtt messages but nothing is happening.
room/lamp1 1
room/lamp1 1
room/lamp 0
room/lamp 0
room/lamp 0
room/lamp 0
room/lamp 0
room/lamp 0
room/temperature 24.00
room/humidity 29.10
room/test 23.22
room/lamp 0
room/lamp 0
room/lamp 2
room/lamp1 2
room/lamp 2
room/lamp1 2
room/lamp 2
room/lamp1 2
room/lamp 2
Any suggestions.

ESP32 Radio - How to improve the sound quality?

I got this ESP32 Radio source code from this site.
I love it because its very simple radio and works fine on ESP32.
But sometime the sound is very choppy.
I suspect maybe because a lack of proper buffers, but I don't know how to fix it.
The code:
/*
WITHOUT OLED, only ESP32 & VS1053
VS1053 - connections detail
XRST = EN (D3)
MISO = D19
MOSI = D23
SCLK = D18
VCC = 5V / 3.3 V
Gnd = Gnd
*/
#include <VS1053.h> //ESP_VS1053_Library
#include <Preferences.h> //For reading and writing into the ROM memory
Preferences preferences;
unsigned int counter,old_counter,new_counter;
#include "helloMp3.h"
#include <WiFi.h>
#include <HTTPClient.h>
#include <esp_wifi.h>
char ssid[] = "SSID"; // your network SSID (name)
char pass[] = "PASSWORD"; // your network password
char *host[7] = {"184.95.47.178","us4.internet-radio.com","us3.internet-radio.com","us3.internet-radio.com","174.36.206.197","sj64.hnux.com","uk7.internet-radio.com"};
char *path[7] = {"/","/","/live.m3u","/","/","/","/"};
int port[7] = {9328,8266,8371,8297,8000,80,8226};
char *sname[7] = {"Love-Radio-USA","Smooth-Jazz-Florida","Best-Rock-Radio","Country-Radio","Venice-Classic-Radio","Smooth-Jazz-Global","UK-Top-40"};
int change=13;
bool x=true;
int status = WL_IDLE_STATUS;
WiFiClient client;
uint8_t mp3buff[32]; // vs1053 likes 32 bytes at a time
// Wiring of VS1053 board (SPI connected in a standard way)
#define VS1053_CS 32 //32
#define VS1053_DCS 33 //33
#define VS1053_DREQ 35 //15
#define VOLUME 100 // volume level 0-100
VS1053 player(VS1053_CS, VS1053_DCS, VS1053_DREQ);
void setup () {
pinMode(change,INPUT_PULLUP);
// initialize SPI
Serial.begin(115200);
delay(500);
// initialize SPI bus;
SPI.begin();
// initialize VS1053 player
player.begin();
// player.switchToMp3Mode(); // optional, some boards require this
player.setVolume(VOLUME);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
// display.drawString(0,15," Connecting..");
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
Serial.print("IP address:");
Serial.println(WiFi.localIP());
preferences.begin("my-app", false);
counter = preferences.getUInt("counter", 0);
old_counter=counter;
Serial.printf("Current counter value1: %u\n", counter);
//if(counter>0) counter=0;
//Serial.printf("Current counter value2: %u\n", counter);
delay(100);
player.playChunk(hello2, sizeof(hello2)); //VS1053 is wake up & running
station_connect(counter);
}
void loop() {
if (client.available() > 0) {
uint8_t bytesread = client.read(mp3buff, 32);
player.playChunk(mp3buff, bytesread);
}
if(digitalRead(change)==0 and x==true){
x=false;
counter = counter+1;
if(counter>6) counter=0;
preferences.putUInt("counter",counter);
new_counter=counter;
Serial.printf("Old_Counter: %u\n",old_counter);
Serial.printf("New_Counter: %u\n",new_counter);
Serial.printf("Set counter to new_value: %u\n", counter);
delay(500);
if(old_counter != new_counter) {
player.softReset();
x=true;
station_connect(new_counter);
preferences.putUInt("counter",new_counter);
}
}
}
void station_connect (int station_no ) {
if (client.connect(host[station_no],port[station_no]) ) {
Serial.println("Connected now");
}
Serial.print(host[station_no]);
Serial.println(path[station_no]);
Serial.println(sname[station_no]);
client.print(String("GET ") + path[station_no] + " HTTP/1.1\r\n" +
"Host: " + host[station_no] + "\r\n" +
"Connection: close\r\n\r\n");
}
How to improve the sound quality? Please help
Thanks for all the helpers! :)

Resources