jedneraz:
Hello!
I want to call my_function in a loop. How to do it?
int led = 13;
void setup()
{
pinMode(led, OUTPUT);
Serial.begin(9600, SERIAL_8N1);
Serial.flush();
}
void my_function()
{
char buf[4];
int charsRead;
charsRead = Serial.readBytesUntil('\n', buf, 4);
buf[charsRead] = '\0';
return my_function();
}
void loop()
{
if (strcmp(my_function(), "on") == 0)
{
digitalWrite(led, HIGH);
Serial.println("on");
}
else if (strcmp(my_function(), "off") == 0)
{
digitalWrite(led, LOW);
Serial.println("off");
}
}
I have a problem.
sketch_dec01a.ino: In function ‘void loop()’:
sketch_dec01a.ino:22:36: error: invalid use of void expression
sketch_dec01a.ino:28:42: error: invalid use of void expression
void my_function() {}; // returns nothing, that's what void means
strcmp( char *, char * ) is not strcmp( void, char * ) which gives you those 2 errors.
You need
char * my_function( )
{
char buf[4];
int charsRead;
charsRead = Serial.readBytesUntil('\n', buf, 4);
buf[charsRead] = '\0';
return buf;
}
And those strcmp() will have to match exactly to work. I changed them to strstr() since I have serial monitor add a newline to every line it sends. I could have gone with matching "on\n" and "off\n" thopugh.
Compiles and works:
byte led = 13; // don't use an int where a byte would do on an 8 bit machine.
void setup()
{
pinMode(led, OUTPUT);
Serial.begin( 115200 ); // why use slower?
Serial.flush();
}
char * my_function( )
{
char buf[4];
byte charsRead;
charsRead = Serial.readBytesUntil('\n', buf, 4);
buf[charsRead] = '\0';
return buf;
}
void loop()
{
if (strstr(my_function(), "on") > 0 ) // you can change this back
{
digitalWrite(led, HIGH);
Serial.println("on");
}
else if (strstr(my_function(), "off") > 0) // you can change this back
{
digitalWrite(led, LOW);
Serial.println("off");
}
}