电子说
步骤1:设置
软件
在此步骤中,我将提供零件清单和下载Arduino软件的链接。我为此项目使用了Arduino Create。您可以使用Arduino程序执行相同的操作,该程序可从此处下载。
部件列表:
Arduino Uno(其他板可能
标准直流电动机
L293DNE H桥
2个按钮
跳线
面包板
所有这些物品都可以很便宜地在线购买。
步骤2:串行通信-接线
首先,让我们进行串行通信。如图所示连接Arduino。
第3步:串行通信-代码
现在,您已将Arduino连接好,将代码复制并粘贴到Arduino IDE。将读取此代码的作用,以获取您将在串行监视器中手动键入的信号。输入1或2时,电动机将在短时间内顺时针或逆时针旋转。做一点实验!键入多个1或2,然后看看会发生什么!
int in1pin = 6;
int in2pin = 7; // connections to H-Bridge, clockwise / counter
char receivedChar; // store info
boolean newData = false; // create a true/false statement
void setup() {
pinMode(in1pin, OUTPUT);
pinMode(in2pin, OUTPUT); // set pins to OUTPUTS
Serial.begin(9600); // start up serial communication
}
void loop() {
recvData(); // read and store data
moveMotor(); // move motor according to data and then reset
}
void recvData() {
if (Serial.available() 》 0) { // if the serial monitor has a reading
receivedChar = Serial.read(); // set char to be what is read
newData = true; // make statement true
}
}
void moveMotor() {
int motordirection = (receivedChar - ‘0’); // turn recieved data into usable form and give it a name
while(newData == true) {
Serial.println(motordirection); // print motor direction
if (motordirection == 1) { // if it reads 1.。.
digitalWrite(in1pin, HIGH); // turn motor one way
digitalWrite(in2pin, LOW);
delay(250);
}
else if (motordirection == 2) { // if it reads 2.。.
digitalWrite(in1pin, LOW); // turn motor other way
digitalWrite(in2pin, HIGH);
delay(250);
}
else { // if nothing is read
digitalWrite(in1pin, LOW); // motor is off
digitalWrite(in2pin, LOW);
}
newData = false; // reset value to false
}
}
步骤4:按钮命令-接线
要进行按钮通讯,请如图所示添加按钮。
第5步:按钮命令-代码
现在,制作新草图并复制并粘贴此代码,然后播放周围。
int in1pin = 6;
int in2pin = 7; // h bridge pins
int leftButton = 8;
int rightButton = 9; // buttons
void setup() {
pinMode(in1pin, OUTPUT);
pinMode(in2pin, OUTPUT); // outputs
pinMode(leftButton, INPUT_PULLUP);
pinMode(rightButton, INPUT_PULLUP); // inputs w internal pullup resistors
}
void loop() {
int leftPinState = digitalRead(leftButton);
int rightPinState = digitalRead(rightButton); // set value names for read data
if (leftPinState == LOW) { // if left button is pressed 。..
digitalWrite(in1pin, HIGH); // make motor go one way
digitalWrite(in2pin, LOW);
}
else if (rightPinState == LOW) { // if right button is pressed 。..
digitalWrite(in1pin, LOW);
digitalWrite(in2pin, HIGH); // make motor go other way
}
else { // if neither button is pressed 。..
digitalWrite(in1pin, LOW); // nothing happens
digitalWrite(in2pin, LOW);
}
}
全部0条评论
快来发表一下你的评论吧 !