0

我想使用 C# 从 PLC 读取数据并将数据写入 PLC。但是,我对如何读取数据感到困惑。我不确定从保持寄存器中读取。比如我在PLC中设置X0为输入,在C#中如何读取X0的数据?

    public static async Task Main(string[] args)
    {
        Console.WriteLine("Connect to PLC....");

        //this three modules need to configured first
        //done the method created by self-define
        modbusClient.ConnectedChanged += ClientConnectedChanged;
        modbusClient.ReceiveDataChanged += ClientReceivedDataChanged;
        modbusClient.SendDataChanged += ClientSendDataChanged;
        //connect to your modbus rtu
        public static ModbusClient modbusClient = new ModbusClient("COM7"); 
        public static bool LogIn = true;
        modbusClient.UnitIdentifier = 1; // Not necessary since default slaveID = 1;
        modbusClient.Baudrate = 9600;   // Not necessary since default baudrate = 9600
        modbusClient.Parity = Parity.Even;
        modbusClient.StopBits = StopBits.Two;
        modbusClient.ConnectionTimeout = 500;
        modbusClient.Connect();

        await ReadData();                       
    }

    public static async Task ReadData()
    {
        //get data every one minute
        while(true)
        {
            Light light = new Light();
            Button button = new Button();
            Console.WriteLine("Press anykey to continue...");
            Console.ReadLine();

            //Light Name
            var LightName = modbusClient.ReadHoldingRegisters(0, 3);
            //transfer the data from bytes into string
            var formattedLName = Convert.ToString(LightName);
            //assign the name value to your instance
            light.Name = formattedLName;

            //Light Status
            var LightStatus = modbusClient.ReadHoldingRegisters(4, 4);
            var formattedLStatus = Convert.ToBoolean(LightStatus);
            light.Status = formattedLStatus;

            //Button Name
            var ButtonName = modbusClient.ReadHoldingRegisters(8, 4);
            var formattedBName = Convert.ToString(ButtonName);
            button.Name = formattedBName;

            //Button Status
            var ButtonStatus = modbusClient.ReadHoldingRegisters(16, 4);
            var formattedBStatus = Convert.ToBoolean(ButtonStatus);
            button.Status = formattedBStatus;

            Console.WriteLine("------------------------------");
            Console.WriteLine("Result detect from sensor\n");
            Console.WriteLine($"Light name:{light.Name.ToString()}'C Status:{light.Status.ToString()}mS/cm\n");
            Console.WriteLine($"Button name:{button.Name.ToString()}'C Status:{button.Status.ToString()}mS/cm\n");
            Console.WriteLine("------------------------------");

            //add your instance to the octane asset
            await AddInstance(light);
            await AddInstance(button);

            //sleep for one minute for every minute update
            Thread.Sleep(60000);
        }     
    }
4

0 回答 0