|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
开篇:二币做的壁障,请别对语法和程序结构做评价,我是二币,能写就不错了。
此帖更新,待后续。。。。
超声波壁障小车,可转换为飞行器。
如下就说明。
A,使用SR04超声波模块4PCS
B,arduino 2560 1PCS。
C,HC-05蓝牙模块1PCS。
D,mx830 4PCS定做的电机驱动板。MX830和L298N基本类似。
程序如下:
#include "SR04.h" //超声波库
#define TRIG_PIN 9 //超声波信号发射 PMW_PIN
#define ECHO_PIN_Q 10 //超声波1信号接收 PMW_PIN
#define ECHO_PIN_Z 11 //超声波2信号接收 PMW_PIN
#define ECHO_PIN_Y 12 //超声波3信号接收 PMW_PIN
#define ECHO_PIN_H 13 //超声波4信号接收 PMW_PIN
#include <math.h>
String comdata = "";
int numdata[9] = {0}; //定义数组接收的字符串个数
int PWMPin[9] = {1, 2, 3, 4, 5, 6, 7, 8, 0}; //定义PMW_PIN的作用
//1为左轮+,2为左轮-,3为右轮+,4为右轮-,5为炮塔+,6为炮塔-,7为炮塔上下+,负极接公共-,8为BB发射器+,负极接公共-,1为自动与手动切换
int mark = 0;
int on_off = 0;
SR04 SR_Q = SR04(ECHO_PIN_Q, TRIG_PIN); //读取超声波1距离CM
SR04 SR_Z = SR04(ECHO_PIN_Z, TRIG_PIN); //读取超声波2距离CM
SR04 SR_Y = SR04(ECHO_PIN_Y, TRIG_PIN); //读取超声波3距离CM
SR04 SR_H = SR04(ECHO_PIN_H, TRIG_PIN); //读取超声波4距离CM
void setup() {
for (int i = 0; i < 9; i++) pinMode(PWMPin, OUTPUT); //定义PWMpin为输出
Serial.begin(38400);
Serial1.begin(38400);
}
void loop() {
int j = 0;
while (Serial1.available() > 0)
{
comdata += char(Serial1.read());
delay(2);
mark = 1;
}
//读取的一组Serial的字符串
if (mark == 1)
{
for (int i = 0; i < comdata.length() - 1 ; i++)
{
if (comdata == ',')
{
j++;
}
else
{
numdata[j] = numdata[j] * 10 + (comdata - '0');
}
}
//将字符串以“,”分割并转换字符串为整数
for (int i = 0; i < 9; i = i + 1)
{
if (numdata < 45 || numdata > 0 )
{
numdata = numdata * 5;
}
else
{
numdata = 0;
}
//做判定,做占空比翻倍
analogWrite(PWMPin, numdata); //将占空比输出到对应的PIN上
Serial.print("PIN:");
Serial.print(PWMPin);
Serial.print("PWM:");
Serial.println(numdata);
on_off = numdata[8];
numdata = 0; //清空数组和临时数据
}
mark = 0; //清空数组和临时数据
comdata = String(""); //清空数组和临时数据
}
if (on_off == 25 )
{
if (SR_Z.Distance() <= 30 || SR_Q.Distance() <= 60 && SR_Y.Distance() >= 50)
{
Serial.println("LEFT OBSTRUCTIVE! ");
analogWrite(1, 175);
analogWrite(2, 0);
analogWrite(3, 100);
analogWrite(4, 0);
delay(500);
}
//判定左边和前方有障碍后右拐
if (SR_Y.Distance() <= 30 || SR_Q.Distance() <= 60 && SR_Z.Distance() >= 50)
{
Serial.println("RIGHT OBSTRUCTIVE! ");
analogWrite(1, 100);
analogWrite(2, 0);
analogWrite(3, 175);
analogWrite(4, 0);
delay(250);
}
//判定右边和前方有障碍后左拐
if (SR_Z.Distance() <= 30 && SR_Y.Distance() <= 30 && SR_Y.Distance()<= 50)
{
Serial.println("BACK OBSTRUCTIVE! ");
analogWrite(1, 0);
analogWrite(2, 170);
analogWrite(3, 0);
analogWrite(4, 100);
delay(500);
}
//判定左边和右边有障碍后倒车左拐
analogWrite(1, 200);
analogWrite(3, 200);
Serial.print("Q:"); Serial.print(SR_Q.Distance()); Serial.print(" ");
Serial.print("Z:"); Serial.print(SR_Z.Distance()); Serial.print(" ");
Serial.print("Y:"); Serial.print(SR_Y.Distance()); Serial.print(" ");
Serial.print("H:"); Serial.print(SR_H.Distance()); Serial.println(" ");
delay(200);
}
}
|
| |