×

使用Arduino的自控机器人汽车

消耗积分:2 | 格式:zip | 大小:0.16 MB | 2022-11-16

李勇

分享资料个

描述

一、简介

使用 Arduino 的自控机器人汽车。

这辆机器人汽车使用超声波传感器来检测前方的障碍物,每当它检测到障碍物时,它的超声波传感器就会在左右两个方向上移动,以计算出自由移动的最佳距离。

它的超声波传感器范围高达 150 厘米。

2. 示范

3. 制作这款机器人汽车的步骤

在 Arduino IDE 中导入 Servo.h 和 NewPing.h 库。

// Library
#include         // Include Servo Library
#include       // Include Newping Library 

初始化引脚

// L298N Control Pins
const int LeftMotorForward = 4;
const int LeftMotorBackward = 5;
const int RightMotorForward = 6;
const int RightMotorBackward = 7;
const int LEDext = 1;
const int Buzzer = 0;

#define TRIGGER_PIN  A1  // Arduino pin to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     A2  // Arduino pin to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 250 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 250cm.

创建对象和变量

Servo servo_motor;  // Servo's name
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
boolean goesForward = false;
int distance = 50;

编写 Arduino 代码的设置部分

 void setup()
{
// Set L298N Control Pins as Output
pinMode(RightMotorForward, OUTPUT);
pinMode(LeftMotorForward, OUTPUT);
pinMode(LeftMotorBackward, OUTPUT);
pinMode(RightMotorBackward, OUTPUT);
pinMode(LEDext, OUTPUT);        //set led as output
pinMode(Buzzer, OUTPUT);        //set buzzer as output
servo_motor.attach(9);   // Attachs the servo on pin 9 to servo object.
servo_motor.write(115);   // Set at 115 degrees.
delay(2000);              // Wait for 2s.
distance = readPing();    // Get Ping Distance.
delay(100);               // Wait for 100ms.
}

编写 Arduino 代码的无效循环部分

void loop() 
{  
  int distanceRight = 0;  //Initialize right side distance                                              
  int distanceLeft = 0;   //Initialize left side distance
  delay(50);

  if (distance <= 30)   //If distance of obstacle less than 30 cm from robot 
  {
    Stop();   //call stop function to stop the robot
    digitalWrite(LEDext, HIGH);   //Turn led ON
    digitalWrite(Buzzer, HIGH);   //Turn Buzzer ON
    delay(300);   //wait for 300ms
    moveBackward();   //call moveBackward function to move robot in backward direction
    
    delay(400);   //wait for 400ms
    Stop();   //call stop function to stop the robot
    
    delay(300);   //wait for 300ms
    distanceRight = lookRight();    //call lookRight function to save distance in distanceRight variable
    
    delay(300);   //wait for 300ms
    distanceLeft = lookLeft();    //call lookLeft function to save distance in distanceLeft variable
    
    delay(300);   //wait for 300ms

    if (distanceRight >= distanceLeft)    //If distance of right greater or equall to distance of left
    {
      turnRight();    //call function to turn right robot
      delay(300);   //wait for 300ms
      Stop();   //call stop function to stop robot
    }
    else //else
    {
      turnLeft();   //call function to turn left robot
      delay(300);   //wait for 300ms
      Stop();   //call stop function to stop robot
    }
  
  }
  else    //else
  {
    moveForward();    //call moveForward function to move robot in forward direction 
  }

    distance = readPing();    //call readPing function to calculate Distance
}

制作计算右侧距离的函数

int lookRight()     // lookRight Function for Servo Motor
{  
  servo_motor.write(0);   //make servo position at 0 degree
  delay(500);   //wait for 500ms
  int distance = readPing();    //read distance
  delay(100);   //wait for 100ms
  servo_motor.write(90);    //make servo position 90 degree
  return distance;    //return distance whenever lookRight function is called
}

制作计算左侧距离的函数

int lookLeft()      // lookLeft Function for Servo Motor 
{
  servo_motor.write(180);   //make servo position at 0 degree
  delay(500);   //wait for 500ms
  int distance = readPing();    //read distance
  delay(100);   //wait for 100ms
  servo_motor.write(90);    //make servo position 90 degree
  return distance;    //return distance whenever lookLeft function is called
} 

