c# 控制智能停车系统出入口道闸模块开关

技术文摘
0 246
admin
凯特云(xukai) 5 2021/3/31 11:45:37
编辑此贴 收藏

描述:-


        不通厂家的模块协议可能不一样,普遍通用,本次分享的是【康耐德】的模块;如果用到其他模块的朋友通过下面的介绍无法控制,那就要自己另寻他法了。


协议:ModbusTCP


一如既往,首先来张demo截图: 

       a、按钮上的1,2分别代表两个道闸;

       b、接触过开关控制器的都知道,2路组成一个开关,如指令 1,0代表开;0,1代表关,同时发1,0,1,0代表两头都开,反之则都关

开始了,上代码。。。

直接上完整代码,需要可运行exe完整源码或程序的联系我无偿提供:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ModbusTCP;
using System.Collections;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private ModbusTCP.Master MBmaster;
        string StartAddress = "200"; //读取开始地址

        string DOStartAddress = "100"; //写入接口开始地址
        private bool RecvieMode_502 = false;
        string dataSize = "16";//长度
        byte uiSlaveID = 255;// 
        private int Recvie_Count = 0;
        string redIP = "172.16.1.237"; //红外控制器IP


        public Form1()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            redIP = txtIP.Text;
            if (RecvieMode_502)
            {
                return;
            }


            try
            {
                // Create new modbus master and add event functions
                MBmaster = new Master(redIP, 502);
                MBmaster.OnResponseData += new ModbusTCP.Master.ResponseData(MBmaster_OnResponseData);
                MBmaster.OnException += new ModbusTCP.Master.ExceptionData(MBmaster_OnException);
                RecvieMode_502 = true;
                MBmaster.autoConnectOfBreak = false;
                MessageBox.Show("连接成功!!");
            }
            catch (SystemException error)
            {
                MessageBox.Show(error.Message);
            }
        }


        // ------------------------------------------------------------------------
        // Event for response data
        // ------------------------------------------------------------------------
        private void MBmaster_OnResponseData(ushort ID, byte function, byte[] values)
        {
            // ------------------------------------------------------------------
            // Seperate calling threads
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new ModbusTCP.Master.ResponseData(MBmaster_OnResponseData), new object[] { ID, function, values });
                return;
            }

            // Ignore watchdog response data
            if (ID == 0xFF) return;

            // ------------------------------------------------------------------------
            // Identify requested data
            ushort Func = ID;

            ++Recvie_Count;
            if (Recvie_Count > 100000000)
            {
                Recvie_Count = 1;
            }
            bool[] bits = new bool[1];
            if (Func > 0)
            {
                // Convert data to selected data type
                richTextBox1.Clear();

                if (null != values)
                {
                    int i = 1;
                    int dzNo = (i - 1) * 4;
                    BitArray bitArray = new BitArray(values);
                    bool[] bs = new bool[bitArray.Count];
                    bitArray.CopyTo(bs, 0);
                    if (bs.Count(a => a == false) == 15)
                    {
                        return;
                    }

                    bool[] bitsArr = new bool[bitArray.Count];
                    for (int k = 0; k < bitArray.Count - dzNo; k++)
                    {
                        bitsArr[k] = bs[k + dzNo];
                        richTextBox1.AppendText(Convert.ToInt32(bitsArr[k]).ToString());
                    }

                    bits = bitsArr;
                }
                //接收成功
                if (richTextBox1.Visible && !richTextBox1.IsDisposed)
                {
                    richTextBox1.AppendText(string.Format("\r\n红外接收结果:{0} {1} {2} {3}\r\n", bits[0], bits[1], bits[2], bits[3]));
                }

                #region
                //if (null != values)
                //{
                //    BitArray bitArray = new BitArray(values);
                //    bits = new bool[bitArray.Count];
                //    bitArray.CopyTo(bits, 0);
                //    for (int i = 0; i < bits.Length; i++)
                //    {
                //        richTextBox1.AppendText(Convert.ToInt32(bits[i]).ToString());
                //    }
                //}
                #endregion
                //接收成功
                // MessageBox.Show(bits.Length.ToString());
            }



        }



        #region 通讯常提示事件
        // ------------------------------------------------------------------------
        // Modbus TCP slave exception
        // ------------------------------------------------------------------------
        private void MBmaster_OnException(ushort id, byte function, byte exception)
        {
            // ------------------------------------------------------------------
            // Seperate calling threads
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new ModbusTCP.Master.ExceptionData(MBmaster_OnException), new object[] { id, function, exception });
                return;
            }

            string exc = "Modbus says error: ";
            switch (exception)
            {
                case Master.excIllegalFunction: exc += "Illegal function!"; break;
                case Master.excIllegalDataAdr: exc += "Illegal data adress!"; break;
                case Master.excIllegalDataVal: exc += "Illegal data value!"; break;
                case Master.excSlaveDeviceFailure: exc += "Slave device failure!"; break;
                case Master.excAck: exc += "Acknoledge!"; break;
                case Master.excSlaveIsBusy: exc += "Slave is busy!"; break;
                case Master.excGatePathUnavailable: exc += "Gateway path unavailbale!"; break;
                case Master.excExceptionTimeout: exc += "Slave timed out!"; break;


            }

            // LogHelper.WriteLog(this.GetType(), exc);
        }

        #endregion


        #region 读取点
        private void btnReadDisInp_Click(object sender, EventArgs e)
        {

            ushort ID = 2;
            ushort StartAddress = ReadStartAdr();
            ushort Length = Convert.ToUInt16(dataSize);

            MBmaster.ReadDiscreteInputs(ID, StartAddress, Length, uiSlaveID);
        }


        private ushort ReadStartAdr()
        {
            // Convert hex numbers into decimal
            if (StartAddress.IndexOf("0x", 0, StartAddress.Length) == 0)
            {
                string str = StartAddress.Replace("0x", "");
                ushort hex = Convert.ToUInt16(str, 16);
                return hex;
            }
            else
            {
                return Convert.ToUInt16(StartAddress);
            }
        }
        #endregion

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //ushort ID = 6;
            //ushort StartAddress = ReadStartAdr();

            //data = GetData(Convert.ToByte(txtSize.Text));
            //MBmaster.WriteMultipleCoils(ID, StartAddress, Convert.ToByte(txtSize.Text), data, GetSlaveID());	

            ChangDZ(Convert.ToInt32(textBox1.Text), Convert.ToBoolean(Convert.ToInt32(textBox2.Text)), Convert.ToBoolean(Convert.ToInt32(textBox3.Text)));
        }
        /// <summary>
        /// 开关道闸
        /// </summary>
        /// <param name="dzNo"></param>
        /// <param name="b1"></param>
        /// <param name="b2"></param>
        private void ChangDZ(int dzNo, bool b1, bool b2)
        {

            ushort ID = 6;
            int sized = Convert.ToInt32(dataSize);
            ushort StartAddress = Convert.ToUInt16(DOStartAddress);
            byte[] data = new byte[sized];
            bool[] bits = new bool[sized];
            string s = richTextBox1.Text;
            int st = (dzNo - 1) * 2;
            bits[st] = b1;
            bits[st + 1] = b2;
            int dl = bits.Length / 8 + (bits.Length % 8 == 0 ? 0 : 1);
            data = new byte[dl];
            BitArray ba = new BitArray(bits);
            ba.CopyTo(data, 0);
            if (MBmaster != null)
            {
                MBmaster.WriteMultipleCoils(ID, StartAddress, (ushort)sized, data, uiSlaveID);
            }
        }


        /// <summary>
        /// 开关道闸
        /// </summary>
        /// <param name="b1">道闸1开</param>
        /// <param name="b2">    1关</param>
        /// <param name="b3">2开</param>
        /// <param name="b4">2关</param>
        private void ChangDZ2(bool b1, bool b2, bool b3, bool b4)
        {
            lock (MBmaster)
            {
                int i = Convert.ToInt32(1);
                int dzNo = (i - 1) * 2 + 1;
                ushort ID = 6;
                int sized = Convert.ToInt32(dataSize);
                ushort StartAddress = Convert.ToUInt16(DOStartAddress);
                byte[] data = new byte[sized];
                bool[] bits = new bool[sized];
                string s = richTextBox1.Text;
                int st = (dzNo - 1) * 2;
                bits[st] = b1;
                bits[st + 1] = b2;
                bits[st + 2] = b3;
                bits[st + 3] = b4;
                int dl = bits.Length / 8 + (bits.Length % 8 == 0 ? 0 : 1);
                data = new byte[dl];
                BitArray ba = new BitArray(bits);
                ba.CopyTo(data, 0);
                if (MBmaster != null)
                {
                    MBmaster.WriteMultipleCoils(ID, StartAddress, (ushort)sized, data, uiSlaveID);
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //ChangDZ(1,false, false);

            //ChangDZ(1,Convert.ToBoolean(Convert.ToInt32(textBox4.Text)), Convert.ToBoolean(Convert.ToInt32(textBox5.Text)));

            //ChangDZ(2, false, false);

            //ChangDZ(2, Convert.ToBoolean(Convert.ToInt32(textBox6.Text)), Convert.ToBoolean(Convert.ToInt32(textBox7.Text)));

            ChangDZ2(false, false, false, false);
            Thread.Sleep(3000);
            ChangDZ2(Convert.ToBoolean(Convert.ToInt32(textBox4.Text)), Convert.ToBoolean(Convert.ToInt32(textBox5.Text)), Convert.ToBoolean(Convert.ToInt32(textBox6.Text)), Convert.ToBoolean(Convert.ToInt32(textBox7.Text)));
            //Thread.Sleep(5);
        }

        private void btn_kg_Click(object sender, EventArgs e)
        {
            ChangDZ2(false, false, false, false);
            Thread.Sleep(getMiCeccond());
            ChangDZ2(true, false, false, true);
        }

        /// <summary>
        /// 默认为两秒
        /// </summary>
        /// <returns></returns>
        int getMiCeccond()
        {
            int a = 0;
            int.TryParse(textBox8.Text, out a);
            return a != 0 ? a : 2000;
        }

        private void btn_gk_Click(object sender, EventArgs e)
        {
            ChangDZ2(false, false, false, false);
            Thread.Sleep(getMiCeccond());
            ChangDZ2(false, true, true, false);
        }

        private void btn_kk_Click(object sender, EventArgs e)
        {
            ChangDZ2(false, false, false, false);
            Thread.Sleep(getMiCeccond());
            ChangDZ2(true, false, true, false);
        }

        private void btn_gg_Click(object sender, EventArgs e)
        {
            ChangDZ2(false, false, false, false);
            Thread.Sleep(getMiCeccond());
            ChangDZ2(false, true, false, true);
        }

        private void btn_1k_Click(object sender, EventArgs e)
        {
            ChangDZ2(false, false, false, false);
            Thread.Sleep(getMiCeccond());
            ChangDZ(1, true, false);
        }

        private void btn_1g_Click(object sender, EventArgs e)
        {
            ChangDZ2(false, false, false, false);
            Thread.Sleep(getMiCeccond());
            ChangDZ(1, false, true);
        }

        private void btn_2k_Click(object sender, EventArgs e)
        {
            ChangDZ2(false, false, false, false);
            Thread.Sleep(getMiCeccond());
            ChangDZ(2, true, false);
        }

        private void btn_2g_Click(object sender, EventArgs e)
        {
            ChangDZ2(false, false, false, false);
            Thread.Sleep(getMiCeccond());
            ChangDZ(2, false, true);
        }
    }
}


