What does "expected unqualified id before 'if'" mean? - arduino

I am not getting why this is not working. I was researching on fixes and they say to add that "if" block in the void loop. Well, that was always in the void loop. Can you tell me the meaning and fix? Also, if there are more errors, please notify me so I can fix it. My code can be a little disorganized.
My code:
#include <LiquidCrystal.h>
LiquidCrystal lcd (7,8,9,10,11,12);
int pinDHT11 = 2;
SimpleDHT11 dht11;
void setup() {
Serial.begin(9600);
lcd.begin(16,2);
}
void loop() {
}
if (dht11.read(pinDHT11, &temperature, &humidity,data))
Serial.print("Read DHT11 failed");
return;
byte temperature = 0;
byte humidity = 0;
byte data[40] = {0};
if(dht11.read (pinDHT11, &temperature, &humidity, data))
return;
Serial.print("Read DHT11 failed");
Serial.println("=================================");
Serial.println("Sample DHT11...");
// read with raw sample data.
byte temperature = 0;
byte humidity = 0;
byte data[40] = {0};
}
Serial.print("Sample RAW Bits: ");
for (int i = 0; i < 40; i++) {
Serial.print((int)data[i]);
if (i > 0 && ((i + 1) % 4) == 0) {
Serial.print(' ');
}
}
Serial.println("");
Serial.print("Sample OK: ");
Serial.print((int)temperature); Serial.print("*C,");
Serial.print((int)humidity); Serial.println("%");
lcd.setCursor(0,0);
lcd.print((int)temperature);
lcd.setCursor(0,1);
lcd,print((int)humidity);
// DHT11 sampling rate is 1HZ.
delay(1000);

