日期:2014-05-18  浏览次数:21091 次

关于SerialPort写串口程序的问题
有两个问题,哥哥姐姐帮帮忙呀,,
SerialPort对象设置如下:
  this.PortName = "COM4";
  this.BaudRate = 9600;
  this.Parity = Parity.None;
  this.DataBits = 8;
  this.ReceivedBytesThreshold = 3;
  this.Handshake = Handshake.RequestToSend;
  this.StopBits = StopBits.One;
  this.Parity = Parity.None;
  this.ReadTimeout = 500;
  this.WriteTimeout = 500;
  this.RtsEnable = true;
  this.NewLine = "\r\n";
  this.Open();

连接CDMA modem设备..
AT+CMGF=1//设置文本格式短信成功
AT+WSCL=6,4//字符编码
执行过这两条AT指令

问题:
 1,接收数据不完整,
  this.Write(ATCmd + "\r");
  Thread.Sleep(500);
  byte[] buffer;
  if (this.BytesToRead > 0)
  {
  buffer = new byte[this.BytesToRead];
  this.Read(buffer, 0, buffer.Length);
  }
  else
  {
  return "";
  }

  return System.Text.Encoding.ASCII.GetString(buffer);
这是执行AT指令的方法,这样取出数据 ,有时会出现,读出的不完整,比如:结果...\r\nOK,而取出来却是:结果...\r\nO
漏了K,而在执行第二条指令的时候,这个K就出现在返回结果的第一个字符...将Thread.Sleep(500);改成1000,2000都试过,问题同样存在,只是机率小了...

2,读取字符短信内容,中文短信出现乱码,,

用了上面代码执行指令 "AT+CMGR=2"

比如得到的结果是:
+CMGR:"REC READ","13754685551","10/06/03,14 :37 :42",0,2,0,"13754685551",2
这里是短信内容(乱码)
OK

而我知道,发送时用的是BigEndianUnicode字符编码,而取出是用ASCII编码,,,取出用BigEndianUnicode编码时,状态,手机号等会变成乱码,内容则不出现乱码,,而这里短信的其它信息和内容是一起返回的,,所以比较郁闷 ,,,该怎么处理??

欢迎讨论````

------解决方案--------------------
数据没有接收完造成的读取数据不完整
------解决方案--------------------
http://libinguest.blog.163.com/blog/static/4534208200811252208704/
------解决方案--------------------
楼上的真快。
------解决方案--------------------
你好,我之前写过和串口打印机通信的程序,未出现你所说的情况。看了你写的代码和问题后,我有一些想法
1.你的波特率是设置成了 9600.你检查下是否和你设备的波特率配对,如果不配对会出现丢失问题。
2.我看了下,你是使用Thread.Sleep(500).然后来检查接受到的数据。换成
C# code

port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
  string value = port.ReadExisting(); // 你接受到的值
  //...
}

------解决方案--------------------
UP 接分
------解决方案--------------------
不懂!帮顶!~~
------解决方案--------------------
up        up      up            
 upupupup     upupupup   upupupup  upupupupup     
   upup       upup     upup up    upup    
   upup       upup     upupup      upup   
   upup       upup     upup        up   
   upup       upup     upup        upup  
   upup       upup     upup        upup  
   upup       upup     upup        upup  
   upup       upup     upup        upup  
   upup       upup     upup        upup  
   upup       upup     upup        upup  
   upup       upup     upup       upup   
   upup      upupup     upupup      upup   
    upup    up upupupup   upupupup    upup    
     upupupupup  up      upup  upupupup      
                   upup