我把XYZ搖頭鈕來操控伺服馬達轉動+超音波測距模組
程式編譯OK,但是執行的時候兩種訊號會互相干擾,比如說執行時,伺服馬達會亂跳、超音波測距的距離只剩四公分(正常可到400cm)
下面是我的程式,請高手幫我解決此問題!!感謝
#include <Servo.h>
Servo myservo;
int value = 0;
int JoyStick_X = 0; //x
int JoyStick_Y = 1; //y
int JoyStick_Z = 3; //key
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Ultrasonic.h>
#define TRIGGER_PIN 12
#define ECHO_PIN 13
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
Ultrasonic ultrasonic(TRIGGER_PIN, ECHO_PIN);
void setup()
{
myservo.attach(9);
pinMode(JoyStick_Z, INPUT);
lcd.init(); // initialize the lcd
lcd.backlight();
lcd.print("Ping)))");
Serial.begin(9600); // 9600 bps
}
void loop()
{
int x,y,z;
x=analogRead(JoyStick_X);
y=analogRead(JoyStick_Y);
z=digitalRead(JoyStick_Z);
if(y>600)
value = 80;
if(x<10)
value = 20;
if(y<300)
value = 0;
myservo.write(value);
Serial.print(x ,DEC);
Serial.print(",");
Serial.print(y ,DEC);
Serial.print(",");
Serial.println(z ,DEC);
delay(500);
float cmMsec, inMsec;
long microsec = ultrasonic.timing();
cmMsec = ultrasonic.convert(microsec, Ultrasonic::CM); // 計算距離,單位: 公分
lcd.setCursor(0, 1);
lcd.print("Dist: ");
if(cmMsec>200)
lcd.print(", safe: ");
if(cmMsec<200)
lcd.print(cmMsec);
delay(200);
} |