I have written a small C application to do PWM for some motors connected to a Raspberry Pi. I am using the PiGPIO library. The code as follows:
int[] FWD = {MOTOR1_FWD, MOTOR2_FWD};
int[] BCK = {MOTOR1_BCK, MOTOR2_BCK};
void setMotorSpeed(int motorIndex, int speed)
{
if (speed > 0) //forward
{
gpioPWM(FWD[motorIndex], speed);
gpioPWM(BCK[motorIndex], 0);
}
else if (speed < 0) //back
{
gpioPWM(FWD[motorIndex], 0);
gpioPWM(BCK[motorIndex], -speed);
}
else /* stop */
{
gpioPWM(FWD[motorIndex], 0);
gpioPWM(BCK[motorIndex], 0);
}
}
int main(int argc, char *argv[])
{
double start;
if (gpioInitialise() < 0)
{
fprintf(stderr, "pigpio initialisation failed\n");
return 1;
}
char *p;
int speed = strtol(argv[2],&p, 10);
/* Set GPIO modes */
int i = 0;
for (i = 0; i < 4; i++) {
gpioSetMode(FWD[i], PI_OUTPUT);
gpioSetMode(BCK[i], PI_OUTPUT);
gpioSetMode(EN[i], PI_OUTPUT);
setMotorSpeed(i, 0);
gpioWrite(EN[i], ON);
}
if (argc <= 1)
{
printf("STOP\n");
} else {
if (strcmp(argv[1], "l") == 0 || strcmp(argv[1], "lr") == 0)
{
printf("LEFT ON: %d\n", speed);
setMotorSpeed(0, speed);
}
if (strcmp(argv[1], "r") == 0 || strcmp(argv[1], "lr") == 0)
{
printf("RIGHT ON: %d\n", speed);
setMotorSpeed(1, speed);
}
}
gpioTerminate();
return 0;
}
Works fine, but if I change MAX to 255 and use gpioPWM(motorX, MAX)
it only works sometimes, and when it does work only the left will run. What should I do to make them both be able to work, and work consistently?
This does not work consistently when I compile and run as follows:
gcc -o drive drive.c -lpigpio -lrt -lpthread
sudo ./drive lr 150
Currently I just have the pins connected to LED's and sometimes the LED's get power, other times they do not.