首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在C#应用中读取PLC的开关位

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

Stack Overflow用户
提问于 2022-03-09 01:05:54
回答 1查看 200关注 0票数 1

我正在通过C#应用程序读写三菱PLC,我需要读取plc的日期和时间,并在应用程序的数据视图中显示。如果我在D111、D112、D113中存储日期示例--年份、月和日--那么我成功地读取了日期,但问题是,年份存储在D111中,月份和日存储在交换机D112字节0-7和字节8-15中。如果我阅读D111和D112,那么日期将显示为2022/0309,但我需要2022/03/09。如何分别读取字节0-7和8-15 .

代码语言:javascript
复制
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();
       }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-10 12:36:37

我不知道您是否真的需要直接从PLC读取一个字节,但是通过手动将数据拆分成字节可以很容易地实现:

代码语言:javascript
复制
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",因为这就是您的问题所在。;)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71403184

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档