Skip to content
Advertisement

I am have a problem reading some data using the serial.read() command

I am periodically reading the temperature and Humidity values from a DHT22 sensor in a green house tunnel.

The sensor is attached to a Arduino Pro Mini. The Pro Mini also has a nF24l01 transceiver attached to it, and the readings are transmitted to another nF24L01/Arduino Pro Mini in my office.

The Arduino is connected to a desktop PC via a USB serial cable.

The intention is to write the received Temperatue and Humidity readings to a file in a CSV format.

I am receiving all the data over the radio link which in-turn is feed to my PC via my USB port. I am running Node with a file called index.js.

Below is the code from the Arduino connected to the PC. It is the receiver side of the radio link.

JavaScript

Below is a screen shot of the serial output of the Arduino Pro Mini connected to my PC shown what is being received from the green house and what is being sent to the PC.

Arduino Serial port screen shot

The index2.js code is listed below

JavaScript

When I run node index2.js and look at the log.txt file I see that sometimes the temp/Hum values are listed as undefined as show in the screen shot below.

log.txt

After a bit of debugging I saw the following in the console.log() as show in the screen shot below.

Console.log() screen shot with program running.

So my problem is that every now and again, the fs.append can’t determine the value of sensorData.temperature and sensorData.humidity. The fs.append still appends a record to the log.txt file but the 1st two fields have undefined in them.

JavaScript

It appears that function tryParseJson(str) sometimes only gets some of the data and not the full JSON object. see code below,

JavaScript

I see that catch (e) gets called and my console.log(“JSON error”) gets printed.

I need some help to work out how to resolve this..

Advertisement

Answer

I did some changes to my code to check the contents of the const sensorData = tryParseJson(data) as shown below.

JavaScript

and then used a IF statement to append or not append to the log.txt file.

Everything is now working, however there is still one minor issue.

I noticed something in the log.txt file. If the value of the temp or humidity is say 25.00, then the file will have 25. will no trailing zero’s. This will not happen say if the temp is 25.4

if I check the values of sensorData in this line of code const sensorData = tryParseJson(data); the values are correct. They seem to change with fs.appendFile

Any idea why?

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement