Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell write value to serial port

Tags:

powershell

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 !

like image 233
Spectrum Avatar asked Oct 16 '22 23:10

Spectrum


1 Answers

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:

  • use cast [byte[]] to cast your byte value(s)
  • and specify values for 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 want to send entire strings, and those strings include characters outside the ASCII range, you'll need to set the port's character encoding first, as shown in this answer, which also shows an alternative solution based on obtaining a byte-array representation of a string based on the desired encoding (which then allows you to use the same method overload as above).
like image 170
mklement0 Avatar answered Nov 25 '22 07:11

mklement0