begin to write motor.c

This commit is contained in:
Siegfried Kienzle
2017-04-22 17:35:29 +02:00
parent 70969386a6
commit 644f053f9d

91
project/motor.c Normal file → Executable file
View File

@@ -1,18 +1,99 @@
#include<stdio.h> #include<stdio.h>
#include<fctnl.h> #include<fcntl.h>
#include<string.h> #include<string.h>
#include<unistd.h> #include<unistd.h>
#define BASEPATH "/sys/class/gpio/" #define BASEPATH "/sys/class/gpio/"
#define GPIO_FOLDER "gpio%s/" #define GPIO_FOLDER "gpio%s/"
#define PIN_IN1 "6" #define PIN_MOTOR1_FORWARD "6"
#define PIN_IN2 "13" #define PIN_MOTOR1_REVERSE "13"
#define PIN_IN3 "19" #define PIN_MOTOR2_FORWARD "19"
#define PIN_IN4 "26" #define PIN_MOTOR2_REVERSE "26"
#define MOTOR_ON 0
#define MOTOR_OFF 1
void writeFile(char *filename, char *buffer, size_t count)
{
int fd = open(filename, O_WRONLY);
write(fd, buffer, count);
close(fd);
}
void registerPin(char *pin)
{
writeFile(BASEPATH "export", pin, strlen(pin));
}
void freePin(char *pin)
{
writeFile(BASEPATH "unexport", pin, strlen(pin));
}
void setDirection(char *pin, char *direction, int dirlen)
{
char path[50];
sprintf(path, BASEPATH GPIO_FOLDER "direction", pin);
writeFile(path, direction, dirlen);
}
void registerOutput(char *pin)
{
registerPin(pin);
setDirection(pin, "out", 3);
}
void writeOutput(char *pin, int state)
{
char path[50];
sprintf(path, BASEPATH GPIO_FOLDER "value", pin);
FILE *fd = fopen(path, "w");
fprintf(fd, "%i", state);
fclose(fd);
}
void forward(int motorNumber)
{
if(motorNumber == 1)
{
writeOutput(PIN_MOTOR1_FORWARD, MOTOR_ON);
}
else if(motorNumber == 2)
{
writeOutput(PIN_MOTOR2_FORWARD, MOTOR_ON);
}
else if(motorNumber == 3)
{
writeOutput(PIN_MOTOR1_FORWARD, MOTOR_ON);
writeOutput(PIN_MOTOR2_FORWARD, MOTOR_ON);
}
}
void reverse(int motorNumber)
{
if(motorNumber == 1)
{
writeOutput(PIN_MOTOR1_REVERSE, MOTOR_ON);
}
else if(motorNumber == 2)
{
writeOutput(PIN_MOTOR2_REVERSE, MOTOR_ON);
}
else if(motorNumber == 3)
{
writeOutput(PIN_MOTOR1_REVERSE, MOTOR_ON);
writeOutput(PIN_MOTOR2_REVERSE, MOTOR_ON);
}
}
int main() int main()
{ {
registerOutput(PIN_MOTOR1_FORWARD);
registerOutput(PIN_MOTOR1_REVERSE);
registerOutput(PIN_MOTOR2_FORWARD);
registerOutput(PIN_MOTOR2_REVERSE);
return 0; return 0;
} }