电路连接方式请看另一篇博文:【利用树莓派控制步进电机——pythony语言】
/****************************************************** * File name: stepMotor.c * Author: Jason Dai * Date: 2015/01/26 ******************************************************/ #include <wiringPi.h> #include <stdio.h> #define IN1 0 // wiringPi GPIO0(pin11) #define IN2 1 #define IN3 2 #define IN4 3 void setStep(int a, int b, int c, int d) { digitalWrite(IN1, a); digitalWrite(IN2, b); digitalWrite(IN3, c); digitalWrite(IN4, d); } void stop() { setStep(0, 0, 0, 0); } void forward(int t, int steps) { int i; for(i = 0; i < steps; i++){ setStep(1, 0, 0, 0); delay(t); setStep(0, 1, 0, 0); delay(t); setStep(0, 0, 1, 0); delay(t); setStep(0, 0, 0, 1); delay(t); } } void backward(int t, int steps) { int i; for(i = 0; i < steps; i++){ setStep(0, 0, 0, 1); delay(t); setStep(0, 0, 1, 0); delay(t); setStep(0, 1, 0, 0); delay(t); setStep(1, 0, 0, 0); delay(t); } } int main(void) { if (-1 == wiringPiSetup()) { printf("Setup wiringPi failed!"); return 1; } /* set mode to output */ pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT); while (1){ printf("forward...\n"); forward(3, 256); printf("stop...\n"); stop(); delay(2000); // 2s printf("backward...\n"); backward(3, 512); // 512 steps ---- 360 angle printf("stop...\n"); stop(); delay(2000); // 2s } return 0; }
编译:
gcc stepMotor.c -o stepMotor -lwiringPi
运行:
./stepMotor
时间: 2024-11-08 09:47:26