给我几个电机控制的C语言代码
时间: 2023-03-31 15:01:16 浏览: 587
以下是几个电机控制的C语言代码:
1. 控制直流电机转动:
#include <stdio.h>
#include <stdlib.h>
#include <wiringPi.h>
#define MOTOR_PIN 1 // 定义电机控制引脚
int main(void)
{
if (wiringPiSetup() == -1) // 初始化wiringPi库
{
printf("wiringPi setup failed!\n");
return 1;
}
pinMode(MOTOR_PIN, OUTPUT); // 设置电机控制引脚为输出模式
while (1)
{
digitalWrite(MOTOR_PIN, HIGH); // 电机正转
delay(100);
digitalWrite(MOTOR_PIN, LOW); // 电机停止
delay(100);
}
return ;
}
2. 控制步进电机转动:
#include <stdio.h>
#include <stdlib.h>
#include <wiringPi.h>
#define MOTOR_PIN1 1 // 定义步进电机控制引脚1
#define MOTOR_PIN2 2 // 定义步进电机控制引脚2
#define MOTOR_PIN3 3 // 定义步进电机控制引脚3
#define MOTOR_PIN4 4 // 定义步进电机控制引脚4
int main(void)
{
if (wiringPiSetup() == -1) // 初始化wiringPi库
{
printf("wiringPi setup failed!\n");
return 1;
}
pinMode(MOTOR_PIN1, OUTPUT); // 设置步进电机控制引脚为输出模式
pinMode(MOTOR_PIN2, OUTPUT);
pinMode(MOTOR_PIN3, OUTPUT);
pinMode(MOTOR_PIN4, OUTPUT);
int i;
while (1)
{
for (i = ; i < 8; i++) // 步进电机正转
{
switch (i)
{
case :
digitalWrite(MOTOR_PIN1, HIGH);
digitalWrite(MOTOR_PIN2, LOW);
digitalWrite(MOTOR_PIN3, LOW);
digitalWrite(MOTOR_PIN4, LOW);
break;
case 1:
digitalWrite(MOTOR_PIN1, HIGH);
digitalWrite(MOTOR_PIN2, HIGH);
digitalWrite(MOTOR_PIN3, LOW);
digitalWrite(MOTOR_PIN4, LOW);
break;
case 2:
digitalWrite(MOTOR_PIN1, LOW);
digitalWrite(MOTOR_PIN2, HIGH);
digitalWrite(MOTOR_PIN3, LOW);
digitalWrite(MOTOR_PIN4, LOW);
break;
case 3:
digitalWrite(MOTOR_PIN1, LOW);
digitalWrite(MOTOR_PIN2, HIGH);
digitalWrite(MOTOR_PIN3, HIGH);
digitalWrite(MOTOR_PIN4, LOW);
break;
case 4:
digitalWrite(MOTOR_PIN1, LOW);
digitalWrite(MOTOR_PIN2, LOW);
digitalWrite(MOTOR_PIN3, HIGH);
digitalWrite(MOTOR_PIN4, LOW);
break;
case 5:
digitalWrite(MOTOR_PIN1, LOW);
digitalWrite(MOTOR_PIN2, LOW);
digitalWrite(MOTOR_PIN3, HIGH);
digitalWrite(MOTOR_PIN4, HIGH);
break;
case 6:
digitalWrite(MOTOR_PIN1, LOW);
digitalWrite(MOTOR_PIN2, LOW);
digitalWrite(MOTOR_PIN3, LOW);
digitalWrite(MOTOR_PIN4, HIGH);
break;
case 7:
digitalWrite(MOTOR_PIN1, HIGH);
digitalWrite(MOTOR_PIN2, LOW);
digitalWrite(MOTOR_PIN3, LOW);
digitalWrite(MOTOR_PIN4, HIGH);
break;
default:
break;
}
delay(10);
}
}
return ;
}
3. 控制舵机转动:
#include <stdio.h>
#include <stdlib.h>
#include <wiringPi.h>
#include <softPwm.h>
#define MOTOR_PIN 1 // 定义舵机控制引脚
int main(void)
{
if (wiringPiSetup() == -1) // 初始化wiringPi库
{
printf("wiringPi setup failed!\n");
return 1;
}
softPwmCreate(MOTOR_PIN, , 200); // 设置舵机控制引脚为软件PWM模式,频率为200Hz
while (1)
{
softPwmWrite(MOTOR_PIN, 10); // 舵机转动到最小角度
delay(100);
softPwmWrite(MOTOR_PIN, 15); // 舵机转动到中间角度
delay(100);
softPwmWrite(MOTOR_PIN, 20); // 舵机转动到最大角度
delay(100);
}
return ;
}
阅读全文