powershell 串口相關


自己用來測試串口的一些函數

---------

 

 1 # 使用 powershell 測試串口數據
 2 
 3 # 列出有對外使用價值的函數
 4 function showFunctions()
 5 {
 6     ('function list:',
 7      '    listPortNames()',
 8      '    getPort($portSetting, $readTimeOut)',
 9      '    closePort($port)',
10      '    sendReceiveAndDisplayBytes($port, $hexString)',
11      '-- done --') | write-host;
12 }
13 
14 # 列出串口列表
15 function listPortNames()
16 {
17     return [System.IO.Ports.SerialPort]::getPortNames();
18 }
19 
20 # 獲取 SerialPort 對象, 例:
21 #     getPort COM3,9600,none,8,one 1000
22 # portSetting : 串口參數, 例: COM3,9600,none,8,one
23 # readTimeOut : 讀數據超時毫秒數, 例: 1000, 在 1 秒內沒有讀到數據就產生異常
24 #     得到的對象需要調用 open 方法, 之后發送數據
25 function getPort($portSetting, $readTimeOut)
26 {
27     $result = new-object System.IO.Ports.SerialPort $portSetting;
28     $result.readTimeOut = $readTimeOut;
29 
30     return $result;
31 }
32 
33 # 關閉串口
34 function closePort($port)
35 {
36     $port.close();  # 打開使用 $port.open()
37     return 'done';
38 }
39 
40 # 發送接收和顯示字節
41 # hexString 16進制表示的字節值字符串,以空格分割數據, 例: 01 02 0F
42 function sendReceiveAndDisplayBytes($port, $hexString)
43 {
44     write-host -noNewline 'send : ';
45     write-host $hexString; # 顯示參數
46     if ($hexString -eq $null) {
47         write-host 'input is null, stopped!';
48         return;
49     }
50 
51     # 發送
52     $bytes4send = convertToByteArray $hexString;
53     $port.write($bytes4send, 0, $bytes4send.length);
54 
55     start-sleep -MilliSeconds 100;
56 
57     # 接收
58     $recvBuffer = new-object byte[] 128;
59     $recvLen    = $port.read($recvBuffer, 0, 128);
60 
61     # 顯示
62     write-host -noNewLine 'receive: ';
63     convertToHex $recvBuffer 0 $recvLen | write-host;
64 
65     return 'done';
66 }
67 
68 # 將16進制字符串轉換成字節數組
69 function convertToByteArray($hexString)
70 {
71     $seperator = new-object String[] 1;
72     $seperator[0] = ' ';
73     $hexArray = $hexString.Split($seperator, [System.StringSplitOptions]::RemoveEmptyEntries);
74 
75     $result = new-object byte[] $hexArray.length;
76     for ($i = 0; $i -lt $result.length; $i++) {
77         $result[$i] = [System.Convert]::ToByte($hexArray[$i], 16);
78     }
79     return $result;
80 }
81 
82 # bytes  要顯示的字節數組, 
83 # offset 從第一個字節起的偏移量,
84 # count  在字節數組中讀取的長度,
85 #     byte to hex string : 
86 #         a) [System.Convert]::toString($bytes[$i], 16);
87 #         b) aByte.toString("X2")  // 小於16會加一個0, 形如: 0E
88 function convertToHex($bytes, $offset, $count)
89 {
90     $result = '';
91     for ($i = $offset; $i -lt ($offset + $count); $i++) {
92         $result += ' ' + $bytes[$i].toString("X2");
93     }
94     return $result;
95 }

 

 

--------- THE END ---------

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM