Re: Confused about handling bytes

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi,

Monday, May 21, 2007, 10:50:27 AM, you wrote:
JV> While I'm sure this is a stupid question and the solution will be 
JV> obvious to everyone here, this is confusing me.

JV> I'm trying to control a device over a serial port using a PHP script, 
JV> and one of the things I need to do is read a 26-byte string from an 
JV> EEPROM, using a command that returns two bytes at a time, and write 
JV> similar strings using a similar command. For example, to read the first
JV> two bytes of one such string beginning at address 0x484, I would send:

JV> 04 84 00 00 BB

JV> Here's the code I've written so far:

JV> $string = 1; //which of 200 strings I want to read
JV> $base = pack("H*",dechex((($string-1)*hexdec(0x1a))+hexdec(0x484))); 
JV> //calculate the base address of the string (the first starts at 0x484)
JV> for($i=0;$i < 13;$i++) { //iterate 13 times (26 bytes / 2 bytes at a time)
JV> dio_write($serial,$base."\x00\x00\xbb",5); //send the command
JV> $output[] = dio_read($serial,1);  // read first byte
JV> $output[] = dio_read($serial,1); // read second byte
JV> $base = pack("H*",dechex(hexdec(bin2hex($base))+2)); //increment address
JV> }

JV> There are two things wrong with this. First, the final line isn't doing
JV> what it's supposed to. Instead of adding 2 to the value of $base each 
JV> time, It's producing a pattern like this:

JV> 0x484, 0x486, 0x73, 0x73, 0x73, 0x488, 0x48a, 0x48c, 0x48e, 0x490, 0x74,
JV> 0x74, 0x74

JV> Second, the format of $base doesn't seem to be handled correctly in line
JV> 4 of the above code. Given a value of 0x484, this line should write the
JV> bytes "04 84", but it is obviously not doing so, given the response I 
JV> get from the device (it sends "FF FF" instead of the expected value at
JV> that address, which I get when I remove the variable and manually 
JV> specify the address).

JV> What are the solutions to these problems?

JV> Thanks,
JV> -Joe Veldhuis


Do your packing after all the calculations:

<?php
$output = array();
$string = 1;
for(
  $i=0, $base = (($string-1) * 26) + 0x484; 
  $i < 26;
  $i++, $base += 2)
{
    $binarydata = pack("nc*", $base, 0, 0, 0xBB);
    dio_write($serial,$k=strlen($binarydata),5); //send the command
    $output[] = dio_read($serial,1);  // read first byte
    $output[] = dio_read($serial,1); // read second byte
}

-- 
regards,
Tom

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux