Arduino控制motorshield

来源:互联网 发布:卧龙大数据招聘 编辑:程序博客网 时间:2024/06/07 08:19


/***
使用arduino和motor shield测试通过。
确保A1、A2、ENA、GND连接正确,最好在同一排。
电源模块的电压在工作范围内。
***/


#define motor1pin1 7                              //定义IN1引脚
#define motor1pin2 8                              //定义IN2引脚
#define motor1pwm 3                             //定义ENA引脚(我的是arduino uno的板子)


void motor(int motorpin1,int motorpin2,int motorpwm,int val)  //定义一个电机转动函数
{
    pinMode(motorpin1,OUTPUT);                              //输出第一个引脚
    pinMode(motorpin2,OUTPUT);                             //输出第二个引脚
    digitalWrite(motorpin2,0);                                    //将第二个引脚置低
    digitalWrite(motorpin1,1);                                     //将第一个引脚抬高
    analogWrite(motorpwm,val);                                //给EN引脚设定模拟值,设定转速
}
void setup()
{  
}
void loop()
{
    motor(motor1pin1,motor1pin2,motor1pwm,250);                 //电机A以最大转速转动
    delay(5000);
    motor(motor1pin2,motor1pin1,motor1pwm,250);                //电机A反向转动
    delay(5000);
}

测试结果:

电机A先正转后反转,不断循环。