日期:2014-05-17  浏览次数:20422 次

出口通讯实时曲线
我最近做串口实时曲线的一个实验平台,可是曲线总出不来,也不知道是哪里出了问题,望各位大侠指点,我把代码贴上[code=C#][/code]
AutoResetEvent detailCollectedEvent = new AutoResetEvent(false);//生命一个等待事件,用做线程开关

 private void Form1_Load(object sender, EventArgs e)
  {
  cbcomlist.DataSource = GetComList();//获取可用的com口
  mythread = new Thread(new ThreadStart(drawing));//新线程
  mythread.Start();//线程开始
  //mythread.Suspend();
   
  }
 private void button1_Click(object sender, EventArgs e)
  {
  try
  {
  com.DataReceived += com_DataReceived;//注册datareceive事件
  com.PortName = cbcomlist.Text.Trim();//串口号
  com.BaudRate = 115200;//波特率
  com.DataBits = 8;//数据位
  com.StopBits = StopBits.One;//停止位
  com.Parity = Parity.None;//校验位
  com.ReadBufferSize = 100;//设置输入缓存区大小
  com.ReadTimeout=1000;//设置读取操作未完成时发生超时之前的毫秒

  com.Open();//打开串口
  }
  catch (Exception e1)
  {
  MessageBox.Show("串口" + cbcomlist.Text + "问题:" + e1.Message);
   
  }
string[] GetComList()
  {
  RegistryKey subkey = Registry.LocalMachine.OpenSubKey("HARDWARE").OpenSubKey("DEVICEMAP").OpenSubKey("SERIALCOMM");
  string[] strnames = subkey.GetValueNames();
  string[] strkeys = new string[strnames.Length];
  for (int i = 0; i < strnames.Length; i++)
  strkeys[i] = subkey.GetValue(strnames[i], "COMM-1").ToString();
  subkey.Close();
  return strkeys;
  }
void com_DataReceived(object sender, SerialDataReceivedEventArgs e)
  {
  int n = com.BytesToRead;//一次达到的数据量
   
  byte[] buf = new byte[n];//定义数组接收
  com.Read(buf, 0, n);//读串口
  // int k = my_date.Count;
  lock (my_date)
  {
  for (int i = 0; i < n; i++)
  {
  //my_date[k+i]= buf[i];

  my_date.Add(buf[i]);//将读到的数据存入链表中保存
  }
  }
  builder.Clear();//字符串构建先清空
  foreach (byte b in buf) //依次的拼接出16进制字符串  
  {
  builder.Append(b.ToString("X").PadLeft(2,'0') + " ");
  }
  string str = builder.ToString();

  detailCollectedEvent.Set();//触发画图线程
  }
protected void drawing()
  {
  detailCollectedEvent.WaitOne();
  lock (my_date)
  {
  if (my_date[0] == 0xff && my_date[1] == 0xff)
  {
  short k1 = (short)my_date[0];
  short k2 = (short)my_date[1];

  short data1_2 = (short)my_date[2];
  short data1_1 = (short)my_date[3];
  data1_1 <<= 8;

  data_x = (short)(data1_1 + data1_2);

  short data2_2 = (short)my_da