Convert String to byte - getting 'invalid cast; error

I need help. I am trying to convert a String of numbers into individual bytes, but I am getting an "Invalid cast from type 'arduino::String' to type 'byte {aka unsigned char}" error message. The Arduino doccumentation for type conversion says I can use byte() to convert any value type to byte, so I don't understand why it is "invalid".

I understand that using Strings can lead to a whole host of issues. The main reason I am using them is because the code I copied and adapted used them. So, if there is a way I can avoid using them, feel free to suggest. But, I warn you, I am a complete novice (approx 3 weeks of experience), and every mention of char* arrays has left me more confused than before. So, dumb it down for me.

To (attempt to) explain the purpose of the code: this code is for what I am calling motorUnit. I will have another Arduino (controlUnit) that is acting as WiFi Access Point and Server Host. This controlUnit will send both commandWord and variableRequest messages. The syntax of the messages is either commandWord:xxxxxxxxxxx (where each x is a 0 or 1), or <motorUnit_x:"variable"?> The return message syntax will be <motorUnit_x:"variable":"value"> (where x is the board number, in this case 0, "variable" will be the specific variable that is being requested, such as shutterStatus, batteryLevel, signalStrength, etc, and value is the value that is returned from the sensors - not yet added).

The problem I am having is I am reading the incomingData from the controlUnit as a String so that I can use the indexOf() function to separate the incomingData into commandType (either commandWord or variableRequest) and commandValue. I am then trying to conver the command Value into a byte array so that each of the motorUnits (there will be 11) can read the byte that is specific to it.

Code and error is posted below.

G:\My Drive\arduinoProjects\testMotorUnit_2.0wButton\testMotorUnit_2.0wButton.ino: In function 'void loop()':
G:\My Drive\arduinoProjects\testMotorUnit_2.0wButton\testMotorUnit_2.0wButton.ino:73:62: error: invalid cast from type 'arduino::String' to type 'byte {aka unsigned char}'
commandWord[i] = byte(commandValue.substring(i));
^

exit status 1

Compilation error: invalid cast from type 'arduino::String' to type 'byte {aka unsigned char}'

/*
Motor Units

need to change Unit number for each one
*/

#include <Arduino.h>
#include <WiFiNINA.h>
#include "arduino_secrets.h"
#include "utility/wifi_drv.h" //only needed for onboard led.
//also will need battery libraries

//variables for network information
const char ssid[] = APssid;
const char pass[] = APpass;
IPAddress server(192,168,4,1);
unsigned long previousMillis = 0;
int interval = 5000;

//variable for motorUnits
const byte motorUnits = 11;
byte commandWord[motorUnits];
const String variableRequest[] = {"shutterStatus", "batteryLevel", "signalStrength", "tempSensor"};
float motorUnitStatus[sizeof(variableRequest)];

//variables for client information
String clientName = "motorUnit_0";                                                                                                       //This is the name of this board. It needs to be changed for each board (0, 1, 2, 3, etc).
WiFiClient client;

//variables for LED testing
const int ledPin = 2;
const int onboardLEDRed = 25;
const int onboardLEDGreen = 26;
const int onboardLEDBlue = 27;

//variables for Serial Monitor testing



String ServerMessage; // not sure what this is for.... it is never called in the code I am copying


void setup() {
  Serial.begin(9600);
  Serial.print("Begin setup() function | Line: "); Serial.println(__LINE__);
  Serial.print("Connecting to AP network | Line: "); Serial.println(__LINE__);
  WiFi.begin(ssid, pass);                                                                                                               //I might need to use WiFi.config() to change the ip address of each board before calling WiFi.begin(). But, I am going to leave it as is for now and see what happens. It might all work out.
  while(WiFi.status() != WL_CONNECTED){
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to AP network with IP Address: "); Serial.print(WiFi.localIP()); Serial.print(" | Line: "); Serial.println(__LINE__);
}


// The clientRequest() from the control board uses the following syntax: either <commandWord:xxxxxxxxxxx>, or <motorUnit_x:"variable"?> | It is expecting no response for commandWord and a response for motorUnit_x with the following syntax: <motorUnit_x:"variable":"value" | x is an int that changes for each function, "variable" is the variable type that is requested (shutterStatus, batteryLevel, etc), and value is a float returned from the sensors.
void loop() {
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval) {
    if(WiFi.status() == WL_CONNECTED){
      Serial.print("Connecting to Server | Line: "); Serial.println(__LINE__);
      client.connect(server, 80);
      while(client.connected()){
        Serial.print("Connected to Server | Line: "); Serial.println(__LINE__);
        String incomingData = client.readStringUntil('\r'); //read String until carriage return
        if(incomingData != "\0"){
          Serial.print("Received data from Server: "); Serial.print(incomingData); Serial.print(" | Line: "); Serial.println(__LINE__);
          int index = incomingData.indexOf(':');
          String commandType = incomingData.substring(0, index);
          String commandValue = incomingData.substring(index +1);
          if(commandType == "commandWord"){
            for(int i=0; i<commandValue.length(); i++){
              commandWord[i] = byte(commandValue.substring(i, i++));
            }
            for(int i=0; i<sizeof(commandWord); i++){
              Serial.print(commandWord[i]);
            } 
          } else if(commandType == clientName){

          }
        }
      }
    }
  }
}

