title: Serial Port Reading with PHP weirdness
body: <p>I have a project already written in PHP.  I need to read data in from the serial port.  I would like to keep the ability to read from the serial port in the same language as the rest of the project.</p>
  
  <p>I found a class that many people seem to be having problems with.  php_serial.class.php  Based on examples this is what I wrote for it as a test.  Using an RFID card reader as the serial input.</p>
  
  <pre><code>#!/usr/bin/php
  &lt;?php
  
  // Include the class to read the serial line.
  include ("php_serial.class.php");
  
  // Let's start the class
  $serial = new phpSerial;
  
  $serial-&gt;deviceSet("/dev/ttyAMA0");
  $serial-&gt;confBaudRate(9600);
  $serial-&gt;confParity("none");
  $serial-&gt;confCharacterLength(8);
  $serial-&gt;confStopBits(1);
  // We can change the baud rate, parity, length, stop bits, flow control
  #$serial-&gt;confFlowControl("none");
  
  // Check if we can open the serial line.  Otherwise die.
  if(!$serial-&gt;deviceOpen()) die("unable to open device");
  
  stream_set_timeout($serial-&gt;_dHandle, 10);
  
  $rfid_key = FALSE;
  
  // Start the loop to keep checking the
  while(!$rfid_key)
  {
      $read = $serial-&gt;readPort();
  
      // Array to store eachvalue of the RFID tag
      $ascii_read  = array();
  
      for($i = 0; $i &lt; strlen($read); $i++)
      {
          $ascii_read[] = ord($read[$i]);
          if(count($ascii_read) == 14 &amp;&amp; $ascii_read[0] == 2 &amp;&amp; $ascii_read[13] == 3)
          {
              $rfid_key = implode("", $ascii_read);
              break;
          }
      }
  
      // If the key is empty then sleep for 1 second.
      if(!$rfid_key)
      {
          sleep(1);
      }
  }
  
  print_r($rfid_key);
  print "\n\n";
  </code></pre>
  
  <p>If I run the script it will wait for an input, and if I flash an RFID tag over the antenna it fails.</p>
  
  <p>I then decided to see if it was php or not, so I wrote a python script.</p>
  
  <pre><code>import serial
  serialport = serial.Serial("/dev/ttyAMA0", 9600, timeout=0.5)
  response = serialport.readlines(None)
  print response
  </code></pre>
  
  <p>If I put the tag on the antenna and run the script and then pull the tag away, I get whatever number of instances of the tag it read in that timespan.  Telling me that the RFID reader works with the RaspberryPi.</p>
  
  <p>Now here's the really odd part.  If I go back and execute the php code after executing the python code then it works.  This leads me to believe that it has something to do with instantiation of the serial port done in Python that sticks around for the php code when it is executed afterwards.  I then strip down the python code to just instantiate the serial port and exit and as expected the php code works.</p>
  
  <p>So, my question is.  WTF is python doing that the php code is not?  I am not an expert with the serial bus and am very confused atm.</p>