使功能与超声波传感器保持距离

int readPing()      // readPing Function for Ultrasonic Sensor.
{
  delay(100);                 // Wait 100ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  int cm = sonar.ping_cm();   //Send ping, get ping distance in centimeters (cm).
  if (cm==0)
  {
    cm=250;
  }
  return cm;    //return distance whenever readPing function is called
} 

制作停止机器人的功能

void Stop()       // Stop Function for Motor Driver.
{
  digitalWrite(RightMotorForward, LOW);
  digitalWrite(RightMotorBackward, LOW);
  digitalWrite(LeftMotorForward, LOW);
  digitalWrite(LeftMotorBackward, LOW);
} 

使机器人向前移动的功能

void moveForward()    // Move Forward Function for Motor Driver.
{
    digitalWrite(RightMotorForward, HIGH);
    digitalWrite(RightMotorBackward, LOW);
    digitalWrite(LeftMotorForward, HIGH);
    digitalWrite(LeftMotorBackward, LOW);
    digitalWrite(LEDext, LOW);
    digitalWrite(Buzzer, LOW);
}

使机器人向后移动的功能

void moveBackward()   // Move Backward Function for Motor Driver.
{
  digitalWrite(RightMotorForward, LOW);
  digitalWrite(RightMotorBackward, HIGH);
  digitalWrite(LeftMotorForward, LOW);
  digitalWrite(LeftMotorBackward, HIGH);
} 

使机器人向右移动的功能

void turnRight()      // Turn Right Function for Motor Driver.
{
  digitalWrite(RightMotorForward, LOW);
  digitalWrite(RightMotorBackward, HIGH);
  digitalWrite(LeftMotorForward, HIGH);
  digitalWrite(LeftMotorBackward, LOW);
} 

使机器人在左侧方向移动的功能

void turnLeft()       // Turn Left Function for Motor Driver.
{
  digitalWrite(RightMotorForward, HIGH);
  digitalWrite(RightMotorBackward, LOW);
  digitalWrite(LeftMotorForward, LOW);
  digitalWrite(LeftMotorBackward, HIGH);
} 

将代码上传到您的 Arduino 板。

4. 按照原理图连接所有组件。


声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

评论(0)
发评论

下载排行榜

全部0条评论

快来发表一下你的评论吧 !

'+ '

'+ '

