#include <mil.h>
MIL_ID MilApplication,
MilSystem,
MilCom;
MIL_UINT8 Trigger;
MIL_UINT8 ResultACK;
MIL_UINT8 value = 0;
void WriteStatus(MIL_UINT8 triggerACK, MIL_UINT8 resultReady, MIL_UINT8 resultValue);
void ReadControl(MIL_UINT8* result);
void SetInitialStatus(void);
MIL_INT WaitForTriggerFromPLC(void);
MIL_UINT8 DoProcessing(void);
void WriteResultToPLC(MIL_UINT8 result);
int MosMain(void)
{
MIL_UINT8 processingResult;
MappAllocDefault(M_DEFAULT, &MilApplication, &MilSystem, M_NULL, M_NULL, M_NULL);
McomAlloc(MilSystem, M_COM_PROTOCOL_MODBUS, MIL_TEXT("M_DEFAULT"), M_DEFAULT, M_DEFAULT, &MilCom);
MosPrintf(MIL_TEXT("Waiting for PLC trigger to happen.\nPress <Enter> to end.\n"));
SetInitialStatus();
while (!MosKbhit())
{
if (!WaitForTriggerFromPLC())
{
processingResult = DoProcessing();
WriteResultToPLC(processingResult);
}
}
SetInitialStatus();
McomFree(MilCom);
MappFreeDefault(MilApplication, MilSystem, M_NULL, M_NULL, M_NULL);
return 0;
}
void WriteStatus(MIL_UINT8 triggerACK, MIL_UINT8 resultReady, MIL_UINT8 resultValue)
{
MIL_UINT8 status[2];
status[0] = ((resultReady & 0x01) << 1) | (triggerACK & 0x01);
status[1] = resultValue;
McomWrite(MilCom, M_INPUT_REGISTER, 0, sizeof(status) / sizeof(MIL_UINT16), status);
}
void ReadControl(MIL_UINT8 *result)
{
MIL_UINT8 control[2];
McomRead(MilCom, M_HOLDING_REGISTER, 0, sizeof(control) / sizeof(MIL_UINT16), control);
Trigger = control[0] & 0x1;
ResultACK = (control[0] & 0x2) >> 1;
*result = control[1];
}
void SetInitialStatus(void)
{
WriteStatus(0, 0, 0);
}
MIL_INT WaitForTriggerFromPLC(void)
{
MIL_INT KeyHit;
MIL_UINT8 ResultValue = 0;
do
{
ReadControl(&ResultValue);
MosSleep(10);
KeyHit = MosKbhit();
} while (Trigger == 0 && !KeyHit);
if (!KeyHit)
{
MosPrintf(MIL_TEXT("Received Trigger!\n"));
WriteStatus(1, 0, 0);
}
return KeyHit;
}
MIL_UINT8 DoProcessing(void)
{
value++;
return value;
}
void WriteResultToPLC(MIL_UINT8 result)
{
MIL_INT KeyHit;
MIL_UINT8 ResultCopy = 0;
WriteStatus(0, 1, result);
do
{
ReadControl(&ResultCopy);
MosSleep(10);
KeyHit = MosKbhit();
} while (ResultACK == 0 && !KeyHit);
if (!KeyHit)
{
MosPrintf(MIL_TEXT("Received result ACK! Value:%d Copy:%d\n"), value, ResultCopy);
WriteStatus(0, 0, ResultCopy);
}
}