hello i have a problem i need to compare char. It doesnt work. Can you help me??
char A[10]="101001010";
char x[0];
char y[]="1";
char z[]="0";
int i;
void setup() {
Serial.begin(9600);
}
void loop() {
for(i=0; i<sizeof(A)-1;i++){
x[0]=(A[i]);
Serial.write (x[0]);
if (strcmp (x,y) == 0)
{ Serial.write ("true");
Serial.println( );}
if (strcmp (x,z) == 0)
{ Serial.write ("false");
Serial.println( );}
delay (1000);}
What is your intended logic? Give us some sample input and outputs. The program is horribly written. It's like every line has a mistake. I'll pick out one at a time:
Use Serial.print instead of write when you try to output "true" or "false".
char x[0];
You are trying to store a character into an array that can hold at most ZERO characters.
x[0]=(A[i]);
if (strcmp (x,y) == 0)
You are storing a single character into an array and treating it as a null-terminated string without inserting a null terminator.
It looks like what you are trying to do is:
char A[] = "101001010"; // Safer not to force the array size
void setup() {
Serial.begin(9600);
}
void loop() {
for (unsigned int i = 0; i < strlen(A); i++) {
// You don't have to store each element in a variable to
// display or compare.
Serial.write(A[i]);
if (A[i] == '1') { // You can directly compare characters
Serial.println(" true");
}
else if (A[i] == '0') {
Serial.println(" false");
}
delay (1000);
}
}
I think the problem was that you knew how to compare character strings (strcmp()) but did not know you can compare individual characters just like any other integers.