Trying to Control Motor with Particle Subscribe/Publish

Hey I'm trying to use particle publish & subscribe to control a motor with a joystick from two separate boards and don't understand what I'm doing wrong in my code. Was wondering if anyone could provide help

Joystick Code

#define x A4


int xVal1;

void setup() {
    pinMode(x,INPUT);
    
}

void loop() {
    
    xVal1 = analogRead(x);
    Particle.publish("Joystick val", String(xVal1)); 
    delay(200);
    
  
}

Motor Code

#define PWMA D2
#define In1A D3
#define LED D4
#define LED1 D7



void setup() {
    

    pinMode(PWMA, OUTPUT);                                     
    pinMode(In1A, OUTPUT); 
    pinMode(LED1, OUTPUT);
    Particle.subscribe("Xval",drive,"e00fce680c766377df77c168");


}

void loop() {

}
void drive(const char *event, const char *data){
    
    int value = atoi(data);
    
    int mSpeed = map(value, 0, 4095,0,180);
    
    if(mSpeed>0){
        digitalWrite(In1A,HIGH);
        analogWrite(LED,HIGH);
        analogWrite(LED1,HIGH);
    }
    else if(mSpeed<0){
        digitalWrite(In1A,LOW);
        analogWrite(LED,LOW);
        analogWrite(LED1,HIGH);
    }
    analogWrite(PWMA,abs(mSpeed));
}

You should first divide the problem into smaller parts, making sure your data communication is working separately from the motor control. Using USB serial debugging is a good technique.

You're publishing the location every 200 milliseconds. This will not work, as the maximum publish rate is 1 per second. This will cause the publishes to be throttled so none will go out Also, even at 1 per second will use a very large number of data operations such that you will likely exceed the limit of 700,000 per month. You can see if publishes are working by monitoring the event log in the console.

What is the third parameter in Particle.subscribe for? I'm surprising that compiled. If you are trying to filter for a device it needs to go as a prefix in the event name, not as a separate parameter. The publishing code would also need to be modified with the new event name.

The LED control won't work because you're writing high and low to LED and LED1 using analogWrite. This results in a value of 0 or 1 out of 255, which is probably not distinguishable from off.

If both devices are Argons, the motor and LED pins are OK for PWM, so that's good.

To see if your motor control board is working, does it work if you hardcode the value for analogWrite to PWMA? And what kind of motor controller is it? If it's a servo, then you should use the Servo class instead of directly using analogWrite.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.