arduino

[arduino] 電腦透過php控制arduino

用VB控制arduino應該有不少範例才對,不過我想透過網頁來控制我的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);
    }
  }
}

燒完後 你可以到 COM的界面去輸入H或是L 你應該可以看到ARDUINO板上的LED燈被打開或關閉,要是會亮就代表目前為止都沒問題

接下來就是PHP部分拉
首先我們程式是連9600的 所以PHP裡面也是寫9600 然後我的電腦ARDUINO目前是連接到COM7 這個每個人電腦都不一樣 你的可能是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去執行