예제 #1
0
        /// <summary>
        /// Test modbus RTU master function on a slave RTU id = 5
        /// </summary>
        private static void Test_ModbusRTUMaster()
        {
            byte unit_id = 5;
            // Create instance of modbus serial RTU (replace COMx with a free serial port - ex. COM5).
            ModbusMasterSerial mm = new ModbusMasterSerial(ModbusSerialType.RTU, "COM20", 9600, 8, Parity.Even, StopBits.One, Handshake.None);

            // Initialize the MODBUS connection.
            mm.Connect();

            // Read and write some registers on RTU n. 5.
            Random rnd = new Random();

            while (true)
            {
                // Print some nice formatting to the console.
                Console.WriteLine("---------------------- READING ----------------------");

                // Read from a register.
                ushort inputReg1 = mm.ReadHoldingRegisters(unit_id, 0, 1).First();

                // Print the result to the console.
                Console.WriteLine("Holding register n.1  : " + inputReg1.ToString("D5"));

                // Read from another register.
                ushort inputReg41 = mm.ReadInputRegisters(unit_id, 40, 1).First();

                // Print the result to the console.
                Console.WriteLine("Input register   n.41 : " + inputReg41.ToString("D5"));

                // Read from a coil.
                bool coil23 = mm.ReadCoils(unit_id, 22, 1).First();

                // Print the results to the console.
                Console.WriteLine("Coil register    n 23 : " + coil23.ToString());

                // Print some nice formatting to the console.
                Console.WriteLine("---------------------- WRITING ----------------------");

                // Write to a register.
                mm.WriteSingleRegister(unit_id, 4, (ushort)rnd.Next(ushort.MinValue, ushort.MaxValue));

                // ...then read it back.
                ushort holdingReg4 = mm.ReadHoldingRegisters(unit_id, 4, 1).First();

                // Print the result to the console.
                Console.WriteLine("Holding register n.5  : " + holdingReg4.ToString("D5") + Environment.NewLine);

                // Write to another register.
                mm.WriteSingleCoil(unit_id, 2, Convert.ToBoolean(rnd.Next(0, 1)));

                // ...then read it back.
                bool holdingReg3 = mm.ReadCoils(unit_id, 2, 1).First();

                // Print the result to the console.
                Console.WriteLine("Coil register    n.3  : " + holdingReg3.ToString() + Environment.NewLine);

                // Repeat every 2 seconds.
                Thread.Sleep(2000);
            }
        }
예제 #2
0
        /// <summary>
        /// Test modbus RTU master function on a slave RTU id = 5
        /// </summary>
        static void Test_ModbusRTUMaster()
        {
            byte unit_id = 5;
            // Crete instance of modbus serial RTU (replace COMx with a free serial port - ex. COM5)
            ModbusMasterSerial mm = new ModbusMasterSerial(ModbusSerialType.RTU, "COM1", 9600, 8, Parity.Even, StopBits.One, Handshake.None);

            // Exec the connection
            mm.Connect();
            // Read and write some registers on RTU n. 5
            Random rnd = new Random();

            while (true)
            {
                Console.Write(
                    "---------------------- READING ----------------------" + Environment.NewLine +
                    "Holding register n.1  : " + mm.ReadHoldingRegisters(unit_id, 0, 1).First().ToString("D5") + Environment.NewLine +
                    "Input register   n.41 : " + mm.ReadInputRegisters(unit_id, 40, 1).First().ToString("D5") + Environment.NewLine +
                    "Coil register    n 23 : " + mm.ReadCoils(unit_id, 22, 1).First().ToString() + Environment.NewLine +
                    "---------------------- WRITING ----------------------" + Environment.NewLine);
                mm.WriteSingleRegister(unit_id, 4, (ushort)rnd.Next(ushort.MinValue, ushort.MaxValue));
                Console.WriteLine(
                    "Holding register n.5  : " + mm.ReadHoldingRegisters(unit_id, 4, 1).First().ToString("D5") + Environment.NewLine);
                mm.WriteSingleCoil(unit_id, 2, Convert.ToBoolean(rnd.Next(0, 1)));
                Console.WriteLine(
                    "Coil register    n.3  : " + mm.ReadCoils(unit_id, 2, 1).First().ToString() + Environment.NewLine);
                // Exec the cicle each 2 seconds
                Thread.Sleep(2000);
            }
        }
