Controlling a servo using c on beagle bone black

99 Views Asked by At

I can't seem to get the servo to move. I am using pin p9_14, my servo is a Tower Pro SG92R, and I have Debian on my beaglebone black

I'm trying to solve it using no libraries if possible(for practice)

here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define PWM_PERIOD 20000 
#define DUTY_MIN 1000
#define DUTY_MAX 2000

void writeToFile(const char* path, int value) {
        FILE* file = fopen(path, "w");
        if(file == NULL) {
                perror("Error opening file");
                printf("My integer is: %d\n", value);
                printf(path);
                exit(1);
        }
        fprintf(file, "%d", value);
        fclose(file);
}
int main(){
        writeToFile("/sys/class/pwm/pwm-0:0/enable", 1);
        writeToFile("/sys/class/pwm/pwm-0:0/period", PWM_PERIOD);
        while(1){
                
                // Move the servo to the left (minimum position)
                writeToFile("/sys/class/pwm/pwm-0:0/duty_cycle", DUTY_MIN);
                usleep(2000000);

                // Move the servo to the right (maximum position)
                writeToFile("/sys/class/pwm/pwm-0:0/duty_cycle", DUTY_MAX);
                usleep(2000000);

                // Move the servo to the center position 
                writeToFile("/sys/class/pwm/pwm-0:0/duty_cycle", (DUTY_MIN + DUTY_MAX) / 2);
                usleep(2000000);
        }
        writeToFile("/sys/class/pwm/pwm-0:0/enable", 0);

        return 0;
}

I have tried all the pwm channels, I have played with the max/min dutycyles and the period

1

There are 1 best solutions below

3
On

/dev/bone/pwm/ may help. Does this show in your file system?