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,one22 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 0F36 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, 形如: 0E74 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 }