예제 #3
0
        private void button1_Click(object sender, EventArgs e)
        {
            byte unit_id = 1;
            // Crete instance of modbus serial RTU (replace COMx with a free serial port - ex. COM5)
            ModbusMasterSerial mm = new ModbusMasterSerial(ModbusSerialType.RTU, "COM1", 9600, 8, Parity.Even, StopBits.One, Handshake.None);

            // Exec the connection
            mm.Connect();
            // Read and write some registers on RTU n. 5
            Random rnd = new Random();

            while (true)
            {
                textBox1.Text = "Holding register n.1  : " + mm.ReadHoldingRegisters(unit_id, 0, 1).First().ToString("D5") +
                                "Input register   n.41 : " + mm.ReadInputRegisters(unit_id, 40, 1).First().ToString("D5") +
                                "Coil register    n 23 : " + mm.ReadCoils(unit_id, 22, 1).First().ToString();
                mm.WriteSingleRegister(unit_id, 4, (ushort)rnd.Next(ushort.MinValue, ushort.MaxValue));
                textBox2.Text = "Holding register n.5  : " + mm.ReadHoldingRegisters(unit_id, 4, 1).First().ToString("D5");
                mm.WriteSingleCoil(unit_id, 2, Convert.ToBoolean(rnd.Next(0, 1)));
                textBox3.Text = "Coil register    n.3  : " + mm.ReadCoils(unit_id, 2, 1).First().ToString();
                // Exec the cicle each 2 seconds
                Thread.Sleep(2000);
            }
        }
예제 #4
0
        /// <summary>
        /// Read Holding Registers.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonHoldingRegisterRead_Click(object sender, EventArgs e)
        {
            try
            {
                // Get the selected device address.
                byte slaveAddr = GetDeviceAddress();

                // If the register address text box is empty...
                if (string.IsNullOrWhiteSpace(textBoxHoldingRegisterAddressDecimal.Text))
                {
                    // Convert from hex.
                    TextBoxHoldingRegisterAddressHex_Leave(null, null);
                }

                // Get the selected register address.
                ushort regAddr = GetRegisterAddress(textBoxHoldingRegisterAddressDecimal.Text);

                // Get the selected data format.
                DataType dataType = GetDataFormat(comboBoxHoldingRegisterFormat);

                // Calculate the number of registers to read.
                ushort numRegs = 2;
                if (dataType == DataType.String)
                {
                    numRegs = GetNumRegisters(textBoxHoldingRegisterStringLength.Text);
                }

                // Read from the device.
                ushort[] regValues = _mbMaster.ReadHoldingRegisters(slaveAddr, regAddr, numRegs);

                // Format and display the data.
                textBoxHoldingRegisterData.Text = RegistersToString(dataType, regValues);

                // Update the status.
                toolStripStatusLabel1.Text = "Holding Register Read Successfully";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().Name.ToString());
            }
        }
예제 #5
0
        private void readModbus()
        {
            try
            {
                ushort[] regs;
                regs = mm.ReadHoldingRegisters(1, 0, MB_REGS);

                commStatus.Text = "COMM OK";

                if ((regs != null) && (regs.Length == MB_REGS))
                {
                    switch (regs[MB_CAM_SELECT])
                    {
                    case CAM1:
                        selectCam1.Checked = true;
                        break;

                    case CAM2:
                        selectCam2.Checked = true;
                        break;

                    case CAM3:
                        selectCam3.Checked = true;
                        break;
                    }

                    switch (regs[MB_CAM1_SWITCH])
                    {
                    case SWITCH_OFF:
                        cam1Off.Checked = true;
                        break;

                    case SWITCH_ON:
                        cam1On.Checked = true;
                        break;

                    case SWITCH_AUTO:
                        cam1Auto.Checked = true;
                        break;
                    }

                    switch (regs[MB_CAM2_SWITCH])
                    {
                    case SWITCH_OFF:
                        cam2Off.Checked = true;
                        break;

                    case SWITCH_ON:
                        cam2On.Checked = true;
                        break;

                    case SWITCH_AUTO:
                        cam2Auto.Checked = true;
                        break;
                    }

                    switch (regs[MB_CAM3_SWITCH])
                    {
                    case SWITCH_OFF:
                        cam3Off.Checked = true;
                        break;

                    case SWITCH_ON:
                        cam3On.Checked = true;
                        break;

                    case SWITCH_AUTO:
                        cam3Auto.Checked = true;
                        break;
                    }

                    if (regs[MB_RAIN_RLTYPE] == NORMALLY_OPEN)
                    {
                        noRainToolStripMenuItem.Checked = true;
                        ncRainToolStripMenuItem.Checked = false;
                    }
                    else
                    {
                        noRainToolStripMenuItem.Checked = false;
                        ncRainToolStripMenuItem.Checked = true;
                    }

                    if (regs[MB_NIGHT_RLTYPE] == NORMALLY_OPEN)
                    {
                        noNightToolStripMenuItem.Checked = true;
                        ncNightToolStripMenuItem.Checked = false;
                    }
                    else
                    {
                        noNightToolStripMenuItem.Checked = false;
                        ncNightToolStripMenuItem.Checked = true;
                    }

                    if (regs[MB_CAM1_STATUS] == 1)
                    {
                        cam1Status.Text      = "on";
                        cam1Status.BackColor = COLOR_ON;
                    }
                    else
                    {
                        cam1Status.Text      = "off";
                        cam1Status.BackColor = COLOR_OFF;
                    }

                    if (regs[MB_CAM2_STATUS] == 1)
                    {
                        cam2Status.Text      = "on";
                        cam2Status.BackColor = COLOR_ON;
                    }
                    else
                    {
                        cam2Status.Text      = "off";
                        cam2Status.BackColor = COLOR_OFF;
                    }

                    if (regs[MB_CAM3_STATUS] == 1)
                    {
                        cam3Status.Text      = "on";
                        cam3Status.BackColor = COLOR_ON;
                    }
                    else
                    {
                        cam3Status.Text      = "off";
                        cam3Status.BackColor = COLOR_OFF;
                    }

                    if (regs[MB_NIGHT_SENSOR] == 1)
                    {
                        sensorNight.Text = "Nighttime";
                    }
                    else
                    {
                        sensorNight.Text = "Daytime";
                    }

                    if (regs[MB_RAIN_SENSOR] == 1)
                    {
                        sensorRain.Text = "Not Raining";
                    }
                    else
                    {
                        sensorRain.Text = "Raining";
                    }
                }
            }
            catch (Exception) { }
            {
                commStatus.Text = "COMM ERR";
                reconnect();
            }
        }
