Micro Servo SG 90 – 0 to 180 Degrees Loop

Tiny C program to loop a Micro Servo SG 90 from 0 to 180 degrees and back. Requires servoblaster.


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

#define SERVOBLASTER_DEVICE_PATH "/dev/servoblaster"
#define SERVOBLASTER_PIN 2
#define MIN 60
#define MAX 250
#define STEP_INTERVAL_MILLISECONDS 960

int set_pulse_width(int width) {
FILE *pDeviceOutput;
pDeviceOutput = fopen(SERVOBLASTER_DEVICE_PATH, "a");
if(pDeviceOutput==NULL) {
printf("Can not open device.\n");
fclose(pDeviceOutput);
return 1;
}
fprintf(pDeviceOutput, "%d=%d\n", SERVOBLASTER_PIN, width);
fclose(pDeviceOutput);
return 0;
}

int main() {
int i;
for (i = MIN; i <= MAX; i++) {
if (set_pulse_width(i) == 1) {
printf("Can not set width.\n");
return 1;
}
usleep(STEP_INTERVAL_MILLISECONDS);
}
return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *