需求:儀器上只有一個物理串口接口,但是儀器中有兩個軟件需要同時讀取該串口的輸入數據。最簡單的方法是在硬件上實現串口的分路,但是老板想要保持硬件不變,在軟件上解決這個問題。物理串口類型是RS232.
查了一些資料,總結下有兩種方案:
1、寫一個程序,將讀到的物理串口數據不斷寫到一個外部文件中。當那兩個軟件需要運行時,從外部文件中讀取數據;
2、利用虛擬串口:寫一個程序,將讀到的物理串口數據不斷寫到兩個虛擬串口中。當那兩個軟件需要運行時,從兩個虛擬串口中讀取數據;
經過對比,選擇方法二,因為我覺得方法二使用起來更方便,可以直接設置那兩個軟件的讀取數據com口即可。具體的實現方式如下:
Step 1. 新建虛擬串口
什么是虛擬串口?
虛擬串口是相對于物理串口而言的,不需要物理上的串口就可以存在;
如何創建虛擬串口?
使用軟件Configure Virtual Serial Port Driver,界面如下:

該軟件使用非常簡單,在Manage ports中選擇com口,點擊Add pair。在創建虛擬串口時,是成對創建的,該對串口默認相互連接。創建虛擬串口后,在設備管理器中可以看到:

其中com10是物理端口,com1/com2/com3/com4都是虛擬串口。
Step 2. 用labview讀取com10接收到的數據,并寫給com1和com3
什么是Labview?
Labview是NI公司出的一款編程軟件,我覺得它有兩個優點,一是容易實現PC與外部硬件的交互;二是圖形化編程,適用于編寫一些簡單的程序。
如何用Labview將物理串口數據分發給虛擬串口?
程序流程如下:
1、配置com10、com1、com3口;
2、讀取com10接收到的數據;
3、將com10接收到的數據發送給com1和com3;
4、循環執行步驟2和3;
5、關閉三個端口;
程序如下:
該程序的作用是,使得能夠在com2和com4上同時讀取到com10接收的數據。接收方式如下。
Step 3. 驗證是否成功進行串口分配
用arduino mega發送串口數據到com10
我們選擇外圍電路mega給PC進行串口數據的發送。arduino程序如下:
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// prints title with ending line break
Serial.println("ASCII Table ~ Character Map");
}
// first visible ASCIIcharacter '!' is number 33:
int thisByte = 33;
// you can also write ASCII characters in single quotes.
// for example. '!' is the same as 33, so you could also use this:
//int thisByte = '!';
void loop() {
// prints value unaltered, i.e. the raw binary version of the
// byte. The serial monitor interprets all bytes as
// ASCII, so 33, the first number, will show up as '!'
Serial.write(thisByte);
Serial.print(", dec: ");
// prints value as string as an ASCII-encoded decimal (base 10).
// Decimal is the default format for Serial.print() and Serial.println(),
// so no modifier is needed:
Serial.print(thisByte);
// But you can declare the modifier for decimal if you want to.
//this also works if you uncomment it:
// Serial.print(thisByte, DEC);
Serial.print(", hex: ");
// prints value as string in hexadecimal (base 16):
Serial.print(thisByte, HEX);
Serial.print(", oct: ");
// prints value as string in octal (base 8);
Serial.print(thisByte, OCT);
Serial.print(", bin: ");
// prints value as string in binary (base 2)
// also prints ending line break:
Serial.println(thisByte, BIN);
// if printed last visible character '~' or 126, stop:
if(thisByte == 126) { // you could also use if (thisByte == '~') {
// This loop loops forever and does nothing
//while(true) {
// continue;
// }
thisByte = 32;
delay(3000);
}
// go on to the next character
thisByte++;
}
該程序可以使mega不斷地給PC發送數據。
用PuTTY讀取com2和com4
第一次用PuTTY,真的很強大,功能很多。讀串口數據是功能之一。界面如下

只要在Serial中選擇com口之后點擊Open即可讀取該端口數據。我們同時監視com2和com4,結果如下:
通過驗證,發現用該方法可以實現物理串口到虛擬串口一對多分發。