예제 #6
0
        public void ModbusRTUMaster_ReadRegister(byte unit_id)
        {
            //problem
            //1.ReadHoldingRegisters after ReadInputRegisters,then the receive data will change

            //===================//
            //==Read Input resister
            //===================//
            //ushort[] InputReg_array = mm.ReadInputRegisters(unit_id, REG_INPUT_START, REG_INPUT_NREGS);
            //if (InputReg_array == null)
            //{
            //    Err_State = (UInt16)eErrorSate.RECEIVE_NULL;
            //    return;
            //}
            //else if (InputReg_array.Length != REG_INPUT_NREGS)//stanley
            //{
            //    Err_State = (UInt16)eErrorSate.RECEIVE_LENGTH;
            //    return;
            //}

            //int i = 0;
            //for (i = 0; i < DEF_MAX_AXIS; i++)
            //{
            //    PosVal[i] = InputReg_array[i];
            //    VelValue[i] = InputReg_array[i + DEF_MAX_AXIS];
            //}

            //Err_State = InputReg_array[7 + 7];
            //TargetPosX = Convert.ToInt16(num_array[7 + 7 + 1]);
            //TargetPosY = Convert.ToInt16(num_array[7 + 7 + 2]);
            //TargetPosZ = Convert.ToInt16(num_array[7 + 7 + 3]);
            //OPMode = Convert.ToInt16(num_array[7 + 7 + 4]);
            //SpeedRatio = Convert.ToInt16(num_array[7 + 7 + 5]);

            //Console.Write("addr999=0x" + num_array[0].ToString("x") + "  " +
            //                "addr1000=0x" + num_array[1].ToString("x") + "  " +
            //                "addr1001=0x" + num_array[2].ToString("x") + "  " +
            //                "addr1002=0x" + num_array[3].ToString("x") + Environment.NewLine);
            //Thread.Sleep(100);


            //========================//
            //==Read Holding resister=//
            //========================//
            ushort[] HoldReg_array = mm.ReadHoldingRegisters(unit_id, REG_HOLDING_START, REG_HOLDING_NREGS);  //ReadInputRegisters 執行完直接再Read會出錯
            if (HoldReg_array == null)
            {
                Err_State = (UInt16)eErrorSate.RECEIVE_NULL;
                return;
            }
            else if (HoldReg_array.Length != REG_HOLDING_NREGS) //stanley
            {
                Err_State = (UInt16)eErrorSate.RECEIVE_LENGTH;
                return;
            }

            TargetPosX = Convert.ToInt16(HoldReg_array[0]);
            TargetPosY = Convert.ToInt16(HoldReg_array[1]);
            TargetPosZ = Convert.ToInt16(HoldReg_array[2]);
            OPMode     = Convert.ToInt16(HoldReg_array[3]);
            SpeedRatio = TwoUshortToFloat(HoldReg_array[4], HoldReg_array[5]);

            for (byte i = 0; i < DEF_MAX_AXIS; i++)
            {
                //TarPos[i] = HoldReg_array[6 + i];
                PosVal[i] = HoldReg_array[Convert.ToUInt16(eMbData.DEF_INX_POSVAL1 + i)];
            }

            Err_State = HoldReg_array[27];
        }