-->

C# SerialPort.Write not sending all bytes when 0xC

2019-09-18 17:30发布

问题:

I am trying to send some binary data over the serial port. I send 512 byte pages at a time and use ASCII for control commands. I have about 150 pages to send and they all work fine except for page 97.

Page 97 byte 330 is 0xCC. If I change it to anything else the page sends properly. If it is 0xCC SerialPort.Write only sends 509 bytes instead of 512 bytes. The exact sequence of bytes around there is:

...2E 21 96 CC 33 D1 05 81...

My code looks like this:

var buffer = new byte[512 * 256];   // 512 bytes per page, 256 pages on a 128k device

for (int j = 0; j < buffer_count; j += 8)
    comport.Write(buffer, buffer_offset + j, 8);

If you are wondering why I send 8 bytes at a time it is because if you send all 512 in one Write() it doesn't work at all with any page. Some amount less than 512 bytes is sent and no amount of flushing or waiting will change that, but when you do your next write it will include a load of random characters from the page at the start. SerialPort seems to be quite badly broken...

Anyway, as I said this works for every page except no. 97. I tried changing encoding as MSDN suggested that the byte array would be encoded but it didn't help. I tried Unicode (UTF16), UTF8 and various code pages. Unicode reduces the number of missed bytes from 3 to 2.

System.Text.Encoding iso_8859_1 = System.Text.Encoding.GetEncoding("iso-8859-1");
comport.Encoding = iso_8859_1;

or

comport.Encoding = System.Text.Encoding.UTF8;

I also tried sending a single byte at a time with Write(), didn't make any difference.

It honestly looks like SerialPort can't send raw bytes to the port. Surely that can't be the case.


Okay, I tried this:

comport.Encoding = System.Text.Encoding.UTF8;
var page_buf = new byte[512];
for (int j = 0; j < 512; j++)
    page_buf[j] = buffer[buffer_offset + j];
var tempstr = Encoding.UTF8.GetString(page_buf);
comport.Write(tempstr);
comport.Encoding = System.Text.Encoding.ASCII;

It fixed page 97 but broke page 2. I don't think messing with encoding will work, I need to just send raw bytes to the port. If it makes any difference this is a USB serial port.