How can I write the value 255 to the serial port in Powershell ?
$port= new-Object System.IO.Ports.SerialPort COM6,4800,None,8,one
$port.open()
$port.Write([char]255)
$port.Close()
The output of the previous script is 63 (viewed with a serial port monitor).
However $port.Write([char]127)
gives 127 as result. If the value is higher than 127 the output is always 63.
Thanks in advance for your help !
Despite your attempt to use [char]
, your argument is treated as [string]
, because PowerShell chooses the following overload of the Write
method, given that you're only passing a single argument:
void Write(string text)
The documentation for this particular overload states (emphasis added):
By default, SerialPort uses ASCIIEncoding to encode the characters. ASCIIEncoding encodes all characters greater than 127 as (char)63 or '?'. To support additional characters in that range, set Encoding to UTF8Encoding, UTF32Encoding, or UnicodeEncoding.
To send byte values, you must use the following overload:
void Write(byte[] buffer, int offset, int count)
That requires you to:
[byte[]]
to cast your byte value(s)offset
- the starting byte position as well as count
, the number of bytes to copy from the starting byte position.In your case:
$port.Write([byte[]] (255), 0, 1)
Note: The (...)
around 255
isn't required for a single value, but would be necessary to specify multiple, ,
-separated values.
Note:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With