Mysterious serial bytes

I’m converting a RealBasic application I wrote a few years ago, to Xojo. With a bit of cleanup of some poor practices, like using threads instead of methods, things are now working as expected, with one (so far) exception. This application is for communicating with some serial devices, some of which are 7bit and others 8bit. The 7bit communication works just fine, but for reasons I can’t figure out, when I try to communicate in 8bit, extra bytes get inserted in the sent string. For example, In RealBasic the sent string is correct as:
05 04 04 B5 00 02 60 99
But in Xojo the string gets sent as:
05 04 04 C2 B5 00 02 60 C2 99

In the strings I’ve tried, I’ve seen C2 and C3 as the renegade bytes. I have no idea where they are coming from. Any ideas?

My serial port setup seems quite simple:

Serial1.SerialPort = System.SerialPort(ComPort-1)
Serial1.Baud = Serial.Baud9600
Serial1.Stop = Serial.StopBits1

If Protocol = “modbus” then
Serial1.Parity = Serial.ParityNone
Serial1.Bits = Serial.Bits8
Serial1.Parity = Serial.ParityEven
Serial1.Bits = Serial.Bits7
End If

// Open the device for communications
if not Serial1.Open then
MsgBox “Could not open the serial port!”
Exit Sub
If Protocol = “modbus” Then
end if
End If

ModBusCmd sends the 8bit string that gets messed up. SendRequest sends the 7bit string. The 8bit looks like this:

Serial1.Write Chr(&h05) + Chr(&h04) + Chr(&h04) + Chr(&hB5) + Chr(&h00) + Chr(&h02) + Chr(&h60) + Chr(&h99)

You are writing as UTF-8, hence the extra byte. Use ChrB instead.

Great! Thanks Kem. What is the difference between Chr and ChrB?

From Real Studio language reference:
“ChrB should be used rather than Chr when value represents binary data.”

Nun said.

Thanks again

Chr( x ) says, “I want the character represented by Unicode code point x output with UTF-8 encoding.” Characters from 0 to 127 will be represented by a single byte, but anything over 127 will be represented by two, three, or even four bytes.

ChrB( x ) means, “I want byte x”, as I see you discovered.