'+ ''+ '
'+ ''+ ''+ '
'+ ''+ '' ); $.get('/article/vipdownload/aid/'+webid,function(data){ if(data.code ==5){ $(pop_this).attr('href',"/login/index.html"); return false } if(data.code == 2){ //跳转到VIP升级页面 window.location.href="//m.lene-v.com/vip/index?aid=" + webid return false } //是会员 if (data.code > 0) { $('body').append(htmlSetNormalDownload); var getWidth=$("#poplayer").width(); $("#poplayer").css("margin-left","-"+getWidth/2+"px"); $('#tips').html(data.msg) $('.download_confirm').click(function(){ $('#dialog').remove(); }) } else { var down_url = $('#vipdownload').attr('data-url'); isBindAnalysisForm(pop_this, down_url, 1) } }); }); //是否开通VIP $.get('/article/vipdownload/aid/'+webid,function(data){ if(data.code == 2 || data.code ==5){ //跳转到VIP升级页面 $('#vipdownload>span').text("开通VIP 免费下载") return false }else{ // 待续费 if(data.code == 3) { vipExpiredInfo.ifVipExpired = true vipExpiredInfo.vipExpiredDate = data.data.endoftime } $('#vipdownload .icon-vip-tips').remove() $('#vipdownload>span').text("VIP免积分下载") } }); }).on("click",".download_cancel",function(){ $('#dialog').remove(); }) var setWeixinShare={};//定义默认的微信分享信息,页面如果要自定义分享,直接更改此变量即可 if(window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger'){ var d={ title:'使用Arduino的自控机器人汽车',//标题 desc:$('[name=description]').attr("content"), //描述 imgUrl:'https://'+location.host+'/static/images/ele-logo.png',// 分享图标,默认是logo link:'',//链接 type:'',// 分享类型,music、video或link,不填默认为link dataUrl:'',//如果type是music或video,则要提供数据链接,默认为空 success:'', // 用户确认分享后执行的回调函数 cancel:''// 用户取消分享后执行的回调函数 } setWeixinShare=$.extend(d,setWeixinShare); $.ajax({ url:"//www.lene-v.com/app/wechat/index.php?s=Home/ShareConfig/index", data:"share_url="+encodeURIComponent(location.href)+"&format=jsonp&domain=m", type:'get', dataType:'jsonp', success:function(res){ if(res.status!="successed"){ return false; } $.getScript('https://res.wx.qq.com/open/js/jweixin-1.0.0.js',function(result,status){ if(status!="success"){ return false; } var getWxCfg=res.data; wx.config({ //debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId:getWxCfg.appId, // 必填,公众号的唯一标识 timestamp:getWxCfg.timestamp, // 必填,生成签名的时间戳 nonceStr:getWxCfg.nonceStr, // 必填,生成签名的随机串 signature:getWxCfg.signature,// 必填,签名,见附录1 jsApiList:['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); wx.ready(function(){ //获取“分享到朋友圈”按钮点击状态及自定义分享内容接口 wx.onMenuShareTimeline({ title: setWeixinShare.title, // 分享标题 link: setWeixinShare.link, // 分享链接 imgUrl: setWeixinShare.imgUrl, // 分享图标 success: function () { setWeixinShare.success; // 用户确认分享后执行的回调函数 }, cancel: function () { setWeixinShare.cancel; // 用户取消分享后执行的回调函数 } }); //获取“分享给朋友”按钮点击状态及自定义分享内容接口 wx.onMenuShareAppMessage({ title: setWeixinShare.title, // 分享标题 desc: setWeixinShare.desc, // 分享描述 link: setWeixinShare.link, // 分享链接 imgUrl: setWeixinShare.imgUrl, // 分享图标 type: setWeixinShare.type, // 分享类型,music、video或link,不填默认为link dataUrl: setWeixinShare.dataUrl, // 如果type是music或video,则要提供数据链接,默认为空 success: function () { setWeixinShare.success; // 用户确认分享后执行的回调函数 }, cancel: function () { setWeixinShare.cancel; // 用户取消分享后执行的回调函数 } }); //获取“分享到QQ”按钮点击状态及自定义分享内容接口 wx.onMenuShareQQ({ title: setWeixinShare.title, // 分享标题 desc: setWeixinShare.desc, // 分享描述 link: setWeixinShare.link, // 分享链接 imgUrl: setWeixinShare.imgUrl, // 分享图标 success: function () { setWeixinShare.success; // 用户确认分享后执行的回调函数 }, cancel: function () { setWeixinShare.cancel; // 用户取消分享后执行的回调函数 } }); //获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口 wx.onMenuShareWeibo({ title: setWeixinShare.title, // 分享标题 desc: setWeixinShare.desc, // 分享描述 link: setWeixinShare.link, // 分享链接 imgUrl: setWeixinShare.imgUrl, // 分享图标 success: function () { setWeixinShare.success; // 用户确认分享后执行的回调函数 }, cancel: function () { setWeixinShare.cancel; // 用户取消分享后执行的回调函数 } }); //获取“分享到QQ空间”按钮点击状态及自定义分享内容接口 wx.onMenuShareQZone({ title: setWeixinShare.title, // 分享标题 desc: setWeixinShare.desc, // 分享描述 link: setWeixinShare.link, // 分享链接 imgUrl: setWeixinShare.imgUrl, // 分享图标 success: function () { setWeixinShare.success; // 用户确认分享后执行的回调函数 }, cancel: function () { setWeixinShare.cancel; // 用户取消分享后执行的回调函数 } }); }); }); } }); } function openX_ad(posterid, htmlid, width, height) { if ($(htmlid).length > 0) { var randomnumber = Math.random(); var now_url = encodeURIComponent(window.location.href); var ga = document.createElement('iframe'); ga.src = 'https://www1.elecfans.com/www/delivery/myafr.php?target=_blank&cb=' + randomnumber + '&zoneid=' + posterid+'&prefer='+now_url; ga.width = width; ga.height = height; ga.frameBorder = 0; ga.scrolling = 'no'; var s = $(htmlid).append(ga); } } openX_ad(828, '#berry-300', 300, 250);