Confused about handling bytes
| From: | Joe Veldhuis | Date: | Mon, 21 May 2007 00:50:27 +0000 |
| Subject: | Confused about handling bytes | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-255260@lists.php.net to get a copy of this message | ||
While I'm sure this is a stupid question and the solution will be obvious to everyone here, this is confusing me.
I'm trying to control a device over a serial port using a PHP script, and one of the things I need to do is read a 26-byte string from an EEPROM, using a command that returns two bytes at a time, and write similar strings using a similar command. For example, to read the first two bytes of one such string beginning at address 0x484, I would send:
04 84 00 00 BB
Here's the code I've written so far:
$string = 1; //which of 200 strings I want to read
$base = pack("H*",dechex((($string-1)*hexdec(0x1a))+hexdec(0x484))); //calculate the base address of the string (the first starts at 0x484)
for($i=0;$i < 13;$i++) { //iterate 13 times (26 bytes / 2 bytes at a time)
dio_write($serial,$base."\x00\x00\xbb",5); //send the command
$output[] = dio_read($serial,1); // read first byte
$output[] = dio_read($serial,1); // read second byte
$base = pack("H*",dechex(hexdec(bin2hex($base))+2)); //increment address
}
There are two things wrong with this. First, the final line isn't doing what it's supposed to. Instead of adding 2 to the value of $base each time, It's producing a pattern like this:
0x484, 0x486, 0x73, 0x73, 0x73, 0x488, 0x48a, 0x48c, 0x48e, 0x490, 0x74, 0x74, 0x74
Second, the format of $base doesn't seem to be handled correctly in line 4 of the above code. Given a value of 0x484, this line should write the bytes "04 84", but it is obviously not doing so, given the response I get from the device (it sends "FF FF" instead of the expected value at that address, which I get when I remove the variable and manually specify the address).
What are the solutions to these problems?
Thanks,
-Joe Veldhuis