自己用来测试串口的一些函数
---------
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 ---------