I am newbie in C (I'm using Delphi/pascal instead) and trying to get some temperature sensor values and make them equal/fixed size to send to the MCU (with Arduino IDE- so I have to work with C).
Length of data (strlen()) can be 3(like 5.3, 0.9, 0.0 etc), 4(like -4.2, 19.8 etc) or 5(like -15.6) based on temp sensor and below code;
char value[5]; // must be char in order to send to MCU
if ((temp_data>=temp_max){
fix_size(value,true); //Error part. writes: "EEEEE" to reach fix size: 5
} else {
dtostrf(temp_data, 0, 1, value);
fix_size(value,false); //I'll use this to send data to screen later..
}
I need to fixed the size of data (to do that I am trying to add zeros at the end) and Iam trying to do with below;
char fix_size(char temp_char[5],bool err=false){
if(err){
temp_char= "EEEEE";
Serial.println(temp_char);
return temp_char;
}
int num = strlen(temp_char);
// If strlen is 5 then it is OK and strlen cannot be 2 and 1 because of my temp sensor data processing (dtostrf(temp_data, 0, 1, value)) so I only need to take care 3 and 4
switch (num) {
case 3:
temp_char[3] = "0";
temp_char[4] = "\0";
//0.0 would become 0.000
//5.4 would become 5.400
break;
case 4:
temp_char[4] = "\0";
//15.2 would become 15.20
//-7.4 would become -7.40
break;
// -15.3 is in right format already
} | E.g. I tried for 15.4 and get
Serial.println(temp_char[0]); | 1
Serial.println(temp_char[1]); | 5
Serial.println(temp_char[2]); | .
Serial.println(temp_char[3]); | 4
Serial.println(temp_char[4]); | ؟
return temp_char;
}
But, when I execute the app I am taking strange characters as output in ArduinoIDE (reversed question marks, squares etc..). What can be the problem?How can I solve this problem? or can you suggest better way? thanks right now..
NOTE: Origin of this question (problem) is more about Embedded Systems and I've asked another question on Electronics StackExchage as a reference to this question (If you want/need you can read here )
At least three problems. First, temp_char[]
is declared at size 5, but you're trying to put 6 characters into it with "EEEEE" (which has a trailing zero), and by using temp_char[5]
(only values 0..4 are legal).
Second, the assignment temp_char = "EEEEE"
just changes the pointer, it doesn't actually copy anything into temp_char
. You need strcpy()
or something similar for that.
Third, you're confusing types:
temp_char[4] = "0";
temp_char[4]
is of type char
. "0"
is of type char *
, that is, it's a pointer to a character, not a character, so you're just getting the lower 8 bits of some random memory address. You probably mean:
temp_char[4] = '0';
because '0'
is of type int
, representing an ASCII value, that will be properly truncated to 8 bits on assignment.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.