【Arduino】利用直流电机制作简易风扇,调速摇头两不误
夏日炎炎,如果没有一丝自然风,那只能自己创造啦! 运用手头的道具制作一个具有调速和摇头功能的简易风扇,利用Arduino控制直流电机来实现扇叶的转动,可随意控制岂不乐哉。

今天我们来利用手头的道具制作一个具有调速和摇头功能的简易风扇,本次一共用到了:
一个直流电机
一个舵机
一个 RotaryEncoder模块
线路图:

工作原理:
实验所用的代码如下:
/***********************************************************
File name: _26_DCMotorModule.ino
Description: The state of DC motor includes its forward, reverse,
acceleration, deceleration and stop. And you will
see the data on the serial monitor
Website: www.adeept.com
E-mail: support@adeept.com
Author: Tom
Date: 2017/03/18
***********************************************************/
#include<Servo.h>
const int DC_APin = 10; //DC motor module A pin connected to digital 11 pin
const int DC_BPin = 11; //DC motor module B pin connected to digital 10 pin
int DCmotorspeed = 60; //motor speed 0~255
const int APin= 2; //Set the digital 2 to A pin
const int BPin= 3; //Set the digital 3 to B pin
const int SPin= 4 ;//Set the digital 4 to S pin
int i=1;
int encoderVal = 0;
int angle = 90;
Servo s1;
int flag = LOW;
int flag_1 = 0;
int getRotaryEncoder(void)
{
static int oldA = HIGH; //set the oldA as HIGH
static int oldB = HIGH; //set the oldB as HIGH
int result = 0;
int newA = digitalRead(APin); //read the value of APin to newA
int newB = digitalRead(BPin); //read the value of BPin to newB
if (newA != oldA || newB != oldB)//if the value of APin or the BPin has changed
{
if (oldA == HIGH && newA == LOW)// something has changed
{
result = (oldB * 2 - 1);
}
}
oldA = newA;
oldB = newB;
return result;
}
void clockwise(int Speed) //the function to drive motor rotate clockwise
{
analogWrite(DC_APin,Speed); //set the speed of motor
analogWrite(DC_BPin,0); //stop the B pin of motor
}
void counterclockwise(int Speed) //the function to drive motor rotate counterclockwise
{
analogWrite(DC_APin,0); //stop the A pin of motor
analogWrite(DC_BPin,Speed); //set the speed of motor
}
void setup()
{
pinMode(DC_APin,OUTPUT); //initialize the A pin as output
pinMode(DC_BPin,OUTPUT); //initialize the B pin as output
pinMode(APin, INPUT);//initialize the A pin as input
pinMode(BPin, INPUT);//initialize the B pin as input
pinMode(SPin, INPUT);//initialize the S pin as input
s1.attach(A4);
s1.write(angle);
analogWrite(DC_APin,0);
analogWrite(DC_BPin,0);
Serial.begin(115200); //opens serial port, sets data rate to 9600 bps
}
int j;
void loop()
{
int change = getRotaryEncoder();
encoderVal = encoderVal - change;
if(encoderVal>=72){
encoderVal = 72;
}
if(encoderVal<=0){
encoderVal = 0;
DCmotorspeed = 0;
}
if(encoderVal>0&&encoderVal<24)
DCmotorspeed = 60;
if(encoderVal>24&&encoderVal<48)
DCmotorspeed = 80;
if(encoderVal>48&&encoderVal<72)
DCmotorspeed = 120;
if(digitalRead(SPin) == LOW)
flag = !flag;
if(i!=encoderVal){
Serial.write(encoderVal);
i = encoderVal;
}
counterclockwise(DCmotorspeed);
s1.write(angle);
j++;
if(flag &&j > 500)
{
j = 0;
if(flag_1 == 0)
{
angle +=3;
}
else
{
angle -=3;
}
if(angle > 150)
{
flag_1 = 1;
}
if(angle < 30)
{
flag_1 = 0;
}
Serial.print(angle);
}
}