2017-05-24 65 views
0

我想通過PHP 獲取HC-Sr04超聲波傳感器與我筆記本電腦上顯示的LED燈顏色的距離任何人都可以請幫我卡在這裏.. 在此先感謝如何通過php獲取hcsr04超聲波傳感器在桌面上的距離

我的PHP代碼..

<?php 
echo "<p>Control Page</p><p>"; 
$port = fopen("COM4", "w+"); 
sleep(2); 
?> 
<br> 
</form> 
<?php 
if ($_GET['distance']<30) 
{ 
$data = $_GET['distance']; 
echo '<td bgcolor="#FF0000"> red'; 
} 
else if ($_GET['distance']>35){ 
    $data = $_GET['distance']; 
    echo '<td bgcolor="#00FF00"> green'; 
} 
else { 
    echo "Empty"; 
    echo '<td bgcolor="#00FF00"> green'; 
} 
fclose($port); 
?> 
</body> 
</html> 

我的Arduino代碼:...

#define trigPin 10 
#define echoPin 2 
#define led 4 
#define led2 6 

void setup() { 
    Serial.begin (9600); 
    pinMode(trigPin, OUTPUT); 
    pinMode(echoPin, INPUT); 
    pinMode(led, OUTPUT); 
    pinMode(led2, OUTPUT); 
} 

void loop() { 
    long duration, distance; 
    digitalWrite(trigPin, LOW); // Added this line 
    delayMicroseconds(2); // Added this line 
    digitalWrite(trigPin, HIGH); 
    delayMicroseconds(10); // Added this line 
    digitalWrite(trigPin, LOW); 
    duration = pulseIn(echoPin, HIGH); 
    delay(1000); 
    distance = (duration/2)/29.1; 
    if (distance < 30) { // This is where the LED On/Off happens 
    digitalWrite(led,HIGH); // When the Red condition is met, the Green LED should turn off 
    digitalWrite(led2,LOW); 
} 
    else if(distance >35) { 
    digitalWrite(led,LOW); 
    digitalWrite(led2,HIGH); 
    } 
    else{ 
    digitalWrite(led,LOW); 
    digitalWrite(led2,LOW); 
    } 
    } 

回答

1

我假設你的工作與Linux。

首先你必須設置你的串口:

stty -F /dev/ttyACM0 cs8 9600 ignbrk -brkint -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts 

然後你可以使用FREAD/FWRITE

$fp =fopen("/dev/ttyACM0", "w+"); 
if(!$fp) { 
     echo "Error";die(); 
} 

fwrite($fp, $_SERVER['argv'][1] . 0x00); 
echo fread($fp, 10); 

fclose($fp); 

的Arduino將重新啓動在每次連接。

使用arduino的串口監視器進行調試!

祝你好運!

for more info: https://systemsarchitect.net/2013/01/26/connecting-php-with-arduino-via-serial-port-on-linux/

相關問題