#define MAX_SERIAL_PORT 3
int main(
int argc,
char *argv[])
{
int retval = 0;
UINT32 rc = 0;
UINT8 slot = 0;
UINT8 unitID = 0x10;
UINT16 aiAddress = 0x1000;
UINT32 timeoutMs = 5 * 1000;
float aiValue = 0;
UINT8 doSlot = 1;
UINT8 doChannel = 0;
UINT32 doValue = 0;
UINT8 exceptionCode = 0;
while((retval = getopt(argc, argv, "hs:p:u:a:S:C:")) != -1)
{
switch(retval)
{
case 's':
slot = atoi(optarg);
{
printf("Error serial slot = %d\r\n", slot);
exit(1);
}
break;
case 'p':
port = atoi(optarg);
{
printf("Error serial port = %d\r\n", port);
exit(1);
}
break;
case 'u':
unitID = atoi(optarg);
break;
case 'a':
aiAddress = atoi(optarg);
break;
case 'S':
doSlot = atoi(optarg);
{
printf("Error DO slot = %d\r\n", doSlot);
exit(1);
}
break;
case 'C':
doChannel = atoi(optarg);
{
printf("Error DO channel = %d\r\n", doChannel);
exit(1);
}
break;
case '?':
case 'h':
default:
printf("Modbus RTU Master.\n\n");
printf("Usage: ./modbus_rtu_master [OPTIONS]\n\n");
printf("Options:\n");
printf(
"\t%-8s slot [%d-%d]. Default slot = %d\n",
"-s", 0,
MAX_SLOT, slot);
printf("\t%-8s (slot 0: Built-in COM Ports, slot 1 ~ 9: Expansion COM Ports)\n", "");
printf(
"\t%-8s port [%d-%d]. Default port = %d\n",
"-p", 0,
MAX_SERIAL_PORT, port);
printf("\t%-8s Unit ID [0x%x-0x%x]. Default Unit ID = 0x%x (%d)\n", "-u", 0x0, 0xFFFF, unitID, unitID);
printf("\t%-8s AI Address [0x%x-0x%x]. Default AI Address = 0x%x (%d)\n", "-a", 0x0, 0xFFFF, aiAddress, aiAddress);
printf(
"\t%-8s DO slot [%d-%d]. Default DO slot = %d\n",
"-S", 0,
MAX_SLOT, doSlot);
printf("\t%-8s (slot 0: Built-in IO, slot 1 ~ 9: IO Module)\n", "");
printf(
"\t%-8s DO channel [%d-%d]. Default DO channel = %d\n",
"-C", 0,
MAX_CHANNEL, doChannel);
printf("\n");
return 0;
}
}
{
printf("MX_RTU_Modbus_Master_Init(), return code = %d\r\n", rc);
exit(1);
}
memset(¶m, 0, sizeof(param));
printf("Slot = %d, Port = %d, UnitID = 0x%x, AI Address = 0x%x, DO Slot = %d, DO Channel = %d\r\n", slot, port, unitID, aiAddress, doSlot, doChannel);
{
printf("MX_RTU_Modbus_Rtu_Master_Open(%d, %d, ¶m), return code = %d\r\n", slot, port, rc);
exit(1);
}
while(1)
{
{
printf("MX_RTU_Modbus_Rtu_Master_Read_Input_Regs(%d, %d, 0x%x, 0x%x, %d, &aiValue, %d), return code = %d, exception code = %d\r\n", slot, port, unitID, aiAddress, 2, timeoutMs, rc, exceptionCode);
exit(1);
}
if(aiValue >= 5.0)
{
{
printf("MX_RTU_Module_DO_Value_Get(%d, &doValue), return code = %d\r\n", doSlot, rc);
exit(1);
}
doValue |= (1 << doChannel);
{
printf("MX_RTU_Module_DO_Value_Set(%d, %x), return code = %d\r\n", doSlot, doValue, rc);
exit(1);
}
}
else
{
{
printf("MX_RTU_Module_DO_Value_Get(%d, &doValue), return code = %d\r\n", doSlot, rc);
exit(1);
}
doValue &= ~(1 << doChannel);
{
printf("MX_RTU_Module_DO_Value_Set(%d, %x), return code = %d\r\n", doSlot, doValue, rc);
exit(1);
}
}
if(aiValue > 8.0) break;
sleep(1);
}
{
printf("MX_RTU_Modbus_Rtu_Master_Close(%d, %d), return code = %d\r\n", slot, port, rc);
exit(1);
}
return 0;
}