Powershell 向串口写入值

Spe*_*rum 5 powershell

如何将值 255 写入 Powershell 中的串行端口?

$port= new-Object System.IO.Ports.SerialPort COM6,4800,None,8,one
$port.open()
$port.Write([char]255)
$port.Close()
Run Code Online (Sandbox Code Playgroud)

上一个脚本的输出是 63(用串口监视器查看)。

但是$port.Write([char]127)结果是 127。如果该值高于 127,则输出始终为 63。

在此先感谢您的帮助 !

mkl*_*nt0 4

\n

尽管您尝试使用[char]您的参数仍被视为[string],因为 PowerShell 选择该方法的以下重载Write(假设您仅传递一个参数):

\n
void Write(string text)\n
Run Code Online (Sandbox Code Playgroud)\n

此特定重载的文档指出(添加了重点):

\n
\n

默认情况下,\xc2\xa0SerialPort\xc2\xa0 使用\xc2\xa0ASCIIEncoding\xc2\xa0 对字符进行编码。\xc2\xa0 ASCIIEncoding\xc2\xa0 将所有大于 127 的字符编码为 (char)63 或 \'?\'。要支持该范围内的其他字符,请将\xc2\xa0Encoding\xc2\xa0设置为\xc2\xa0UTF8Encoding、\xc2\xa0UTF32Encoding或\xc2\xa0UnicodeEncoding。

\n
\n
\n

要发送字节值,必须使用以下重载:

\n
void Write(byte[] buffer, int offset, int count)\n
Run Code Online (Sandbox Code Playgroud)\n

这需要你:

\n
    \n
  • 使用cast[byte[]]来转换你的字节值
  • \n
  • 并指定offset- 起始字节位置以及count从起始字节位置复制的字节数。
  • \n
\n

在你的情况下:

\n
$port.Write([byte[]] (255), 0, 1)\n
Run Code Online (Sandbox Code Playgroud)\n

注意:单个值不需要(...)around ,但需要指定多个, -分隔的值。255,

\n
\n

笔记:

\n
    \n
  • 如果您想发送整个字符串,并且这些字符串包含ASCII 范围之外的字符,则需要首先设置端口的字符编码,如本答案所示,该答案还显示了基于获取基于所需编码的字符串的字节数组表示形式(然后允许您使用与上面相同的方法重载)。
  • \n
\n