powershell 串口相关

 

 1 # 使用 powershell 测试串口数据
 2 
 3 # 列出有对外使用价值的函数
 4 function showFunctions()
 5 {
 6     'function list:'
 7     '    listPortNames()'
 8     '    getPort($portSetting)'
 9     '    closePort($port)'
10     '    sendReceiveAndDisplayBytes($port, $hexString)'
11     '----'
12 }
13 
14 # 列出串口列表
15 function listPortNames()
16 {
17     return [System.IO.Ports.SerialPort]::getPortNames();
18 }
19 
20 # 获取 SerialPort 对象
21 # portSetting : COM3,9600,none,8,one
22 function getPort($portSetting)
23 {
24     return new-object System.IO.Ports.SerialPort $portSetting;
25 }
26 
27 # 关闭串口
28 function closePort($port)
29 {
30     $port.close();
31     return 'done';
32 }
33 
34 # 发送接收和显示字节
35 # hexString 16进制表示的字节值字符串,以空格分割数据, 例: 01 02 0F
36 function sendReceiveAndDisplayBytes($port, $hexString)
37 {
38     write-host -noNewline 'send : ';
39     write-host $hexString; # 显示参数
40     if ($hexString -eq $null) {
41         write-host 'input is null, stopped!';
42         return;
43     }
44     $bytes4send = convertToByteArray $hexString;
45     $port.write($bytes4send, 0, $bytes4send.length);
46 
47     $recvBuffer = new-object byte[] 128;
48     start-sleep -MilliSeconds 100;
49     $recvLen    = $port.read($recvBuffer, 0, 128);
50     
51     displayBytesAsHex $recvBuffer 0 $recvLen;
52 }
53 
54 # 将16进制字符串转换成字节数组
55 function convertToByteArray($hexString)
56 {
57     $seperator = new-object String[] 1;
58     $seperator[0] = ' ';
59     $hexArray = $hexString.Split($seperator, [System.StringSplitOptions]::RemoveEmptyEntries);
60 
61     $result = new-object byte[] $hexArray.length;
62     for ($i = 0; $i -lt $result.length; $i++) {
63         $result[$i] = [System.Convert]::ToByte($hexArray[$i], 16);
64     }
65     return $result;
66 }
67 
68 # bytes  要显示的字节数组, 
69 # offset 从第一个字节起的偏移量,
70 # count  在字节数组中读取的长度,
71 #     byte to hex string : 
72 #         a) [System.Convert]::toString($bytes[$i], 16);
73 #         b) aByte.toString("X2")  // 小于16会加一个0, 形如: 0E
74 function displayBytesAsHex($bytes, $offset, $count)
75 {
76     $result = 'receive : ';
77     for ($i = $offset; $i -lt ($offset + $count); $i++) {
78         $result += ' ' + $bytes[$i].toString("X2");
79     }
80     return $result;
81 }

 

转载于:https://www.cnblogs.com/shadow-abyss/p/11009752.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值