arduinotype-conversionarduino-due

Convert "String" above 255 to exact "Integer" or "Long" type in Arduino IDE


Appreciate your time.

I am trying to convert "String" read from serial port in serialEvent() of Arduino IDE to integer values with exact representation.

For eg, if String myString = 200 then int myInt should be 200.

I have been somewhat successful but unable to convert String to exact int representation beyond 255.

Solutions I have tried:

1) used .toInt() function in Arduino.

2) used "atoi" and "atol" functions.

3) Serial.parseInt() in loop().

All of these methods start recounting from 0 after every 255 values.

I can't use parseInt since it only works inside loop(). My application requires to store variable value permanently until another value is given through port. For this Arduino Due's flash memory has been used.

The memory storing code seems to work only inside serialEvent().

Code snippet is as below:

#include <stdlib.h>
#include <DueFlashStorage.h>
DueFlashStorage memory;

String x = " ";
int x_size;
int threshold;

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

void loop{
  Serial.println(memory.read(0));
}

void serialEvent(){

  while(Serial.available()){

    x = Serial.readStringUntil('\n');

    x_size = x.length();
    char a[x_size+1];

    x.toCharArray(a, x_size+1);

    threshold = atoi(a);

    memory.write(0, threshold);
  }
}

Solution

  • I solved the problem using highByte and lowByte functions of Arduino. Works flawlessly.

    #include <DueFlashStorage.h>
    DueFlashStorage m;
    byte a1,a2;
    int val;
    
    void setup() {
       
     Serial.begin(115200);           //start the serial communication
    }
    
    void loop()
    {
     
     if (Serial.available()>0)
        {  
    
         val = Serial.parseInt();     //read the integer value from series
    
        if(val>0){
         a1 = highByte(val);          //get the higher order or leftmost byte
         a2 = lowByte(val);           //get the lower order or rightmost byte
        
         m.write(0,a1);              //save in arduino due flash memory address 0
         m.write(1,a2);              //save in arduino due flash memory address 1
    
        }
      
      int myInteger;
    
       myInteger = (m.read(0)*256)+m.read(1);     //convert into the true integer value
                                    
       Serial.println(myInteger); 
          
     }