我正在通过C#应用程序读写三菱PLC,我需要读取plc的日期和时间,并在应用程序的数据视图中显示。如果我在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();
}发布于 2022-03-10 12:36:37
我不知道您是否真的需要直接从PLC读取一个字节,但是通过手动将数据拆分成字节可以很容易地实现:
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];Recommendation:将问题的描述从“位”改为"Bytes",因为这就是您的问题所在。;)
https://stackoverflow.com/questions/71403184
复制相似问题