您现在所在的是:

施耐德电气论坛

回帖:0个,阅读:628 [上一页] [1] [下一页]
1098
痞龙
文章数:64
年度积分:59
历史总积分:1098
品牌积分(施耐德):0
注册时间:2007/8/17
发站内信
发表于:2015/3/4 15:01:55
#0楼
现在有2个施耐德M221plc,上位机是一台笔记本电脑通过C语言编写的软件,对PLC内的MW寄存器进行读写操作。现在是往PLC写入数据的时候是成功的,可读取的数据不对,如我写入%mw1为1,PLC编程看到已经写入,可读取的数据就是没有。这是啥原因呢,有高手可以请教吗。读取数据代码如下
// send cmd to read data from device
BOOL CDemoDlg::ToReadDevice(int ucRegNo, int ucRegNums)
{
TCHAR str[256];

// build request of form 0 0 0 0 0 6 ui 3 rr rr nn nn
unsigned char obuf[256] = {0};
unsigned char ibuf[256] = {0};

for (int i = 0; i < 5; i ++) obuf[i] = 0;

obuf[5]  = 6;
obuf[6]  = 0; // unit;
obuf[7]  = 3; // cmd;
obuf[8]  = ucRegNo >> 8; // ucRegNo >> 8;
obuf[9]  = ucRegNo & 0xff; // ucRegNo & 0xff;
obuf[10] = ucRegNums >> 8;
obuf[11] = ucRegNums & 0xff;

//
fd_set fds;
FD_ZERO(&fds);
timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;

FD_SET(m_sClient, &fds);
i = select(32, NULL, &fds, NULL, &tv);
if (i <= 0)
{
WriteLog(_T("select - error.\r\n"));
return FALSE;
}

// send request
i = send(m_sClient, (char*)obuf, 12, 0);
if (i < 12)
{
WriteLog(_T("failed to send all 12 chars.\r\n"));
return FALSE;
}

// wait for response
FD_SET(m_sClient, &fds);
i = select(32, &fds, NULL, NULL, &tv);
if (i <= 0)
{
WriteLog(_T("no TCP response received.\r\n"));
return FALSE;
}

// read response
i = recv(m_sClient, (CHAR*)ibuf, 256, 0);
if (i < 9)
{
if (i == 0)
{
WriteLog(_T("unexpected close of connection at remote end.\r\n"));
}
else
{
sprintf(str, _T("response was too short - %d chars.\r\n"), i);
WriteLog(str);
}
}
else if (ibuf[7] & 0x80)
{
sprintf(str, _T("Modbus exception response - type %d.\r\n"), ibuf[8]);
WriteLog(str);
}
//else if (i != (9 + 2 * ucRegNums))
//{
// sprintf(str, _T("incorrect response size is %d expected %d.\r\n"), i, (9 + 2 * ucRegNums));
// WriteLog(str);
//}
else
{
for (i = 0; i < ucRegNums; i ++)
{
unsigned short w = (ibuf[9 + i + i] << 8) + ibuf[10 + i + i];
sprintf(str, _T("word%d = %d\r\n"), i, w);
WriteLog(str);
}
}

WriteLog(_T("====================\r\n"));

return TRUE;
}

关于我们 | 联系我们 | 广告服务 | 本站动态 | 友情链接 | 法律声明 | 非法和不良信息举报

工控网客服热线:0755-86369299
版权所有 工控网 Copyright©2024 Gkong.com, All Rights Reserved

46.8003