日期:2014-05-20  浏览次数:20952 次

我用C#写了个上位机,经测试串口是有用的,但是连到短信猫上就不行了,短信猫一直没回信,但是短信猫用 超级终端测试完全正确
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace Uart
{
  public partial class Uart : Form
  {
  public Uart()
  {
  InitializeComponent();
  }
  //声明串口
  public SerialPort sp = new SerialPort();
  //定义委托
  delegate void HandleInterfaceUpdateDelegate(string text);
  //实例化委托
  HandleInterfaceUpdateDelegate interfaceUpdateHandle = null;
  //开始初始化
  private void Uart_Load(object sender, EventArgs e)
  {
  this.label_Uart_Info.Text = "";
  //初始化tabcontrol
  this.tabControl1.SelectedIndex = 1;
  //initialize combobox_enter
  this.cbxTransfer.SelectedIndex = 0;
  interfaceUpdateHandle = new HandleInterfaceUpdateDelegate(Updata_Text_Rec);
  }
  private void Updata_Text_Rec(string text)
  {
  richTextBox_Rec.Text += text;
  }
  public int sendCount = 0;
  public int recCount = 0;
  //打开串口
  private void btn_Link_Uart_Click(object sender, EventArgs e)
  {
  sp.PortName = "COM3";
  sp.BaudRate = 9600;
  sp.DataBits = 8;
  sp.Parity = Parity.None;
  sp.StopBits = StopBits.One;
  sp.ReceivedBytesThreshold = 1;
  sp.Encoding = Encoding.GetEncoding("utf-8");
  try
  {
  sp.Open();
  }
  catch (System.IO.IOException ex)
  {
  MessageBox.Show(ex.ToString());
  }
  sp.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.sp_DataReceive);
  label_Uart_Info.Text = sp.PortName + ',' + sp.BaudRate + ',' + sp.DataBits + ',' + sp.Parity + ',' + sp.StopBits;
  if (sp.IsOpen == true)
  {
  MessageBox.Show("串口连接成功");
  }
  else
  {
  MessageBox.Show("串口连接失败");
  }
  }
  //关闭串口
  private void btn_Break_Uart_Click(object sender, EventArgs e)
  {
  sp.Close();
  richTextBox_Rec.Text = "";
  richTextBox_Send.Text = "";
  label_Uart_Info.Text = "未连接";
  if (sp.IsOpen == false)
  {
  MessageBox.Show("串口正常关闭");
  this.lbSendCount.Text = "发送计数";
  this.lbRecCount.Text = "接收计数";
  }
  else
  {
  MessageBox.Show("串口未能关闭");
  }
  }
  //DataReceived事件委托方法
  private void sp_DataReceive(object sender, EventArgs e)
  {
  byte[] databuf = new byte[sp.BytesToRead];
  sp.Read(databuf, 0, sp.BytesToRead);
  this.recCount += databuf.Length;
  //this.lbRecCount.Text = string.Format("接收到{0:X}Byte", this.recCount);