Your void loop is empty.
void loop() {
}
The error message is caused because you may not have code outside of functions. The only thing that is allowed outside functions are declarations.
There is a } without a matching {.
You also have two unconditional return statements.
, instead of .
lcd,print((int)humidity);

Related

Time delaying causes checksum errors in PMS5003 particulate matter data reading

I'm using the default code for a PMS5003 particulate matter sensor (with the RTC time features removed for now). However, I don't want to the data output to be on a constant loop; instead, I want to collect data only at certain intervals, for example every 10 seconds or every minute. To do this, I simply added a delay line at the end of the main loop. And with even the slightest delay of 1 second, I quickly run into checksum errors, although the code works fine without the delay.
#include <SoftwareSerial.h>
SoftwareSerial pmsSerial(2, 3);
void setup() {
// our debugging output
Serial.begin(9600);
// sensor baud rate is 9600
pmsSerial.begin(9600);
}
struct pms5003data {
uint16_t framelen;
uint16_t pm10_standard, pm25_standard, pm100_standard;
uint16_t pm10_env, pm25_env, pm100_env;
uint16_t particles_03um, particles_05um, particles_10um, particles_25um, particles_50um, particles_100um;
uint16_t unused;
uint16_t checksum;
};
struct pms5003data data;
void loop() {
if (readPMSdata(&pmsSerial)) {
// reading data was successful!
Serial.println();
Serial.println("Concentration Units (environmental)");
Serial.print("PM 1.0: "); Serial.print(data.pm10_env);
Serial.print("\t\tPM 2.5: "); Serial.print(data.pm25_env);
}
//This line causes issues
delay(1000);
}
boolean readPMSdata(Stream *s) {
if (! s->available()) {
return false;
}
// Read a byte at a time until we get to the special '0x42' start-byte
if (s->peek() != 0x42) {
s->read();
return false;
}
// Now read all 32 bytes
if (s->available() < 32) {
return false;
}
uint8_t buffer[32];
uint16_t sum = 0;
s->readBytes(buffer, 32);
// get checksum ready
for (uint8_t i=0; i<30; i++) {
sum += buffer[i];
}
/* debugging
for (uint8_t i=2; i<32; i++) {
Serial.print("0x"); Serial.print(buffer[i], HEX); Serial.print(", ");
}
Serial.println();
*/
// The data comes in endian'd, this solves it so it works on all platforms
uint16_t buffer_u16[15];
for (uint8_t i=0; i<15; i++) {
buffer_u16[i] = buffer[2 + i*2 + 1];
buffer_u16[i] += (buffer[2 + i*2] << 8);
}
// put it into a nice struct :)
memcpy((void *)&data, (void *)buffer_u16, 30);
if (sum != data.checksum) {
Serial.println("Checksum failure");
return false;
}
// success!
return true;
}
I suspect that the delay is causing the sensor and the Arduino to somehow desync. I also think it could possibly have to do with poor soldering of the sensor wires (though this wouldn't explain why the sensor works perfectly without the delay). Anyone know what's causing this issue, and how I might fix it?
Thanks.

Read Data from energy meter using Modbus RTU in Arduino Mega

Trying to read data from the energy meter. The code suppose to read voltage data and return but it's some random numbers are showing. Where am I making mistake in the code? Meter is conzerv EM6436 Energy Meter.
Tried:- 1) converting data in uint16_t fail
2) Reading different other registers fail
3) The energy meter showing correct data on modscan.
Energy Meter register Link
#include<ModbusMaster.h>
#define MAX485_DE 3
#define MAX485_RE_NEG 2
ModbusMaster node;
void preTransmission() {
digitalWrite(MAX485_RE_NEG, 1);
digitalWrite(MAX485_DE, 1);
}
void postTransmission()
{
digitalWrite(MAX485_RE_NEG, 0);
digitalWrite(MAX485_DE, 0);
}
void setup() {
pinMode(MAX485_RE_NEG, OUTPUT);
pinMode(MAX485_DE, OUTPUT);
// Init in receive mode
digitalWrite(MAX485_RE_NEG, 0);
digitalWrite(MAX485_DE, 0);
Serial.begin(19200,SERIAL_8E1);
//slave ID 1
node.begin(1, Serial);
Serial.println("Starting Modbus Transaction:");
node.preTransmission(preTransmission);
node.postTransmission(postTransmission);
}
uint16_t newData = 0;
float floatData;
double dataOne;
void loop() { // loop starts from here.
static uint32_t i;
uint8_t j, result;
uint16_t data[10];
i++;
result = node.readHoldingRegisters(3036,1);
Serial.println(" ");
if (result == node.ku8MBSuccess) {
Serial.print("\nSuccess, Received data 0: ");
for (j = 0; j < 1; j++) {
data[j] = node.getResponseBuffer(j);
floatData, dataOne= node.getResponseBuffer(j);
Serial.print("\nHex data:");
Serial.print(data[j], HEX);
Serial.print(" ");
Serial.print("\nDec data:");
Serial.print(data[j], DEC);
Serial.print("\nfloat data:");
Serial.print(floatData);
}
} else {
Serial.print("Failed, Response Code: ");
Serial.print(result, HEX);
Serial.println(" ");
delay(5000);
}
delay(1000);
}
Result:-
Success, Received data 0:
-> Hex data:648F
-> Dec data:25743
-> float data:25743.00βΈ®
As Bosz suggested in the comments above, the first thing you need to do is read two Modbus registers instead of 1. So change:
result = node.readHoldingRegisters(3036,1);
to:
result = node.readHoldingRegisters(3036,2);
Then you need to work with both registers and combine them to get the float you are looking for:
if (result == node.ku8MBSuccess) {
Serial.print("\nSuccess, Received data 0: ");
for (j = 0; j < 2; j++) {
data[j] = node.getResponseBuffer(j);
}
unsigned long temp = (unsigned long)data[0] + (unsigned long)data[1]*65536;
floatData = *((float*)&temp);
Serial.print(floatData);
}
This conversion should work for any FLOAT32 values on your device's register list.
This particular problem has been discussed in several places, you can see for instance here.

Can I temporarily disable Arduino Serial data receive?

