Saving data from serial monitor to variable

Hi guys,

I am attempting to communicate with a sensor i purchased online and due to the help i recieved on this forum i was able to use a MAX485 to recieve a RS485 hex response from the sensor.

The issue now is that the data is sent concurrently e.g 1A then 2A then 3B… so on.

I need to be able to store this data in a variable (array maybe?) so that i can acess it later in the code and read the value then display it onto an LCD screen.

i tried using an unsigned long however i need to be able to store double 0 and 0 values… e.g 1A then 00 then 04

how can i do this?

i know that the length will always be 7 e.g 1A 00 1B 01 1C 02 1D

Here is the code i tried . The data is supposed to be ‘1A 00 1B 01 1C 02 1D’
The serial monitor showed ‘1A01B11C21D0’

unsigned long val;


void setup()
{
  Serial.begin(9600);            
}

void loop()
{    
   
    val = Serial.read();
    delay(500); 
    if (val != -1) //only did this because the when serial avaliable didnt seem to work.
    {
      Serial.print(val,HEX);
    }
}

thankyou!!

First of all Serial.available() does work perfectly. So try again because you are going to need it. Secondly don't be confused because the print function doesn't print leading zeros, even with HEX. Third, yes you should put them in an array (I suggest data type of 'uint8_t'). So make an array and stuff them in sequentially.

aarg:
Secondly don't be confused because the print function doesn't print leading zeros, even with HEX.

so does that mean even though it isnt printing it, i can store it with the leading zeros?

aarg:
Third, yes you should put them in an array (I suggest data type of 'uint8_t'. So make an array and stuff them in sequentially.

if it isnt too much trouble would you be able to give me an example of how to do this? i havent used arrays before :confused:

Isaac258:
so does that mean even though it isnt printing it, i can store it with the leading zeros?

if it isnt too much trouble would you be able to give me an example of how to do this? i havent used arrays before :confused:

You can not store blanks (nothings) in a computer. The byte is made of 8 bits that are either set or cleared. When you store 00000000, it can represent any base. It is only when you retrieve and process it, that it has any textual representation like "00" or "0". So "store with leading zeroes" is an oxymoron.

Here is the documentation on Arrays

What sensor are you using? Please, provide a link to your sensor. Also, are you using UNO or MEGA?