.NET的SerialPort串口的使用

private SerialPort sp = new SerialPort();//一个串口,接受测试值

private void timer1_Tick(object sender, EventArgs e)
{
    try
    {
        sp.DiscardInBuffer();//丢弃来自串行驱动程序的接收缓冲区的数据。
        sp.DiscardOutBuffer();//丢弃来自串行驱动程序的传输缓冲区的数据。
        if(combo_device.SelectedIndex == 0)
        {
            ReadTestRange();
            ReadSetVoltage();
            ReadValueAndResult();
        }
        if(combo_device.SelectedIndex == 1)
        {
            ReadChromaSetting();
            ReadChromaResult();
        }
                
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

#region 数据转换
public static byte[] HexStringToBytes(string hs)
{
    string[] strArr = hs.Trim().Split(' ');
    byte[] b = new byte[strArr.Length];
    //逐个字符变为16进制字节数据
    for (int i = 0; i < strArr.Length; i++)
    {
        b[i] = Convert.ToByte(strArr[i], 16);
    }
    
    return b;
}

//按照指定编码将字节数组变为字符串
public string byteToHexStr(byte[] bytes)
{
    string str = "";
    if (bytes != null)
    {
        for (int i = bytes.Length - 1; i >= 0; i--)
        {
            if (i == bytes.Length - 1)
            {
                str += bytes[i].ToString("X").PadLeft(2, '0');//左填充
            }
            else
            {
                str += " " + bytes[i].ToString("X").PadLeft(2, '0');
            }

        }
    }
    return str;
}

//十六进制转十进制,需要两个程序块Hex2Ten(string hex)及HexChar2Value(string hexChar)
public static int HexToTen(string hex)
{
    int ten = 0;
    for (int i = 0, j = hex.Length - 1; i < hex.Length; i++)
    {
        ten += HexCharToValue(hex.Substring(i, 1)) * ((int)Math.Pow(16, j));
        j--;
    }
    return ten;
}
public static int HexCharToValue(string hexChar)
{
    switch (hexChar)
    {
        case "0":
        case "1":
        case "2":
        case "3":
        case "4":
        case "5":
        case "6":
        case "7":
        case "8":
        case "9":
            return Convert.ToInt32(hexChar);
        case "a":
        case "A":
            return 10;
        case "b":
        case "B":
            return 11;
        case "c":
        case "C":
            return 12;
        case "d":
        case "D":
            return 13;
        case "e":
        case "E":
            return 14;
        case "f":
        case "F":
            return 15;
        default:
            return 0;
    }
}
#endregion

 打开串口

//打开串口
private void OpenPort()
{
    try
    {
        sp.PortName = string.IsNullOrEmpty(Properties.Settings.Default.PortName) ? "COM3" : Properties.Settings.Default.PortName;//COM口
        sp.BaudRate = 9600;//串行波特率
        sp.DataBits = 8;//每个字节的标准数据位长度
        sp.Parity = Parity.None;//奇偶校验检查协议
        sp.StopBits = StopBits.One;//每个字节的标准停止位数
        sp.DtrEnable = true;//在串行通信过程中启用数据终端就绪 (DTR) 信号
        sp.RtsEnable = true;//在串行通信中是否启用请求发送 (RTS) 信号
        sp.ReadTimeout = 500;//读超时时间
        sp.WriteTimeout = 500;//写超时时间

        if (!sp.IsOpen)
        {
            sp.Open();
            if (sp.IsOpen)
            {
                lb_connStatus.Text = "已连接";
                lb_connStatus.ForeColor = Color.Green;
                timer1.Interval = Properties.Settings.Default.DelayTime;
                timer1.Enabled = true;
            }
            else
            {
                lb_connStatus.Text = "未连接";
                lb_connStatus.ForeColor = Color.Red;
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
        PubLibrary.WriteErrLog(ex.ToString());
    }
}

关闭串口

//关闭串口
private void ClosePort()
{
    try
    {
        if (sp != null && sp.IsOpen)
        {
            //处理当前在消息队列中的所有Windows消息
            Application.DoEvents(); //避免关闭串口时死锁
            sp.Close();
        }
    }
    catch (Exception ex)
    {
        //MessageBox.Show(ex.ToString());
        MessageBox.Show(ex.Message);
        PubLibrary.WriteErrLog(ex.ToString());
    }
}

给串口写数据

sp.Write(HexStringToBytes("0xAB 0x01 0x70 0x03 0xB1 0x00 0xD7 0x04"), 0, HexStringToBytes("0xAB 0x01 0x70 0x03 0xB1 0x00 0xD7 0x04").Length);

Thread.Sleep(500);

读取16进制返回数据

int size = sp.BytesToRead;

byte[] buffer = new byte[size];
string receive = string.Empty;
if (sp.BytesToRead > 0)
{
    sp.Read(buffer, 0, size);
    receive = byteToHexStr(buffer).Trim();
    //receive = sp.ReadExisting().Trim();
}
else
{
    for (int i = 0; i < 3; i++)
    {
        Thread.Sleep(10);
        if (sp.BytesToRead > 0)
        {
            sp.Read(buffer, 0, size);
            receive = byteToHexStr(buffer).Trim();
            break;
        }
    }
}

写指令

sp.WriteLine(":VOLTage?");
Thread.Sleep(100);

string receive = string.Empty;
if (sp.BytesToRead > 0)
{
    receive = sp.ReadExisting().Trim();
}
else
{
    for (int i = 0; i < 3; i++)
    {
        Thread.Sleep(10);
        if (sp.BytesToRead > 0)
        {
            receive = sp.ReadExisting().Trim();
            break;
        }
    }
}

你可能感兴趣的:(.net,c#,开发语言)