您的位置:首页 > Web前端

LED显示屏串口通信

2011-05-27 09:38 176 查看
LED显示屏是RS485串口,根据LED显示屏通信协议,数据格式为0x00 0x00 0xFF之类的。

1.连接串口

SerialPort serialPort1=new SerialPort();

public bool OpenPort(string port,string baudrate,string parity,string databits,string stopbits)

{

       bool a=false;

       try

      {

              if(serialPort1.IsOpen){

                     serialPort1.Close();

              }else{

                    serialPort1.PortName = port;
                    serialPort1.BaudRate = Convert.ToInt32(baudrate);
                    serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), parity);
                    serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopbits );
                    serialPort1.DataBits = Int32.Parse(databits );
                    serialPort1.Encoding = Encoding.GetEncoding("GB2312");
                    serialPort1.Open();

                    a=true;

              } 

              return a;            

      }catch(Exception){

            throw;

      }

}

 

2.发送数据(可根据协议发送ASCII码,也可发送中文字符串)

//向LED发送中文字符串

public bool ASCiiToStr(string str)

{

byte[] by=new byte[str.Length*2];

by=System.Text.Encoding.Default.GetBytes(str);

SerialPort1.Write(by,0,by.Length);

return true;

}

 

//发送ASCII获得LED显示(ASCII协议里简化发送"AA 01 BB 51 54 72 01 00 00 02 63 41 42 BB B6 D3 AD B9 E2 C1 D9 31 32 FF")

        public bool SendStrGetShow(string ASCstr){
            string a = ASCstr.Replace(" ", "").ToUpper();
            byte[] Wbuffer = Str16ToArrayList(a);
            serialPort1.Write(Wbuffer, 0, Wbuffer.Length);
            return true;
        }

        private byte[] Str16ToArrayList(string str)
        {
            byte[] buffer = new byte[str.Length / 2];
            for (int i = 0; i < str.Length; i += 2)
            {
                buffer[i / 2] = Convert.ToByte(str.Substring(i, 2), 16);
            }
            return buffer;
        }

 

3.关闭串口

public bool ClosePort()

{

         serialPort1.Close();

         return true;

}

 

WinForm里可选调用SendStrGetShow或ASCiiToStr与LED通信写数据

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息