#include "assert.h"
#include "support/AT91SAM7X256.h"
#include "support/lib_AT91SAM7X256.h"
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "mb.h"
#define REG_HOLDING_START 0x1000
#define REG_HOLDING_NREGS 130
#define REG_INPUT_START 0x1000
#define REG_INPUT_NREGS 4
static USHORT usRegHoldingStart = REG_HOLDING_START;
static USHORT usRegHoldingBuf[REG_HOLDING_NREGS];
static USHORT usRegInputStart = REG_INPUT_START;
static USHORT usRegInputBuf[REG_INPUT_NREGS];
STATIC void vModbusTask( void *pvParameters );
STATIC void vSetupHardware( void );
int
main( void )
{
vSetupHardware( );
( void )xTaskCreate( vModbusTask, NULL, configMINIMAL_STACK_SIZE, NULL,
tskIDLE_PRIORITY, NULL );
vTaskStartScheduler( );
return 0;
}
static void
vModbusTask( void *pvParameters )
{
int i;
( void )eMBInit( MB_RTU, 0x0A, 0, 38400, MB_PAR_EVEN );
for( i = 0; i < REG_HOLDING_NREGS; i++ )
{
usRegHoldingBuf[i] = ( unsigned short )i;
}
for( i = 0; i < REG_INPUT_NREGS; i++ )
{
usRegInputBuf[i] = ( unsigned short )i;
}
( void )eMBEnable( );
for( ;; )
{
( void )eMBPoll( );
}
}
eMBErrorCode
eMBRegInputCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNRegs )
{
eMBErrorCode eStatus = MB_ENOERR;
int iRegIndex;
if( ( usAddress >= REG_INPUT_START )
&& ( usAddress + usNRegs <= REG_INPUT_START + REG_INPUT_NREGS ) )
{
iRegIndex = ( int )( usAddress - usRegInputStart );
while( usNRegs > 0 )
{
*pucRegBuffer++ = ( unsigned char )( usRegInputBuf[iRegIndex] >> 8 );
*pucRegBuffer++ = ( unsigned char )( usRegInputBuf[iRegIndex] & 0xFF );
iRegIndex++;
usNRegs--;
}
}
else
{
eStatus = MB_ENOREG;
}
return eStatus;
}
eMBErrorCode
eMBRegHoldingCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNRegs, eMBRegisterMode eMode )
{
eMBErrorCode eStatus = MB_ENOERR;
int iRegIndex;
if( ( usAddress >= REG_HOLDING_START ) &&
( usAddress + usNRegs <= REG_HOLDING_START + REG_HOLDING_NREGS ) )
{
iRegIndex = ( int )( usAddress - usRegHoldingStart );
switch ( eMode )
{
case MB_REG_READ:
while( usNRegs > 0 )
{
*pucRegBuffer++ = ( unsigned char )( usRegHoldingBuf[iRegIndex] >> 8 );
*pucRegBuffer++ = ( unsigned char )( usRegHoldingBuf[iRegIndex] & 0xFF );
iRegIndex++;
usNRegs--;
}
break;
case MB_REG_WRITE:
while( usNRegs > 0 )
{
usRegHoldingBuf[iRegIndex] = *pucRegBuffer++ << 8;
usRegHoldingBuf[iRegIndex] |= *pucRegBuffer++;
iRegIndex++;
usNRegs--;
}
}
}
else
{
eStatus = MB_ENOREG;
}
return eStatus;
}
eMBErrorCode
eMBRegCoilsCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNCoils, eMBRegisterMode eMode )
{
return MB_ENOREG;
}
eMBErrorCode
eMBRegDiscreteCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNDiscrete )
{
return MB_ENOREG;
}
void
vSetupHardware( void )
{
vMBPInit( );
AT91C_BASE_PMC->PMC_PCER = 1 << AT91C_ID_PIOA;
AT91C_BASE_PMC->PMC_PCER = 1 << AT91C_ID_PIOB;
}