Start a new topic

Serial variable issue

Hi, I have a Nextion connected to an arduino. As part of my code I use a timer within the Nextion to periodically write to the serial


print Code.val


I then read this in the arduino 


uint32_t incomingBytes;

  incomingBytes = Serial2.read();


This works perfectly until the value of the Nextion variable goes above 231. At this point the arduino seems to read seudo random numbers. The number it reads is constant but bares no resemblance to the Code.val. 


If on the arduino I use


Code.getValue(&incomingBytes);


I get the correct value but my flow on the arduino does not allow for this unfortunately.


Has anyone got any ideas?


cheers



Insufficient details. 

Arduino is to vague. Perhaps state what Arduino.


Code.getValue() to vague. Perhaps state from which library



I am using a mega 2560 with all your libraries. NexVariable.h is the specific one for getValue(). That bit works though, I think the issue I have is with the print Code.val in the timer event on the Nextion and the format it is outputting as 


uint32_t incomingBytes;

  incomingBytes = Serial2.read();


doesnt appear to read it correctly.


Thanks

Which version of the Arduino IDE?

1.8.8.0

I do not know if Arduino has yet fixed its issue with bit-shifting in uint32_t types for AVR branch.

I suspect, perhaps not from what you are reporting


Therefore, you may want to change the formula in NexHardware.h recvReturnNumber.cpp

to not use bit-shifting to build the 32-bit value from the buffer


Little endian order means

byte[1]+byte[2]*256+byte[3]*65536+byte[4]*16777216

using a (uint32_t) typecasting


This issue certainly did not effect all versions of the Arduino IDE

(upgrading to the latest and newest always has the most bugs)

Debugging remains in the user domain and responsibility


This remains a 100% guess this may help solve your issue

and is not required for all scenarios (thus not a library change required)

@Matthew 

uint32_t incomingBytes;
  incomingBytes = Serial2.read();

 This is not a valid method to read in a 32 bit value on Arduino.


A 32 bit value is read in as 4 separate bytes, meaning 4 separate but sequential calls to the .read() function. Then those bytes need bit shifting in the correct order to rebuild the resulting 32 bit value (incomingBytes). As Patrick states Little endian order.




1 person likes this

ok, I have seen my error!


  float Sent_Code;

  byte incomingBytes[4];

  Serial2.readBytes(incomingBytes, 4);

 

 

 

Sent_Code = incomingBytes[0] + incomingBytes[1] *256 + incomingBytes[2]*65536 + incomingBytes[3]*16777216;


working now.


Many thanks for help!

float is also wrong type

a float is eight bytes, and if working is only out of luck and will fail under other values

Login or Signup to post a comment