This is always an empty string, because i++ increments after the value is taken: both arguments have the same value. In a similar situation, you might use i + 1 -- the for loop already increments i.

Regardless, the result is another String: an object that you cannot simply convert to a byte, regardless of its length. Instead use String::charAt which returns a single char. You don't even have to explicitly convert it after.

Thanks. The i++ is a typo. It is supposed to be i+1. I'll give that charAt a try tomorrow

Would I be able to use that charAt() in the same syntax and add the value directly to the byte commandWord array?

  commandWord[i] = commandValue.charAt(i);

This works fine; but looking at it, it doesn't really do much. Copies a thing at i to another thing at i. A String holds (and provides several handy functions for) a bunch of char, which are close to byte anyway.

  • Just char means a signed char, not an unsigned char
  • char is used for text:
    const char ssid[] = "mywifi";
    
  • unsigned char is actually used for "smallest possible (unsigned) numeric type", 8 bits on almost everything nowadays: 0 to 255
  • if it's a number, it's clearer to use uint8_t or int8_t
  • byte is an alias for uint8_t, which in turn is unsigned char

If you have

byte b = 255;
char c = 65;
Serial.println(b); // size_t Print::println(unsigned char b, int base = DEC)
Serial.println(c); // size_t Print::println(char c)

To a computer, everything is a bunch of bits. But the first println treats those bits as its numeric value, printed as a decimal number by default. The second treats the number as the code point for a character, and prints an 'A' in this case. Similarly

Serial.print(commandWord[i]);         // number
Serial.print(commandValue.charAt(i)); // character

The ASCII value of '1' is 49. What do you really want to see? What do you plan to do with it?

The purpose of this code is to tell 11 motors at different locations around the house to open/close window shutters. The commandWord is a byte array with 11 indexes. So, when the I press a button on the controlUnit, it updates the commandWord and sends it to all 11 motorUnits. The motorUnits each look at a specific index in the commandWord, and open/closes. So, technically, the commandWord could be a bool array, but i had an idea that i could use the remaining 7 bits of each index byte (using bitWrite() for each command on the controlUnit) for additional commands (treating each byte as an 8bit bool array), and use bitRead() to determine the full command so up to 8 commands to each motorUnit per commandWord.

I suppose I can make the commandWord a char array. Since I'm using a for loop to print each index to Serial and client anyway, I dont think it will make much difference for the controlUnit code.

(Could you point me to a reference, such as Arduino Variable Types for Dummies, that could help me understand the int_8t, uint_8t, etc variables. I -kinda- understand that int_8t is the same as int (I think), but I dont understand why a person would use int_8t instead of int.)

Plain char can be signed or unsigned depending on the architecture, but it is never the same type as signed char or unsigned char. On ARM targets it is usually unsigned.

look this over. don't know how you intend set/clr control byte

// 

enum { Off = HIGH, On = LOW };

byte PinLeds [] = { 10, 11, 12 };
byte PinButs [] = { A1, A2, A3 };
#define Nbut   sizeof(PinButs)

byte butState [Nbut];

#define Nbyte Nbut
unsigned int ctrlBytes [Nbyte];;

// -----------------------------------------------------------------------------
#define NoBut -1
int
chkButtons ()
{
    for (unsigned n = 0; n < sizeof(PinButs); n++)  {
        byte but = digitalRead (PinButs [n]);

        if (butState [n] != but)  {
            butState [n] = but;

            delay (10);     // debounce

            if (On == but)
                return n;
        }
    }
    return NoBut;
}

// -----------------------------------------------------------------------------
void
processCmd (
    unsigned int *cmd )
{
    for (unsigned i = 0; i < Nbyte; i++)  {
        digitalWrite (PinLeds [i], cmd [i] & 1);
    }
}

// -----------------------------------------------------------------------------
void
loop ()
{
    int but = chkButtons ();
    if (NoBut != but)  {
        ctrlBytes [but] ^= 1;            // exclusive-OR, toggle control bit
    }

    processCmd (ctrlBytes);
}

// -----------------------------------------------------------------------------
void
setup ()
{
    Serial.begin (9600);

    for (unsigned n = 0; n < sizeof(PinButs); n++)  {
        pinMode (PinButs [n], INPUT_PULLUP);
        butState [n] = digitalRead (PinButs [n]);
    }

    for (unsigned n = 0; n < sizeof(PinLeds); n++)  {
        digitalWrite (PinLeds [n], Off);
        pinMode      (PinLeds [n], OUTPUT);
    }
}

In that case, there is no need to make a copy, because the commandValue String already contains a char array. You can even using the [ ] operators to read and write the elements; the charAt and setCharAt methods are equivalent. A little less code, and save some memory.

Both are integers, but int is at least 16 bits, used for "human-scale" counting and integer math. It used to be usually the "natural word size" of the CPU, so e.g.

  • 16 on 8-bit AVR
  • 32 on ESP32
  • 32 on modern 64-bit desktop/laptop CPUs, since 64 would "waste too many bits"

In contrast, int8_t is 8 bits everywhere. For data structures and wire protocols where you need specific sizes, you use intN_t, signed or unsigned. Further, on a rare CPU doesn't support that size for whatever reason, you'll know right away because your code won't compile there.