zoukankan      html  css  js  c++  java
  • 【实验室笔记】C#上位机学习笔记

    用C#编写上位机,基本流程是【1】串口配置,【2】串口发送数据,【3】串口接收数据。

    【1】串口配置

      串口的属性配置包括:

      No.1串口端口号

      No.2串口波特率

      No.3串口数据位

      No.4串口停止位

      N0.5串口校验位

    串口的上述属性,分别将值存储进combobox里边,然后带用户根据实际情况自己进行选择,设置也比较简单。

    串口的打开和关闭,采用try-catch这对组合,可以自动打开和关闭处理过程中出现的问题。

    【2】串口发送数据

    串口发送数据,采用串口的write属性,该属性有三种重载方式,string,byte,char三种,分别是字符串,字节,字符三种。

     1             if (serialPort1.IsOpen == true)
     2             {
     3                 try
     4                 {
     5                     Byte[] mes = new Byte[3] { 1,2,3};
     6                     char[] chr = new char[3] { 'a','b','c'};
     7                     serialPort1.Write(mes,0,1);
     8                     serialPort1.Write(chr,0,1);
     9                     serialPort1.Write("Hello");
    10                     MessageBox.Show("发送成功");
    11                 }
    12                 catch
    13                 {
    14                     MessageBox.Show("发送失败");
    15                 }
    16             }

    Write的Byte和char函数接口解释为,首先告诉write用的哪一个数组,从数组第几个位开始发数据,发几个数据。
    如此,下位机,讲分别收到1,a,Hello数据。

    【3】串口接收数据

    1 Control.CheckForIllegalCrossThreadCalls = false;
    2 serialPort1.DataReceived += new SerialDataReceivedEventHandler(SP1REV);
    3 serialPort1.ReceivedBytesThreshold = 1;
     1         void SP1REV(object sender, SerialDataReceivedEventArgs e)
     2         {
     3             if (serialPort1.IsOpen == true)
     4             {
     5                 try
     6                 { 
     7                     Byte[] REV = new Byte[serialPort1.BytesToRead];
     8                     serialPort1.Read(REV, 0, REV.Length);
     9                     serialPort1.DiscardInBuffer();
    10                     textBox1.Text += Encoding.ASCII.GetString(REV);
    11                 }
    12                 catch
    13                 {
    14                     MessageBox.Show("接收出错");
    15                 }
    16             }
    17         }
  • 相关阅读:
    大规模扩展casbin的一种方案
    casbin 性能优化的几点建议
    使用casbin进行应用访问控制
    使用xid 生成 唯一id
    jcsabin FilteredAdapter 逻辑处理问题
    jcasbin redis watcher 一些修改
    cube.js 0.27.31 一些新特性
    sdkman Stop! maven is not a valid candidate 类似问题解决
    lakefs 类似git 的文件对象存储
    readme.so docker 镜像
  • 原文地址:https://www.cnblogs.com/achao123456/p/5885714.html
Copyright © 2011-2022 走看看