首页 > 解决方案 > Perl 串口访问 [Windows 10]

问题描述

我在Windows 10中使用Neo-6M GPS 模块 数据表做了一些小项目来跟踪GPS卫星。

下面的代码片段演示了communication core该程序的功能。

我发现有时在程序启动时它不与GPS 模块通信,我必须通过按几次Ctrl+C来中断它,才能重新启动它并建立程序和GPS模块之间的通信。

有时在程序从GPS模块读取数据之前可能需要几次尝试。

GPS模块通过USB转串口模块cp2102连接电脑,cp2102 datasheet

GPS模块和驱动程序正常工作——通过u-center软件确认。

有人可以通过程序和GPS模块之间的交互发现所描述问题的原因吗?

use strict;
use warnings;
use feature 'say';

use Time::HiRes qw(usleep);

use Win32::SerialPort; 
use Win32::Process;
use Win32::Console::ANSI qw/Cls Title Cursor/;
use Term::ANSIScreen qw/:color :cursor :screen/;
use sigtrap 'handler' => \&sig_handler, qw(INT TERM KILL QUIT);

use Data::Dumper;

my $debug = 1;

my $port_name   = 'COM4';
my $baudrate    = 9600;
my $databits    = 8;
my $parity      = 'none';
my $stopbits    = 1;

my $portObj = new Win32::SerialPort($port_name)
     || die "Can't open $port_name: $^E\n";    # $quiet is optional

$portObj->baudrate($baudrate);
$portObj->databits($databits);
$portObj->parity($parity);
$portObj->stopbits($stopbits);

sub sig_handler {
    Cls();
    cursor_mode('on');
    $portObj->lookclear();
    $portObj->close();
    exit 0;
}

cursor_mode('off');

while(1) {
    my $line = $portObj->lookfor();
    if( $line ) {
        {
            local $/ = "\r";
            chomp $line;
        }
        say "[$line]" if $debug;
        # Some data processing takes place
    } else {
        usleep(50);     # Allocate time for other processes to run
    }
}

# Data processing subroutines
# Positioned output to terminal window

sub cursor_mode {
    my $mode = shift;
    
    print "\e[?25l" if $mode eq 'off';
    print "\e[?25h" if $mode eq 'on';       
}

标签: windowsperlserial-portgps

解决方案


您必须登录 GPS 模块主机并重新启动 GPS 模块守护程序(或以其他方式终止陈旧的连接)。在程序上做一个ctrl-c是不够的。有时您可以重新建立连接,因为之前的连接超时。


推荐阅读