[ 3 / biz / cgl / ck / diy / fa / ic / jp / lit / sci / vr / vt ] [ index / top / reports ] [ become a patron ] [ status ]
2023-11: Warosu is now out of extended maintenance.

/diy/ - Do It Yourself

Search:


View post   

>> No.1782478 [View]
File: 224 KB, 675x1022, variable to char array problem.jpg [View same] [iqdb] [saucenao] [google]
1782478

What is the best way of writing a 4-digit number to an unsigned char array on the arduino? Took me far too long and I kept finding people saying strings should be avoided.

my solution as follows:

int x = 1234;
int 12x = 0; //int for storing digits 1, 2, of x
int 34x = 0; //int for storing digits 3, 4, of x

void setup(){
Serial.begin(115200); //using this baudrate for MCP2515 canbus module
}
unsigned char stmp[8] = {0, 0, 0, 0, 0, 0, 0, 0};

void loop(){
String 12str = String(x);
String 34str = String(x);

12str.remove(2, 2); //prints value 12
34str.remove(0, 2); //prints value 34

int 12x = 12str.toInt(); //convert string to int
int 34x = 34str.toInt();

stmp[0] = 12x; //add values to char array
stmp[1] = 34x;
} //end

And it works, but I’m curious if there is a more elegant solution, or one that avoid the use of strings?

Navigation
View posts[+24][+48][+96]