rn9409 发表于 2017-7-25 09:57:09

平衡球與超音波

最近做了一個平衡球的實驗,但超音波讀取的值不是很正確。當超音波打到物體時,實際是1cm但超音波會讀到30,想問這是什麼問題?
如果想讓誤判30cm的值變成1cm,程式該怎麼修??

#include<Servo.h>
#include<PID_v1.h>
const int servoPin = 9;   //Servo Pin
float Kp = 1.8;                                                
float Ki = 0.075;                                                      
float Kd = 1.1;
double Setpoint, Input, Output, ServoOutput;                                       
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);                                                                                                                                                                                                                                                                                          
Servo myServo;                                                      

void setup() {

Serial.begin(9600);                                             
myServo.attach(servoPin);                                          
Input = readPosition();                                                                                                                                                                           
myPID.SetMode(AUTOMATIC);                                       
myPID.SetOutputLimits(-40,40);                                    
}

void loop()
{

Setpoint = 15;
Input = readPosition();                                          

myPID.Compute();                                                
myServo.write(93+ Output);                                       


}

float readPosition() {
delay(25);                                                         


const int pingPin = 11;
const int pingPin2 = 12;

long duration, cm;
unsigned long now = millis();
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin2, INPUT);
duration = pulseIn(pingPin2, HIGH);
cm = duration*(0.01724);



if(cm > 26)   cm=26;



Serial.println(cm);

return cm;                                       

}

wing 发表于 2017-7-25 10:02:58

平衡球的實驗 是什么? 有图么?

164335413 发表于 2017-7-27 09:15:57

正常的超声波模块应该使用10~25uS的脉冲触发,所以拉低一会儿之后需要将电平拉高10~20uS。
所以delayMicroseconds(5)改为delayMicroseconds(25)

rn9409 发表于 2017-7-27 20:29:01

本帖最后由 rn9409 于 2017-7-27 20:33 编辑


這是我做的結構

Super169 发表于 2017-7-28 01:46:35

你確定你的超聲波模塊, 最短距離可以達到 1cm 嗎?一般都是 2cm 以上的.
页: [1]
查看完整版本: 平衡球與超音波