日期:2014-05-18 浏览次数:20839 次
SerialPort SPCom = new SerialPort("COM1",9600); SPCom.Open(); private void SPCom_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { //定义变量 byte[] BufferBytes,ReceivedBuff; int Count; Count = SPCom.BytesToRead; //得到数据 BufferBytes = new Byte[Count]; SPCom.Read(BufferBytes, 0, Count); for (int i = 0; i < Count; i++) { ReceivedBuff[i]= BufferBytes[i]; } }
------解决方案--------------------
1using System;
2using System.IO.Ports;
3using System.Collections;
4using System.Collections.Generic;
5using System.Windows.Forms;
6using System.Runtime.InteropServices;
7
8namespace Lordeo.AssetMan.PPC.App
9{
10 public class GpsMonitor
11 {
12 private SerialPort m_serialPort;
13
14 private System.Windows.Forms.Timer m_timer;
15 private const int defaultTimerInterval = 800; //越快越容易出错
16 //读取到事件
17 public event EventHandler OnDataRecieved;
18 //临时存储读取的信息
19 private string m_dataReaded = string.Empty;
20
21 /**//// <summary>
22 /// 构造
23 /// </summary>
24 public GpsMonitor()
25 {
26 //timer
27 m_timer = new System.Windows.Forms.Timer();
28 m_timer.Interval = defaultTimerInterval;
29 m_timer.Tick += new EventHandler(Timer_Tick);
30
31 //设置端口的默认值
32 m_serialPort = new SerialPort();
33 m_serialPort.ReadBufferSize = 2048;
34 m_serialPort.BaudRate = 4800; //P800默认的速率,过高的速率容易产生误码
35 m_serialPort.DataBits = 8;
36 m_serialPort.Parity = Parity.None;
37 m_serialPort.StopBits = StopBits.One;
38 m_serialPort.ReadTimeout = 2000;//超时
39 m_serialPort.PortName = "COM4"; //多数GPS都用COM4
40
41 m_serialPort.ErrorReceived += new SerialErrorReceivedEventHandler(SerialPort_ErrorReceived);
42 }
43
44 private void SerialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
45 {
46 this.Message = e.ToString();
47 }
48
49 timer#region timer
50 /**//// <summary>
51 /// 计时器工作
52 /// </summary>
53 /// <param name="sender"> </param>
54 /// <param name="e"> </param>
55 private void Timer_Tick(object sender, EventArgs e)
56 {
57 try
58 {
59 if (!string.IsNullOrEmpty(m_serialPort.ReadLine()))
60 {