zoukankan      html  css  js  c++  java
  • C# SerialPort 读写三菱FX系列PLC

    1:串口初始化 

    com = new SerialPort("COM3", 9600, Parity.Even, 7, StopBits.One);

    2:打开关闭串口

    if (com.IsOpen)

     {com.Close();}

    com.Open();

    if (com.IsOpen)

    { com.Close();}

    3:C# ASCII转字符及字符转ASCII

    public static string Chr(int asciiCode)
            {
                if (asciiCode >= 0 && asciiCode <= 255)
                {
                    System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                    byte[] byteArray = new byte[] { (byte)asciiCode };
                    string strCharacter = asciiEncoding.GetString(byteArray);
                    return (strCharacter);
                }
                else
                {
                    throw new Exception("ASCII Code is not valid.");
                }

            }

    public static int Asc(string character)
            {
                if (character.Length == 1)
                {
                    System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                    int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];
                    return (intAsciiCode);
                }
                else
                {
                    throw new Exception("Character is not valid.");
                }

            }

    4:写入串口的命令字符串的和校验

    /// <summary>
            /// 和校验
            /// </summary>
            /// <param name="data"></param>
            /// <returns></returns>
            public string SumCheck(string data)
            {
                int sum = 0;
                for (int i = 0; i < data.Length; i++)
                {
                    sum += Asc(data.Substring(i, 1));
                }

                string res = sum.ToString("X");
                res = res.Substring(res.Length - 2, 2);

                return res;

            }

     5:写入PLC

    private void btnWrite_Click(object sender, EventArgs e)

            {

                string[] write = new string[] { "2","2"}; //将准备写入PLC的值
                //将要写入的值转换成16进制数,补齐两个字节,注意高低字节需要交换
                string sWriteData = "";
                for (int i = 0; i < write.Length; i++)
                {
                    int val = Convert.ToInt32(write[i].Length>0?write[i]:"0");
                    string s = val.ToString("X");
                    while (s.Length<4)
                    {
                        s = "0" + s;
                    }
                    sWriteData += s.Substring(2,2)+s.Substring(0,2);
                }

                MessageBox.Show(sWriteData);
                //写入命令,1表示写入,1194表示D202这个地址的16进制,04表示D202,D203为4个BYTE,1194=(202*2)+4096的16进制数,至于用它表示D202的起始位置,三菱故意要这么麻烦了.
                sWriteData = "1119404" + sWriteData + Chr(3);
                //chr(2)和chr(3)是构成命令的标志字符,然后加上校验和,命令组织完成
                sWriteData = Chr(2) + sWriteData + SumCheck(sWriteData);

                MessageBox.Show(sWriteData);
                //写入串口
                com.Write(sWriteData);
                //byte[] data = Encoding.ASCII.GetBytes(sWriteData);
                //com.Write(data,0,data.Length);

            }

    6:读PLC

     private void btnRead_Click(object sender, EventArgs e)
            {
               
                this.txtRead0.Clear();
                string sReadData = "";

                //在读PLC中的数据之前,需要先发个指令给它,让它将数据发送到串口,下面的字符串中,chr(2),chr(3)为PLC命令的格式标志,0119404中,0表示读,1194表示D202的起始地址,04表示读D202,D203两个字,共4个字节,66为0119404和chr(3)的校验和,向串口写入"读"命令,其实和向plc地址中写入数据是一样的,只是没有数据,用0表示读

                string sReadCmd = Chr(2) + "0119404" + Chr(3) + "66";
                com.Write(sReadCmd);
                //等待1秒钟
                System.Threading.Thread.Sleep(1000);
                // 从串口读数据
                byte[] data = new byte[1024];
                com.Read(data, 0, 1024);

               //如果首位为2,则表示数据有效.这里有个问题,在第二次读,第2位才为'2',第三次又是首位为2,需要再测试
                if (data[0]==2)
                {
                    string sReceiveData = System.Text.Encoding.ASCII.GetString(data);
                    //MessageBox.Show(sReceiveData);
                   //解析命令,将读到的字符解析成数字,注意高低位的转换
                    for (int i = 1; i < 8; i += 4)
                    {
                        string sLow = sReceiveData.Substring(i,2);
                        string sHigh = sReceiveData.Substring(i + 2, 2);
                        //int res = Convert.ToInt32(sHigh)+ Convert.ToInt32(sLow);
                        int res = Convert.ToInt32(sHigh,16) + Convert.ToInt32(sLow,16);

                        this.txtRead0.Text += res.ToString() + ",";
                    }              
                    
                }



  • 相关阅读:
    JS获取浏览器信息及屏幕分辨率
    div + css 让img标签图片在div中等比缩放显示
    java 对于表情和特殊字符的转码解码处理
    VS Code 快捷键设置
    jq 对象获取总结大全
    java Date时间格式工具类DateUtil
    Linux云服务器下Tomcat部署超详细
    文件操作模式
    文件处理
    字符编码
  • 原文地址:https://www.cnblogs.com/baishahe/p/1364244.html
Copyright © 2011-2022 走看看