个人签名:己所不欲勿施于人

回帖
  • 消灭零回复
本周热议
html+css+jquery 实现超帅留言墙效果!超帅,不喜勿喷!附完整demo 6
c#如何集成控制Led屏,实现数据发送自动开机、关机等操作! 3
关于站点启用HTTPS访问的通知 1
非法访问资源ip地址公布 1
不用写一句sql的ORM框架,支持多种数据库 1
c# winform 身份证信息读取 0
c#如何获取电脑mac地址,超简单! 0
批量检测指定ip某些端口是否开启,用来做什么自己想吧!!! 0
c# 实现文件下载功能,带下载进度条,可用到软件的自动更新中 0
winform程序如何做到开机自动启动 0
热门资讯
【每日一习话】把事业放在心上 把责任扛在肩上 204 
看图猜成语:明明很简单,是不是大意了 196 
第一观察 | 从两会“如期”召开看百年大党的执政能力 174 
《奇葩说》第七季总决赛,肖骁用不是自己风格的夺冠后,获得表扬 164 
联播+ | 谋定而动 习近平引领京津冀携手下好“一盘棋” 158 
玖月奇迹王小玮近照曝光!穿紧身裤秀出小鸟腿,皮肤白到发光 157 
强力堆料,几乎没有短板、铭瑄iCraft B550M电竞之心主板评测 155 
美媒承认搞错了,但已经来不及了 153 
成人体验馆被封,客人一天点3个娃娃:男人的孤独,谁能懂? 152 
广东一男子离职索赔270万,公司:你月薪才25万 149 
美日共同发表"对中国措辞最强硬"声明 外交部撂重话 143 
王霜首次回应结束留洋原因:不因贾秀全 只因这3个字 143 
扒女明星每日穿搭,千元Coach这样搭,千元CHANEL这样买! 138 
“波塞冬”无法拦截?俄军事专家:只能在发射前攻击它的母艇 103 
孙一宁明明哪也没露,却让人浮想联翩!难怪王思聪放下身段追四年 88