Bootstrap

C# Winform--SerialPort串口通讯(ASCII码发送)

1.代码部分

        private SerialPort serialPort = new SerialPort();
        private void button1_Click(object sender, EventArgs e)
        {
            serialPort.BaudRate = 9600;
            serialPort.Parity = Parity.None;
            serialPort.StopBits = StopBits.One;
            serialPort.DataBits = 8;
            serialPort.PortName = "COM3";
            serialPort.DataReceived += SerialPort_DataReceived;
            serialPort.Open();
        }
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(100);
            byte[] bs = new byte[serialPort.ReadBufferSize];
            serialPort.Read(bs, 0, serialPort.ReadBufferSize);
            string ss = Encoding.ASCII.GetString(bs);
            string[] parts = ss.Split(new char[] { '\0' },                     
            StringSplitOptions.RemoveEmptyEntries);
             if (parts.Length > 0)
            {
                string result = parts[0];//"BUSY\r\nEND\r\n"
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            List<byte> buffer = new List<byte>();
            buffer.AddRange(Encoding.ASCII.GetBytes("1111"));
            //buffer.AddRange(Encoding.ASCII.GetBytes("2222"));

            buffer.Add(0x0D);
            serialPort.Write(buffer.ToArray(), 0, buffer.Count);
        }
        private void button3_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(textBox1.Text.ToString().Trim()))
            {
                return;
            }
            List<byte> buffer = new List<byte>();
            var shi = textBox1.Text.ToString().Trim();
            buffer.AddRange(Encoding.ASCII.GetBytes(textBox1.Text.ToString().Trim()));
            //buffer.AddRange(Encoding.ASCII.GetBytes("1111"));
            buffer.Add(0x0D);
            serialPort.Write(buffer.ToArray(), 0, buffer.Count);
        }

2.小结:

最近在测试部分硬件底层通信,写了一个自用的串口Demo记录一下

;