I've been searching for the last two weeks to solve a simple problem but have no luck. I'm registering so I can ask the experts here at Arduino.
Here's the operating system specs
OS: Windows XP
Programs: Apache PHP
Hardware: Arduino nano v3, USB communication via COM3 port
Arduino Code (pseudo code):
I send the Arduino a command (read something), it read a port and send back a number via Serial.print().
Results: this works great when I use the Arduino's compiler (v1.0.1) or serial monitor to send and receive command
The problems:
Sending the commands via PHP or sending anything to Arduino works great, it picks up everything.
BUTTTT, reading from the serial COM port is a bigggg problem
PHP code:
<?php
exec (`mode COM3: BAUD=9600 PARITY=N data=8 stop=1 xon=off`);
if (@$fp=fopen("COM3", "rb+")) {
fwrite($fp, "r"); //tell Arduino to read
sleep(5); //wait 5 seconds before getting result
$raw="";
$raw=stream_get_contents($fp); //this doesn't work
//$raw=fread($fp,4096); //this doesn't work
//$raw=fget($fp,4096); //this doesn't work
/******The below doesn't work
while(!feof($fp)){
$raw.=stream_get_contents($fp, 2);
}
******/
fclose($fp);
}
echo $raw;
?>
Here is what I observed:
When arduino board first turn on (plug into my usb, without using Arduino's Serial Monitor ),
Using PHP:
- I CAN use fwrite
- I CAN NOT use fread even with delays
- I CAN NOT use stream_get_contents
Here is what weird....
When arduino board first turn on (plug into my usb),
Using Arduino's 1.0.1 compiler serial monitor:
- I open the serial monitor
- I send it a command and received a response
- I then closed the serial monitor
After using the Arduino's serial monitor or compiler without switching the board off - I CAN use fwrite
- I CAN use fread
- I CAN use stream_get_contents
I'm sure the solution lies somewhere in how the Arduino first initiate the board and the COM port to allow fread to access it freely. Without first initializing the Arduino through the Arduino's compiler, I CAN NOT access the board using fread, I can send command to it just fine.
I'm sure someone with more experience in how Arduino initiate the COM port can solve this. I've searched the web for two weeks and have not found the answer. The "Google God" did not provide an answer this time. Please help.
**TLDR: ** fread doesn't work unless you first run Arduino's "Serial Monitor" or compiler to talk to it first
Begging for solutions. Sincerely, CooCooWorld