PHP 教學 - windows 7 環境下 xampp 透過php控制arduino

首先先把arduino接上usb跟電腦相連
   
const int ledPin = 13; // the pin that the LED
int incomingByte;      // a variable to read incoming serial data into
 
void setup() {
  // initialize serial communication:
  Serial.begin(9600);
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
}
 
void loop() {
  // see if there's incoming serial data:
  if (Serial.available() > 0) {
    // read the oldest byte in the serial buffer:
    incomingByte = Serial.read();
    // if it's a capital H (ASCII 72), turn on the LED:
    if (incomingByte == 'H') {
      digitalWrite(ledPin, HIGH);
    }
    // if it's an L (ASCII 76) turn off the LED:
    if (incomingByte == 'L') {
      digitalWrite(ledPin, LOW);
    }
  }
}

接下來就是PHP部分拉
首先我們程式是連9600的 所以PHP裡面也是寫9600 然後我的電腦ARDUINO目前是連接到COM4 這個每個人電腦都不一樣 你的可能是COM3之類的 就要修改一下PHP程式
然後因為我們ARDUINO程式設定說打上H 就是開LED 打上L就是關閉LED 所以PHP這邊就會有 openSerial(“H"); 這個東西出來
   
<?php
function openSerial($command) {
    $openSerialOK = false;
    try {
        exec("mode com4: BAUD=9600 PARITY=n DATA=8 STOP=1 to=off dtr=off rts=off");
        $fp =fopen("com7", "w");
        //$fp = fopen('/dev/ttyUSB0','r+'); //use this for Linux
        $openSerialOK = true;
    } catch(Exception $e) {
        echo 'Message: ' .$e->getMessage();
    }

    if($openSerialOK) {
        fwrite($fp, $command); //write string to serial
        fclose($fp);
    }  
}

openSerial("Without this line, the first control will not work. I don't know way.");

if(isset($_POST['submit1'])) {
    openSerial("H");
}

if(isset($_POST['submit2'])) {
    openSerial("L");
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
   <input type="submit" name="submit1" value="1 on"><br>
   <input type="submit" name="submit2" value="1 off"><br>
</form>

就這樣 就可以透過php去執行



實驗結果發現到如果 arduino 序列監控螢幕開啟時,會造成 com port 被占用的情況,就無法連線,這點需要注意!

其實除了利用 php 來控制 arduino,另一個最好的應用就是從 arduino 收資料,目前我們若想要從 arduino 上裝 sensor 收資料並送到 mysql 其實有好幾種方式,例如利用 arduino 網卡並建立 get post 的方式傳遞資料,或者是與 raspberry pi 連接,將資料送給 raspberry pi,或者是利用 Tera Term 存 log 檔,透過 php 讀檔寫入 mysql,那麼有了 serial port 我們就可以利用 php 直接收 arduino 的資料,這邊我是利用 php dio 的方式來跟 arduino 溝通,首先先安裝 php_dio.dll 並在 php.ini 中啟用 extension=php_dio.dll

範例程式如下:
<?php
exec('mode COM4: baud=9600 data=8 stop=1 parity=n');
$fd = dio_open('COM4:', O_RDWR);
while (1) {
    $data = dio_read($fd, 1);
    if ($data) {
        echo $data;
    }
}
dio_close($fd);
?>
該程式是利用 cmd 下 php 命令來執行
  
另一個小技巧,就是可以透過 cmd 下指令來檢查 com port 連線現態,因為 arduino usb 線本身就是 rs232!!只是沒有做成公母頭而已,但當我們下 mode com4 /status 一樣能快速得知連線是否正常。


留言

  1. $fp =fopen("com7", "w"); 是這行要進行com port的修改嗎

    回覆刪除
  2. 您好,想請教如果想將arduino DHT11測到的溫度值顯示在php網頁上,要如何做?感謝。

    回覆刪除

張貼留言

這個網誌中的熱門文章

c語言-關於#define用法

PHP教學 - 資料型態(Data Type) - 上

CMD常用網管指令