如何在C#应用程序中读取PLC的开关位

How to read the bit of switch of PLC in C# application

我正在通过 C# 应用程序读写 Mitsubishi PLC 我需要读取 plc 的日期和时间并在应用程序的 datagridview 中显示。如果我将日期示例年、月和日存储在 D111、D112、D113 中,那么我成功读取了日期,但问题是年存储在 D111 中,月和日存储在开关 D112 字节 0-7 和字节 8-15 中.如果我阅读 D111 和 D112,那么日期将显示为 2022/0309,但我需要 2022/03/09。我怎样才能分别读取字节 0-7 和 8-15 .

int count;
       plc.GetDevice("D22", out count);
       int result;
       plc.GetDevice("D22", out result);
       int read_;
       plc.GetDevice("D22", out read_);
       int read1;
       plc.GetDevice("D22", out read1);
       int year;
       plc.GetDevice("D220", out year);
       int month;
       plc.GetDevice("D221", out month);
       int day;
       plc.GetDevice("D222", out day);
       int hour;
       plc.GetDevice("D223", out hour);
       int minute;
       plc.GetDevice("D224", out minute);
       int second;
       plc.GetDevice("D225", out second);
       SqlCommand cmd;

       cmd = new SqlCommand("insert into [Table](date,time,count,tool,up,down) values(@date,@time,@count,@tool,@up,@down)", con);
       con.Open();



       {

           cmd.Parameters.AddWithValue("@date", year.ToString() + "/" + month.ToString() + "/" + day.ToString());
           cmd.Parameters.AddWithValue("@time", hour.ToString() + ":" + minute.ToString() + ":" + second.ToString());
           cmd.Parameters.AddWithValue("@count", count.ToString());
           cmd.Parameters.AddWithValue("@tool", read1.ToString());
           cmd.Parameters.AddWithValue("@up", result.ToString());
           cmd.Parameters.AddWithValue("@down", read_.ToString());
           cmd.ExecuteNonQuery();
           con.Close();
           DisplayData();
           ClearData();
       }

我不知道你是否真的需要直接从PLC读取一个BYTE,但这可以通过手动将数据拆分成字节来轻松实现:

int monthAndDay; 
plc.GetDevice("D112", out monthAndDay);

//monthAndDay will get something like x0903 (hex)
//Then we split it into bytes 
byte[] bytes = BitConverter.GetBytes(monthAndDay);

//And then we get the data. Just check if the first byte really is the Month in the PLC
int month = bytes[0];
int day = bytes[1];

建议: 将问题的描述从“位”更改为“字节”,因为这就是您的问题所在。 ;)