How to translate a String or Char into a Byte or a uint16_t

Hi everyone,

I got stuck in a problem. I'm working with (example: 0xFF03) codes for my Infra Red light strips. In my code I want to Serial send the addres (example: 0x2) to turn my LED strips OFF. I got so far to get full Strings trough my serial monitor. So if I send: 0x2, the program would recognise the "0x" at the beginning. Also he turns the value after the "0x" into a "int" and with a snprintf() function he sticks the "0x" in front of it, but then it turns into a "char".

Can anyone help me with a function to write ether the "String" version or the "Char" version of my "0x2" code into a "Byte" or a "uint16_t"? See my code below...

#include <Arduino.h>
#include "PinDefinitionsAndMore.h"
#include <IRremote.h>

String data;
byte code = 0;

void setup() {
    Serial.begin(9600);
    for(int i=9; i<=12; i++){
      pinMode(i, OUTPUT);
    }
    IrSender.begin(IR_SEND_PIN, ENABLE_LED_FEEDBACK);
}

//IrSender.sendNEC(sAddress, 0x2, sRepeats);

uint16_t sAddress = 0xEF00;
uint8_t sRepeats = 0;
byte test = 0x2;

void loop(){
  while(Serial.available()){
    delay(3);
    char c = Serial.read();
    data += c;
  }
  if(data.length() > 0){
    Switch(data.substring(0, 1).toInt(), data.substring(1));

    if(data.substring(0, 2) == "0x"){
      //char val[20];
      //int input = data.substring(2).toInt();
      //snprintf(val, sizeof(val), "0x%X", input);
      Serial.println(val, HEX);
      IrSender.sendNEC(sAddress, (val, HEX), sRepeats);
    }   
    data = "";
  }
}

void Switch(int numb, String state){
  int pin = numb + 8;
  int intState;
  if(state == "on" || state == "ON"){
    digitalWrite(pin, HIGH);
  }
  if(state == "off" || state == "OFF"){
    digitalWrite(pin, LOW);
  }
}

I would suggest to study Serial Input Basics to handle this

For decimal numbers:

int atoi( const char *str );
long atol( const char *str );

For other bases, like hex:

long strtol( const char *str, char **str_end, int base );

If you set 'base' to 0 it will read the "0x" prefix and use hex.

If you pass a "char **str_end" it will set *str_end to point to the first character after the number.

1 Like

And that helps you decide if the parsing was ok as you can’t tell if a 0 from atol() or atoi() is because the number to read was 0 or the parsing failed.

So strtol() is a good option if that’s important

1 Like

Thanks mr. John Wasser. It worked for me!

It's actually always the better option in my opinion if one does not validate received data before converting :wink:

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.