且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用超声波传感器和arduino控制机器人手臂

更新时间:2023-11-19 12:34:52

目前尚不清楚,您要求的是什么,但您要搜索的第一点是在 NewPing文档



提示:对于清晰的代码,在顶部写入标题是最先进的,而不是实现和初始化:



  #include   <   servo.h  &GT; 跨度>; 
#include < newping.h >
// 以常量开头
#define echopin 11 //设置echopin(我希望你知道为什么这个值)
#define trigpin 12 // set trigpin(我希望你知道为什么这个值)

const int MAX_DISTANCE = 400 ; // 更适合类型检查
// 实现全局对象
Servo robotArm;
NewPing声纳(trigpin,echopin,MAX_DISTANCE);
int distance = MAX_DISTANCE; // initialize&lt ; /newping.h>&LT; /servo.h> 跨度>


#define echopin 11 //set echopin
#define trigpin 12 //set trigpin
#include <servo.h>;
Servo robotArm;
#include <newping.h>
#define MAX_DISTANCE 400
NewPing sonar(trigpin, echopin, MAX_DISTANCE);
int distance;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  robotArm.attach(9); //attach our servo
  robotArm.writeMicroseconds(150);
}

void loop() {
  // put your main code here, to run repeatedly:
  robotArm.write(90); //always set to servo 90 to position it to the middle
  //codes of ultrasonic sensor
  distance=digitalRead(echopin);
  if (distance <= 20) //if ultrasonic sensor detects on obstacle less than 20 cm in 90 degree angle
  {
    robotArm.write(0); //dervo rotates at full speed to the right
    delay(60);
  }
  else
  {
    robotArm.write(90); //else servo stays at 90 degree angle
    delay(60);
  }
  Serial.print(distance); //print distance
  Serial.println("cm"); //print distance unit cm
}



What I have tried:

I'm working about arduino and HC_SR04. I searced most of documents, but I didnt solve our problem. My question is that how to read a value that is taken from library NewPing. Thanks

It is not clear, what you are asking for, but the first point where you should search is in the NewPing documentation.

Tip: for clear code it is state of art to write the headers at top, and than implement and initialize like that:

#include <servo.h>;
#include <newping.h>
//start with constants
#define echopin 11 //set echopin (I hope you know why that value)
#define trigpin 12 //set trigpin (I hope you know why that value)

const int MAX_DISTANCE = 400;//better for type checks
//implement global objects
Servo robotArm;
NewPing sonar(trigpin, echopin, MAX_DISTANCE);
int distance = MAX_DISTANCE;//initialize</newping.h></servo.h>