DC motor control using function

Hey guys im trying to run a dc motor with on and off function and also speed control that is connected to pwm pin D2.
everytime i run the function paramaters it just says bummer failed.
code compiles fine
any help plz.


int motorPin = D2;
int speed= 200;
int speed1= 3;
void setup() 
{ 
Particle.function("Engine_on/off", motorfunction);
  pinMode(motorPin, OUTPUT);
  
} 
 
 
void loop() 
{ 
  
}

int motorfunction(String motorCommand) {
    String convertedCommand = motorCommand.toUpperCase();
    
    

     if(convertedCommand == "Motor on") {
         speed;
        analogWrite(motorPin, speed);
        return(1);
    } else if(convertedCommand== "Motor off") {
        speed1;
        analogWrite(motorPin, speed);
        return(0);        
     }
   else {
        return(-1);
    }
    
    }

    

its using this wiring diagram from arduino

...from the reference guide:

Note: Only use letters, numbers, underscores and dashes in function names. Spaces and special characters may be escaped by different tools and libraries causing unexpected results. A function callback procedure needs to return as quickly as possible otherwise the cloud call will timeout.

...and

Up to 15 cloud functions may be registered and each function name is limited to a maximum of 12 characters ( prior to 0.8.0 ), 64 characters ( since 0.8.0 ). The Spark Core remains limited to 12 characters.

Also - convertedCommand = motorCommand.toUpperCase() means you'll want to compare "MOTOR ON" and "MOTOR OFF"

...and the lines speed; and speed1; aren't doing anything for you - why are they there?

Hope it helps.

2 Likes

Just adding to @PeteTheRanger helpful comments. The Particle function handler should really return very quickly. You are probably OK with doing analogWrite() but I would in preference set a global variable uint8_t duty_cycle; Then in the function handler you set the value of duty_cycle = 0 for off and 255 for full on. In loop you can then call analogWrite() if the value has changed.