0

我想通过 PHP 获得与 HC-Sr04 超声波传感器的距离以及笔记本电脑上显示的 LED 灯的颜色,谁能帮助我被困在这里.. 提前致谢

我的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);
  }
  }
4

1 回答 1

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的串口监视器调试!

祝你好运!

欲了解更多信息: https ://systemsarchitect.net/2013/01/26/connecting-php-with-arduino-via-serial-port-on-linux/

于 2017-05-24T08:05:22.763 回答