I am working on a project and I encountered some problems.
I am using a DHT11 temperature sensor, an Arduino Uno and a TFT LCD display 2.2-inch model ITDB02-2.2.
What I want my project to do is to use 2 functioning modes for the sensor that I can select from the keyboard at the beginning of the program(one which is normal and one which will be used on special occasions)(so I need serial communication).
I noticed that the screen does not function if I start a serial communication at any rate so I used Arduino Serial.begin(9600) and Serial.end() for the mode selecting part of the program.
THE PROBLEM: My Arduino is still sending data through serial port even if I ended the serial communication and is looking like this:
I found out that Serial.end() function does not shut off serial communication but just the rate of communication. I am curious if you have any idea that I can use in order to get rid of the extra data, to neglect it before the computer receives it.
I`m stuck. I thought that interruptions would be a solution but they are not as far as I researched on the internet.
My ARDUINO CODE:
#include <SimpleDHT.h>
#include <UTFT.h>
UTFT myGLCD(ITDB22,A5,A4,A3,A2);
SimpleDHT11 dht11;
// Declare which fonts we will be using
extern uint8_t BigFont[];
//dht sensor data pin
int dataPinSensor1 = 12;
char mode;
int del;
void setup()
{
Serial.begin(9600);
Serial.print("Select functioning mode");
mode=SensorModeSelect(mode);
Serial.end();
pinMode(12, INPUT);
}
void loop()
{
if(mode=='1') {
FirstFuncMode(dataPinSensor1);
}
if(mode=='2') {
SecondFuncMode(dataPinSensor1,del);
}
delay(10);
}
char SensorModeSelect(char in)
{
char mode='0';
while(mode=='0') {
if(Serial.available() > 0) {
mode=Serial.read();
}
}
if (mode == '1') {
Serial.print("\nMOD1 SELECTED: press t key to aquire data \n");
}
if (mode == '2') {
Serial.print("\nMOD2 SELECTED: press q if you want to quit auto mode \n");
Serial.print("Select the data aquisition period(not smaller than 1 second) \n");
}
return mode;
}
int DataAqPeriod()
{
int del=0;
while(del==0) {
while(Serial.available() > 0) {
//Get char and convert to int
char a = Serial.read();
int c = a-48;
del *= 10;
del += c;
delay(10);
}
}
del*=1000;
return del;
}
void FirstFuncMode(int dataPinSensor1)
{
byte temperature = 0;
byte humidity = 0;
int err = SimpleDHTErrSuccess;
bool DispCond=false;
Serial.begin(9600);
delay(1500);
if (Serial.read() == 't' ) {
DispCond=true;
//read temperature and compare it with an error value
if((err = dht11.read(dataPinSensor1, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
Serial.print("unreliable measurement or unselected functioning mode");
}
byte f = temperature * 1.8 + 32;
Serial.print((int)temperature);
Serial.print(" *C, ");
Serial.print((int)f);
Serial.print(" *F, ");
Serial.print((int)humidity);
Serial.println(" H humidity");
delay(1500);
}
Serial.end();
if(DispCond==true) {
//Setup the LCD
myGLCD.InitLCD();
myGLCD.setFont(BigFont);
//print value on LCD
displayNoInit((int)temperature,(int)humidity);
}
}
void SecondFuncMode(int dataPinSensor1,int del)
{
bool q=false;
byte temperature = 0;
byte humidity = 0;
int err = SimpleDHTErrSuccess;
Serial.begin(9600);
del=DataAqPeriod();
Serial.end();
//Setup the LCD
myGLCD.InitLCD();
myGLCD.setFont(BigFont);
while(q==false) {
Serial.begin(9600);
//read temperature and compare it with an error value
if((err = dht11.read(dataPinSensor1, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
Serial.print("unreliable measurement or unselected functioning mode \n");
}
float f = temperature * 1.8 + 32;
Serial.print((int)temperature);
Serial.print(" *C, ");
Serial.print((int)f);
Serial.print(" *F, ");
Serial.print((int)humidity);
Serial.println(" H humidity");
delay(del);
if(Serial.read() == 'q')
q=true;
Serial.end();
displayNoInit((int)temperature,(int)humidity);
delay(10);
}
}
void displayNoInit(int temperature,int humidity)
{
//effective data display
myGLCD.clrScr();
myGLCD.setColor(255, 255, 0);
myGLCD.setBackColor(10,10,10);
myGLCD.print(" Temperature ", CENTER, 10);
myGLCD.setColor(254, 254, 254);
myGLCD.printNumI(temperature, CENTER, 45);
myGLCD.setColor(255, 255, 0);
myGLCD.print("C ", RIGHT, 45);
myGLCD.print("Relative Hum.", CENTER, 90);
myGLCD.setColor(204, 245, 250);
myGLCD.printNumI(humidity, CENTER, 120);
myGLCD.print("%", RIGHT, 120);
}
You are correct in the definition that Serial.end() does not disable the serial monitor, only the interrupts. After calling Serial.end() you can disable the serial monitor like so.
#include <avr/io.h>
// Save status register, disable interrupts
uint8_t oldSREG = SREG;
cli();
// Disable TX and RX
cbi(UCSRB, RXEN);
cbi(UCSRB, TXEN);
// Disable RX ISR
cbi(UCSRB, RXCIE);
// Flush the internal buffer
Serial.flush();
// Restore status register
SREG = oldSREG;

Serial communication on Arduino

I have an assignment for school where I need to turn on a led with the serial message #ON%, and turn the led off with #OFF%. The # and % are the identifiers for the correct string. So I made this code:
(bericht means message in Dutch)
String readString = "";
int recievedCharacter;
String bericht = "";
int ledPin = 6;
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
pinMode(ledPin, OUTPUT);
}
void loop()
{
while (Serial.available() > 0)
{
delay(4);
char readChar = (char) Serial.read(); // 'Convert' to needed type
bericht += + readChar; // concatenate char to message
}
if(bericht.startsWith("#"))
{
if(bericht == "#ON%")
{
Serial.println(bericht);
Serial.println("goed");
digitalWrite(ledPin, HIGH);
//message = "";
}
if(bericht == "#OFF%")
{
Serial.println("goed");
digitalWrite(ledPin, LOW);
//message = "";
}
}
}
The problem is the program will never get into the if(bericht == "#ON%") section...
Sorry if this is a silly question but with a lot of googling I just can't figure it out...
The problem is here:
bericht += + readChar; // concatenate char to message // XXX '+ char' => int
this actually appends an integer to the message. Remove the +:
bericht += readChar; // concatenate char to message // Goed!

Arduino : Check byte array for chars one at a time

I communicate with Arduino via Serial using a program that sends a series of bytes.
In order for the Arduino to realize it is receiving a message rather than junk, I have tagged the start of my byte array with the chars 'S' 'T' 'A' 'R' 'T'. After this will eventually follow a series of bytes that will be assigned to internal variables (not yet implemented).
The Arduino must read each byte sequentially and compare it to the byte array and if all are present in the correct order it will continue with the next part of the program, otherwise it will should discard current byte and wait for more bytes to arrive.
I am trying to implement it in the most efficient and readable way rather than using a series of nested if statements.
So far I have got:
byte inByte = 0;
byte handShake[] = {'S','T','A','R','T'};
void setup() {
Serial.begin(9600);
}
void loop()
{
while (Serial.available())
{
for (int x =0; x < sizeof(handShake) ; x++)
{
inByte = Serial.read();
Serial.println(x);
if (inByte == handShake[x])
{
if (x == (sizeof(handShake)-1)) {setArduino();}
}
else break;
}
}
}
void setArduino () {
Serial.println("Ready To Set Parameters");
}
This however doesn't seem to get past the second byte and I'm not sure why.
Worked it out :
Here is the answer:
byte inByte = 0;
char handShake[] = {'S','T','A','R','T'};
void setup() {
Serial.begin(9600);
}
void loop()
{
while (Serial.available())
{
for (int x =0; x < sizeof(handShake) ; x++)
{
inByte = Serial.read();
Serial.println(x);
if (inByte == handShake[x])
{
if (x == (sizeof(handShake)-1)) {setArduino();}
while(!Serial.available()) {delay(1);}
}
else {break;}
}
}
}
void setArduino () {
Serial.println("Ready To Set Parameters");
}
This may not be the most efficient way perhaps, but I can't see a problem with it currently.
Better answer : This allows the rest of the loop to iterate while waiting for the message to finish and if the full handshake message isn't received the counter will reset.
byte inByte = 0;
char handShake[] = {'S','T','A','R','T'};
int messageIndex = 0;
void setup() {
Serial.begin(9600);
}
void loop()
{
while (Serial.available())
{
inByte = Serial.read();
Serial.println(messageIndex);
if (inByte == handShake[messageIndex])
{
messageIndex++;
if (messageIndex == sizeof(handShake)) {messageIndex = 0; setArduino();}
}
else {messageIndex=0;}
}
// Other code while waiting for message to finish
Serial.println("tick");
}
void setArduino () {
Serial.println("Ready To Set Parameters");
}
You could try to calculate your message. CRC is old and good solution. I use it and it works perfect for me. I am not sure what kind of device are you communicating with.
//define
const uint32_t Polynomial = 0xEDB88320;
const uint16_t NumBytes = 256;
uint8_t data[NumBytes];
/// compute CRC32
uint32_t crc32_bitwise(const void* data, uint16_t length, uint32_t previousCrc32 = 0)
{
uint32_t crc = ~previousCrc32; // same as previousCrc32 ^ 0xFFFFFFFF
uint8_t* current = (uint8_t*) data;
while (length--)
{
crc ^= *current++;
for (uint8_t j = 0; j < 8; j++)
{
uint8_t lowestBit = crc & 1;
crc >>= 1;
if (lowestBit)
crc ^= Polynomial;
}
}
return ~crc; // same as crc ^ 0xFFFFFFFF
}
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}
when you need to calculate CRC
uint32_t crc = crc32_bitwise(data_bytes, sizeof(data_bytes));
data_bytes is byte array.
Then you can get all settings or message in byte data[x] and calculate CRC. Then you can add CRC to the message and send message byte data[x+sizeof(CRC)]
P.S. Use byte instead of int. For ex. for(byte x =0; x<sizeof(handShake); x++)

Resources