I want to use Timer to call a function that actuates my servo. However, I do not want to create a new class and complicate the setup with .h and .cpp files. The compiler does not like the use of “this” for the class instance, but since I am working with just setup(), loop(), and member functions, I don’t know how to properly construct the timer objects. I have attached my full program below.
int motor(){
myservo.write(125);
return 1;
}
int motorReset(){
myservo.write(0);
return 1;
}
int cycleP(String command){
if(command=="Y"||command=="y"){
Timer t(5, motor(), *this, true);
Timer t2(30, motorReset(), *this, true);
t.start();
t2.start();
myservo.write(0);
return 1;
}
else return -1;
}
full program
#include "Particle.h"
//following 2 lines from Particle support regarding problem with functions publishing
SYSTEM_MODE(SEMI_AUTOMATIC);
SYSTEM_THREAD(ENABLED);
Servo myservo; //unlike arduino, servo is in Particle.h so no need for #include <Servo.h>
int pos = 0;
int led1 = A5; //pin headers are treates as ints - this is why you have to read the OS API documentation!
int cycleP(String command);
int testFunction(String arg);
unsigned long old_time = 0; //can also use uint32_t from C standard - unsigned 32 bit int
unsigned long old_time2 = 0;
//we need this in order to implement "soft delay" with millis() rather than "hard" delay()
//functions in setup are only run once - via OS API it is recommended to declare "cloud functions" as soon as possible
//setup is also where you want to declare hardware "attaches" such assigning pins to LEDs, pumps, switches, relays, etc.
void setup(){
Particle.function("onOff", cycleP);
Particle.function("inputTest", testFunction);
myservo.attach(D2);
myservo.write(0);
pinMode(led1, OUTPUT);
Particle.connect();
}
void loop(){
//following 2 if statements make the LED turn on for 1 sec then off for 5 - this allows me to know when updated firmware has flashed and device is online
if(millis()-old_time>=1000){
digitalWrite(led1, LOW);
old_time = millis();
}
if(millis()-old_time2>=5000){
digitalWrite(led1, HIGH);
old_time2 = millis();
}
}
int testFunction(String arg){
if(arg=="test"){
return 1;
}
else return -1;
}
int motor(){
myservo.write(125);
return 1;
}
int motorReset(){
myservo.write(0);
return 1;
}
int cycleP(String command){
if(command=="Y"||command=="y"){
Timer t(5, motor(), *this, true);
Timer t2(30, motorReset(), *this, true);
t.start();
t2.start();
myservo.write(0);
return 1;
}
else return -1;
}