Example #1
0
static void
vInitTask( void *pvParameters )
{
    const unsigned char ucSlaveIDAdditonal[] = { 0xAA, 0xBB, 0xCC };
    eMBErrorCode    eStatus;

    /* Select either ASCII or RTU Mode. */
    eStatus = eMBInit( MB_RTU, 0x0A, 0, 38400, MB_PAR_EVEN );
    assert( eStatus == MB_ENOERR );

    /* Configure the slave id of the device. */
    eStatus = eMBSetSlaveID( 44, TRUE, ucSlaveIDAdditonal, 3 );
    assert( eStatus == MB_ENOERR );

    /* Enable the Modbus Protocol Stack. */
    eStatus = eMBEnable(  );

    for( ;; )
    {
        /* Call the main polling loop of the Modbus protocol stack. Internally
         * the polling loop waits for a new event by calling the port 
         * dependent function xMBPortEventGet(  ). In the FreeRTOS port the
         * event layer is built with queues.
         */
        ( void )eMBPoll(  );

        /* Here we simply count the number of poll cycles. */
        usRegInputBuf[0]++;
    }
}
Example #2
0
/* ----------------------- Start implementation -----------------------------*/
int
main( void )
{
    const UCHAR     ucSlaveID[] = { 0xAA, 0xBB, 0xCC };
    eMBErrorCode    eStatus;

//    DDRA |= 0b00001110;
	 

    eStatus = eMBInit( MB_RTU, 0x0A, 0, 38400, MB_PAR_NONE );

    eStatus = eMBSetSlaveID( 0x34, TRUE, ucSlaveID, 3 );
    sei(  );

    /* Enable the Modbus Protocol Stack. */
    eStatus = eMBEnable(  );

    for( ;; )
    {
        ( void )eMBPoll(  );

        /* Here we simply count the number of poll cycles. */
        usRegInputBuf[0]++;
    }
}
Example #3
0
/**
 * MCU: Atmega328
 * Fuses: Oscilador interno a 8 Mhz (sin dividir por 8)
 * 		-U lfuse:w:0xe2:m -U hfuse:w:0xd1:m -U efuse:w:0x07:m
 */
int main(void) {
	adc_init();

	timer0_init(timer0_callback);

	i2c_init();

	rtc_init(rtc);
	rtc_sqw_rate(rtc, 1);
	rtc_sqw_enable(rtc);
	rtc_clock_start(rtc);

	eMBInit(MB_RTU, 0x03, 0, 9600, MB_PAR_NONE);
	eMBSetSlaveID(0x3, TRUE, (UCHAR*) "demeter", 8);
	eMBEnable();

	blinkenlight(5, 100);

	parameters_init();

	ports_init();

	f_mount(&fs, "", 0);
	update_log_filename();

	while (1) {
		eMBPoll();
		update_state();

		_delay_ms(100);
	}

	return (0);
}
Example #4
0
/* ----------------------- Start implementation -----------------------------*/
int
main( void )
{
    const UCHAR     ucSlaveID[] = { 0xAA, 0xBB, 0xCC };
    eMBErrorCode    eStatus;
	ULONG			my_counter = 0;

    eStatus = eMBInit( MB_RTU, 0x0A, 0, 38400, MB_PAR_EVEN );

    eStatus = eMBSetSlaveID( 0x34, TRUE, ucSlaveID, 3 );
    sei(  );

    /* Enable the Modbus Protocol Stack. */
    eStatus = eMBEnable(  );

    for( ;; )
    {
        ( void )eMBPoll(  );

        /* Here we simply count the number of poll cycles. */
		if( my_counter++ > 100000) {
			my_counter = 0;
			usRegInputBuf[0]++;
		}
        /* The constant value. */
        usRegInputBuf[1] = 33;
    }
}
bool_t initJbus485 (void)
{
    eMBErrorCode    eStatus;
    getJbus485StatesFromEeprom ();

    if ((eStatus = eMBInit (jbus485States.mode, jbus485States.address,
                            1, jbus485States.baudRate,
                            jbus485States.parity, jbus485States.nbBitsStop)) != MB_ENOERR) {
        DebugTrace ("eMBInit Failed err=%d", eStatus);
        return FALSE;
    }

    if ((eStatus = eMBSetSlaveID (0x42, TRUE, UniqProcessorId, UniqProcessorIdLen))  != MB_ENOERR) {
        DebugTrace ("eMBSetSlaveID Failed err=%d", eStatus);
        return FALSE;
    }

    if ((eStatus = eMBEnable())  != MB_ENOERR) {
        DebugTrace ("eMBEnable Failed err=%d", eStatus);
        return FALSE;
    }
    pxMBPortCBTimerExpired ();

    return TRUE;
}
static void Modbus_RS485_Task(void *pvParameters)
{
    eMBEnable(&stContext_RS485);
    Watchdog_SetTaskStatus(RS485_TASK,TASK_ACTIVE);
    for( ;; )
    {
        eMBPoll(&stContext_RS485);
        vTaskDelay(MODBUS_POLL_TIME);
        Watchdog_IncrementCouter(RS485_TASK);
    }
}
Example #7
0
/* ----------------------- Start implementation -----------------------------*/
int
main( void )
{

    /* Select either ASCII or RTU Mode. */
    ( void )eMBInit( MB_RTU, 0x0A, 0, 9600, MB_PAR_EVEN );

    /* Enable the Modbus Protocol Stack. */
    ( void )eMBEnable(  );
    for( ;; )
    {
        /* Call the main polling loop of the Modbus protocol stack. */
        ( void )eMBPoll(  );
    }
}
Example #8
0
static void
vModbusTask( void *pvParameters )
{
    /* Select either ASCII or RTU Mode. */
    ( void )eMBInit( MB_RTU, 0x0A, 0, 38400, MB_PAR_EVEN );

    /* Enable the Modbus Protocol Stack. */
    ( void )eMBEnable(  );

    /* Enter main loop. */
    for( ;; )
    {
        /* Call the main polling loop of the Modbus protocol stack. */
        ( void )eMBPoll(  );
    }
}
Example #9
0
/* ==============================================
 main task routine
 ============================================== */
int main(void) {
	pool_memadd((uint32_t) pool, sizeof(pool));

#ifdef DEBUG
	dbg.start();
#endif

	eMBErrorCode eStatus;
//	dbg.waitToDebugMode();

#if MB_TCP_ENABLED == 1
	eStatus = eMBTCPInit( MB_TCP_PORT_USE_DEFAULT );
#endif

	if (eStatus != MB_ENOERR)
		dbg.println("can't initialize modbus stack!");

	/* Enable the Modbus Protocol Stack. */
	eStatus = eMBEnable();
	if (eStatus != MB_ENOERR)
		dbg.println("can't enable modbus stack!");

	// Initialise some registers
	usRegInputBuf[1] = 0x1234;
	usRegInputBuf[2] = 0x5678;
	usRegInputBuf[3] = 0x9abc;

	// debug LED
	CPin led(LED1);
	CTimeout tm;

	// Enter an endless loop
	while (1) {
		if ( tm.read()>0.5 ) {
			led = !led;
			tm.reset();
		}

	    eStatus = eMBPoll(  );

	    /* Here we simply count the number of poll cycles. */
	    usRegInputBuf[0]++;
	}
	return 0;
}
Example #10
0
/* ----------------------- Start implementation -----------------------------*/
int
main( void )
{
    eMBErrorCode    eStatus;

    eStatus = eMBInit( MB_RTU, 0x0A, 0, 38400, MB_PAR_EVEN );

    /* Enable the Modbus Protocol Stack. */
    eStatus = eMBEnable(  );

    for( ;; )
    {
        ( void )eMBPoll(  );

        /* Here we simply count the number of poll cycles. */
        usRegInputBuf[0]++;
    }
}
/* ----------------------- Start implementation -----------------------------*/
int main(void)
{
  eMBErrorCode eStatus;

  eStatus = eMBInit(MB_RTU, 0x0A, 0, BAUD_MODBUS, MB_PAR_EVEN); /* Port 0 is defined in portserial.c */

  sei( );

  /* Enable the Modbus Protocol Stack. */
  eStatus = eMBEnable();

  for (;;)
  {
    (void) eMBPoll();

    /* Here we simply count the number of poll cycles. */
    usRegInputBuf[0]++;
  }
}
Example #12
0
/**
  * @功能
  * @参数
  * @返回值
  */
int main(void)
{
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
    NVIC_Configuration();
    LED_Config();

    /*       模式 从机地址 端口 波特率 校验位*/
    eMBInit( MB_RTU, 0x02, 0, 9600, MB_PAR_NONE );

    /* Enable the Modbus Protocol Stack. */
    eMBEnable(  );

    for( ;; )
    {
        ( void )eMBPoll(  );
        /* Here we simply count the number of poll cycles. */
//     usRegInputBuf[0]++;
    }
}
Example #13
0
/* ----------------------- Start implementation -----------------------------*/
int
main( void )
{
    _SetupHardware(  );
    
    const UCHAR     ucSlaveID[] = { 0xAA, 0xBB, 0xCC };
    eMBErrorCode    eStatus;

    for( ;; )
    {
        if( MB_ENOERR != ( eStatus = eMBInit( MB_RTU, 0x0A, 1, 38400, MB_PAR_EVEN ) ) )
        {
            /* Can not initialize. Add error handling code here. */
        }
        else
        {      
            if( MB_ENOERR != ( eStatus = eMBSetSlaveID( 0x34, TRUE, ucSlaveID, 3 ) ) )
            {
                /* Can not set slave id. Check arguments */
            }
            else if( MB_ENOERR != ( eStatus = eMBEnable(  ) ) )
            {
                /* Enable failed. */
            }
            else
            {      
                usRegHoldingBuf[0] = 1;
                do
                {
                    ( void )eMBPoll(  );
            
                    /* Here we simply count the number of poll cycles. */
                    usRegInputBuf[0]++;
                }
                while( usRegHoldingBuf[0] );
                ( void )eMBDisable(  );
                ( void )eMBClose(  );                
            }
        }
    }    
    return 1;
}
Example #14
0
DWORD           WINAPI
dwPollingThread( LPVOID lpParameter )
{
    eSetPollingThreadState( RUNNING );

    if( eMBEnable(  ) == MB_ENOERR )
    {
        do
        {
            if( eMBPoll(  ) != MB_ENOERR )
                break;
        }
        while( eGetPollingThreadState(  ) != SHUTDOWN );
    }

    ( void )eMBDisable(  );

    eSetPollingThreadState( STOPPED );

    return 0;
}
Example #15
0
/**
 * Poll the modbus.
 *
 * @param pvParameter
 */
void           *
pvPollingThread( void *pvParameter )
{
    vSetPollingThreadState( RUNNING );
    DEBUG_PUTSTRING("Thread started!");
    if( eMBEnable(  ) == MB_ENOERR )
    {
        do
        {
            if( eMBPoll(  ) != MB_ENOERR )
                break;
        }
        while( eGetPollingThreadState(  ) != SHUTDOWN );
    }

    ( void )eMBDisable(  );
    vSetPollingThreadState( STOPPED );
    DEBUG_PUTSTRING("Thread stopped!");
    cmd_done(BOOT_EXIT);
    return 0;
}
Example #16
0
static void
vTaskMODBUS( void *pvArg )
{
    const UCHAR     ucSlaveID[] = { 0xAA, 0xBB, 0xCC };
    eMBErrorCode    eStatus;

    for( ;; )
    {
        if( MB_ENOERR != ( eStatus = eMBInit( MB_ASCII, 0x0A, 1, 38400, MB_PAR_EVEN ) ) )
        {
            /* Can not initialize. Add error handling code here. */
        }
        else
        {
            if( MB_ENOERR != ( eStatus = eMBSetSlaveID( 0x34, TRUE, ucSlaveID, 3 ) ) )
            {
                /* Can not set slave id. Check arguments */
            }
            else if( MB_ENOERR != ( eStatus = eMBEnable(  ) ) )
            {
                /* Enable failed. */
            }
            else
            {
                usRegHoldingBuf[0] = 1;
                do
                {
                    ( void )eMBPoll(  );

                    /* Here we simply count the number of poll cycles. */
                    usRegInputBuf[0]++;
                }
                while( usRegHoldingBuf[0] );
            }
            ( void )eMBDisable(  );
            ( void )eMBClose(  );
        }
        vTaskDelay( 50 );
    }
}
Example #17
0
int main(void)
{
  board_init();
  system_init();
  QueueInit(&lock_fifo);
  //modbus485有线的配置
  eMBInit(MB_RTU, MSlaveID, MODBUS_UART_NUMBER, MODBUS_UART_BAUDRATE, MB_PAR_NONE); 
  eMBEnable();
  while (1) {
    
    if(Timer2_Get_Sensor_Data() == 0){
      QueueInit(&lock_fifo);
      if(Door_Flag1 == 1)
    {
        SetAndSendRemoteOpenDoorCmd();
        
        Door_Flag1 = 0;
    }      
    }
    
  }
}
Example #18
0
File: main.c Project: Def152/AVR
/* ----------------------- Start implementation -----------------------------*/
int main( void )
{
    const UCHAR     ucSlaveID[] = { 0xAA, 0xBB, 0xCC };
    eMBErrorCode    eStatus;

    eStatus = eMBInit( MB_RTU, 0x0A, 0, 9600, MB_PAR_NONE ); // 0x0A slave address

    eStatus = eMBSetSlaveID( 0x34, TRUE, ucSlaveID, 3 );
    /* Enable the Modbus Protocol Stack. */
    eStatus = eMBEnable(  );



    sei(  );
    while(1)
    {
        ( void )eMBPoll(  );

        usRegInputBuf[0] = 1234;
        usRegHoldingBuf[0] = 5678;
    }
}
Example #19
0
/* ----------------------- Start implementation -----------------------------*/
int
main( void )
{
    const UCHAR     ucSlaveID[] = { 0x01 };
    eMBErrorCode    eStatus;

    eStatus = eMBInit( MB_RTU, 0x01, 0, 38400, MB_PAR_EVEN );

    eStatus = eMBSetSlaveID(ucSlaveID[0], TRUE, ucSlaveID, 3 );
    sei(  );

    /* Enable the Modbus Protocol Stack. */
    eStatus = eMBEnable(  );

    for( ;; )
    {
        ( void )eMBPoll(  );

        /* Here we simply count the number of poll cycles. */
        usRegInputBuf[0]++;
    }
}
Example #20
0
/* ----------------------- Start implementation -----------------------------*/
int
main( void )
{
    eMBErrorCode    eStatus;

    eStatus = eMBInit( MB_RTU, SLAVE_ID, 0, 9600, MB_PAR_NONE );

    /* Enable the Modbus Protocol Stack. */
    eStatus = eMBEnable(  );
    
    // Initialise some registers
    usRegInputBuf[1] = 0x1234;
    usRegInputBuf[2] = 0x5678;
    usRegInputBuf[3] = 0x9abc;        

    for( ;; )
    {
        ( void )eMBPoll(  );
                
        /* Here we simply count the number of poll cycles. */
        usRegInputBuf[0]++;
    }
}
Example #21
0
static void
vModbusTask( void *pvParameters )
{
    int             i;

    /* Select either ASCII or RTU Mode. */
    ( void )eMBInit( MB_RTU, 0x0A, 0, 38400, MB_PAR_EVEN );

    /* Initialize the holding register values before starting the
     * Modbus stack. */
    for( i = 0; i < REG_HOLDING_NREGS; i++ )
    {
        usRegHoldingBuf[i] = ( unsigned short )i;
    }

    /* Enable the Modbus Protocol Stack. */
    ( void )eMBEnable(  );
    for( ;; )
    {
        /* Call the main polling loop of the Modbus protocol stack. */
        ( void )eMBPoll(  );
    }
}
Example #22
0
int main( int argc, char *argv[] )
{
  int c;
  int option_index = 0;
  int received;
  int mq_id;
  struct sIPCMsg mymsg;

  char *ttydev = DEFAULT_TTY;
  char *parity_s = DEFAULT_PAR;
  int parity;
  int baud = DEFAULT_BAUD;
  USHORT result[255] = {0,};
  int result_int = 0;

  USHORT usLen;
  eMBErrorCode err = MB_ENOERR;

  int reg_start = DEFAULT_REGISTER_START;
  int address = DEFAULT_ADDRESS;
  int regt = -1;
  int reg_action = -1;
  int reg_action_param = -1;
  int no_reg = -1;
  int run_forground = 0;
  int errorcount = 0;
  struct pidfile *pidfile = NULL;

  UCHAR *pucFrame;
  eMBException    eException;
  UCHAR ucFuncType;

  /* Parse cmd-line options */
  while ( (c = getopt_long (argc, argv, "hVd:s:p:r:t:c:a:f", long_options, &option_index)) != EOF ) {    
    switch (c) {
      case 'h':
        fprintf(stderr, "%s", helptext);
        exit(EXIT_SUCCESS);
      case 'V':
        exit(EXIT_SUCCESS);
      case 'd':
        ttydev = strndup(optarg, MAXLEN);
        break;
      case 's':
        baud = atoi(optarg);
        break; 
      case 'p':
        parity_s = strndup(optarg, MAXLEN);
        break;
      case 'f': // run in forground
	run_forground = 1;
	break;
      case '?':
        /* getopt_long already printed an error message. */
      default:
        fprintf(stderr, "%s", helptext);
        exit(EXIT_SUCCESS);
    }
  }

  if(!run_forground){
      fprintf(stderr, "Deamonizing...\n");
      daemon(0, 0);
  }


  /* Setup signalhandler so that we shut down 
     nicely on CTRL+C */
  signal(SIGINT, int_handler);
  
  pidfile = pidfile_create(DEFAULT_PIDFILE, PMODE_RETURN, 0);

  mq_id = create_ipc();


  /* Allocate space for an ADU frame */
  pucFrame = eMBAllocateFrame(&usLen);

  while(outer_loop) {

    if(running == 1) 
      printf("Restarting modbus layer\n");   
    else {
      printf("\n\n\n\n Restarting modbus layer\n\n\n\n");
      running = 1;
      errorcount = 0;
    }

    /* Parse user inputs... */
    if(strcmp(parity_s, "even") == 0)
      parity = MB_PAR_EVEN;
    else if(strcmp(parity_s, "odd") == 0)
      parity = MB_PAR_ODD;
    else
      parity = MB_PAR_NONE;

    PRINT_DBG(1, "init modbus at tty: %s parity %d baud %d", ttydev, parity, baud);

    /* mode, port, baud, parity */
    eMBMasterInit(MB_RTU, ttydev, baud, parity);

    while(running) {

      /* Check message queue */
      if((received = msgrcv(mq_id, &mymsg, sizeof(mymsg.text), 1, IPC_NOWAIT)) > 0) {

        /* Address */
        address = parse_address(mymsg.text);
        /* Starting register */
        reg_start = parse_reg_start(mymsg.text);
        /* Register type */
        regt = parse_reg_type(mymsg.text);
        /* Register action */
        reg_action_param = 0;
        reg_action = parse_reg_action(mymsg.text, &reg_action_param);
        /* Optional: number of registers */
        no_reg = parse_no_reg(mymsg.text);


#ifdef DBG
	if(dbglev>=1){
	    printf("Got: %s\n", mymsg.text);
	    printf("Parsing command:\n");
	    printf("Address: 0x%02x\n", address);
	    printf("Register: %d\n", reg_start);
	    printf("Register type: %d\n", regt);
	    printf("Register action: %d  Arg: %d\n", reg_action, reg_action_param);
	    printf("Register count: %d\n", no_reg);
	}
#endif

        switch(regt) {
          case MB_TYPE_COILS:
            switch(reg_action) {
              case ACTION_READ:
                err = build_eMBMasterReadCoils (pucFrame, reg_start, reg_action_param, &usLen);
                break;
              case ACTION_WRITE:
                err = build_eMBMasterWriteCoils (pucFrame, reg_start, reg_action_param ? 0xff : 0x0, &usLen);
                break;
              case ACTION_WRITEMULTIPLE:
                err = build_eMBMasterWriteMultipleCoils (pucFrame, reg_start, no_reg, reg_action_param ? 0xff : 0x0, &usLen);
                break;
            }
            break;
          case MB_TYPE_INPUT:
            err = build_eMBMasterReadInput (pucFrame, reg_start, reg_action_param, &usLen);
            break;
          case MB_TYPE_HOLDING:
            switch(reg_action) {
              case ACTION_READ:
                err = build_eMBMasterReadHolding (pucFrame, reg_start, reg_action_param, &usLen);
                break;
              case ACTION_WRITE:
                err = build_eMBMasterWriteSingleHolding (pucFrame, reg_start, reg_action_param, &usLen);
                break;
            }
            break;
        }
     
#ifdef DBG
        if(dbglev){
          int n;
          printf("Dumping built frame:\n");
          for(n=0; n<10; n++)
            printf("%02x ",pucFrame[n]);
          printf("\n");            
        }
#endif
      
        /* ? */
        eMBEnable();

        memset(result, 0, sizeof(result));

        if(err == MB_EX_NONE) {
          /* Set the address of the device in question */
          eMBSetSlaveAddress(address);

          /* Send the frame */
          if( (err = eMBSendFrame(pucFrame, usLen)) == MB_ENOERR) {
            printf(" ---- done processing frame ----\n");
            eException = MB_EX_ILLEGAL_FUNCTION;
            ucFuncType = pucFrame[MB_PDU_FUNC_OFF];      

#ifdef DBG
	    if(dbglev){
            printf("%s():%d - after send...\n", __FUNCTION__, __LINE__);
            {
              int n;
              printf("Dumping received frame:\n");
              for(n=0; n<10; n++)
                printf("%02x ",pucFrame[n]);
              printf("\n");            
            }
	    }
#endif
          

            if(ucFuncType & 0x80) {
              UCHAR ucExceptType = pucFrame[MB_PDU_FUNC_OFF+1];
              /* We encountered some sort of error */
              switch(ucExceptType) {
                case MB_EX_ILLEGAL_FUNCTION:
                  fprintf(stderr, "Error! Illegal function!\n");
                  break;
                case MB_EX_ILLEGAL_DATA_ADDRESS:
                  fprintf(stderr, "Error! Illegal data address!\n");
                  break;
                case MB_EX_ILLEGAL_DATA_VALUE:
                  fprintf(stderr, "Error! Illegal data value!\n");
                  break;
                case MB_EX_SLAVE_DEVICE_FAILURE:
                  fprintf(stderr, "Error! Slave device failure!\n");
                  break;
                default:
                  fprintf(stderr, "Unknown error (%d)!\n", eException);
                  break;
              }
            } else {
              switch(ucFuncType) {
                case MB_FUNC_READ_COILS:
                  eException = parse_eMBMasterReadCoils(pucFrame, &usLen, (void *)result);
#ifdef DBG
                  if(dbglev)
		      printf("Reply: %04x\n", result[0]);
#endif
                  break;
                case MB_FUNC_WRITE_SINGLE_COIL:
                  eException = parse_eMBMasterWriteCoils(pucFrame, &usLen, (void *)result);
#ifdef DBG
		  if(dbglev)
		      printf("Reply: %04x\n", result[0]);
#endif
                  break;
                case MB_FUNC_READ_INPUT_REGISTER:
                  eException = parse_eMBMasterReadInput(pucFrame, &usLen, (void *)result);
#ifdef DBG
		  if(dbglev)
		      printf("Reply (%d): %04x\n", eException, result[0]);
#endif
                  break;
                case MB_FUNC_READ_HOLDING_REGISTER:
                  eException = parse_eMBMasterReadHolding(pucFrame, &usLen, (void *)result);
		  
		 
		  
#ifdef DBG
                  printf("Reply: %04x %04x %d %d\n", result[0],result[1], result_int, reg_action_param);
#endif
                  break;
                case MB_FUNC_WRITE_REGISTER:
                  eException = parse_eMBMasterWriteSingleHolding(pucFrame, &usLen, (void *)result);
#ifdef DBG
                  printf("Reply: %04x\n", result[0]);
#endif
                  break;
                case MB_FUNC_WRITE_MULTIPLE_COILS:
                  usLen = 5;
                  eException =  parse_eMBMasterWriteMultipleCoils(pucFrame, &usLen, (void *)result);
                  if(eException == MB_EX_NONE)
                    printf("Write multiple coils SUCCESS!\n");
                  else
                    printf("Write multiple coils FAIL!\n");
                  break;
                default:
                  printf("Unknown function type : %x\n", ucFuncType);
                  printf("%d : %s()\n", __LINE__, __FUNCTION__);
                  {
                    int n;
                    for(n=0; n<10; n++)
                      printf("%02x ",pucFrame[n]);
                    printf("\n");            
                  }
                  break;
              }
	      switch(ucFuncType) {
		case MB_FUNC_READ_HOLDING_REGISTER:
		case MB_FUNC_READ_INPUT_REGISTER:
		   if(reg_action_param == 2){
		      printf("!!!!\n");
		      result_int = (result[0]<<16) | result[1];
		  }else {
		      result_int = result[0];
		  }
		  break;
		default:
		  result_int = result[0];
		  break;
	      }
              if(eException == MB_EX_NONE) {
		  snprintf(mymsg.text, sizeof(mymsg.text), "%ld:REG:%d:RESULT:%d",  time(NULL), reg_start, result_int);
              } else {
                snprintf(mymsg.text, sizeof(mymsg.text), "ERROR:Parsing frame");
              }
#ifdef DBG
              printf("%s():%d - reply: %s\n",
                     __FUNCTION__, __LINE__, mymsg.text);
#endif
              goto out;

            }
          } else {
            printf("Error sending frame. (%d)\n", err);
            snprintf(mymsg.text, sizeof(mymsg.text), "ERROR:Sending frame");
            if(errorcount > 10)
              running = 0;
            else
              errorcount++;
          }
        } else {
          printf("Error in frame arguments.\n");
          snprintf(mymsg.text, sizeof(mymsg.text), "ERROR:Wrong argument");
        }
      out:
        /* Set the reply */
        mymsg.type = 2;
#ifdef DBG
        printf("%s():%d - reply: %s\n",
               __FUNCTION__, __LINE__, mymsg.text);
#endif
        msgsnd(mq_id, &mymsg, sizeof(mymsg.text), IPC_NOWAIT);

        eMBDisable();
      } else {
        //printf("No messages. Sleeping (%d - %s)\n", received, received < 0 ? strerror(errno) :  "");
      } 
      usleep(1000);
    }
    //    free(pucFrame);
    eMBClose();
  }

  destroy_ipc(PROJ_ID);

  pidfile_delete(pidfile);

  return 0;
}
Example #23
0
/* Private function ----------------------------------------------------------*/
int main(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    uint8_t cnt=0;
    
    /* Set the Vector Table base adress at 0x8004000 */
    NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x4000);    
    
    /* LED0 -> PB0     LED1 -> PB1  */
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; 
    GPIO_Init(GPIOB, &GPIO_InitStructure);	
    
    // Initialize protocol stack in RTU mode for a slave with address 10 = 0x0A
	  // MB_RTU, Device ID: 1, USART portL: 1 (este configurat in portserial.h, Baud rate: 38400, Parity: NONE)
    eMBInit(MB_RTU, 1, 1, 38400, MB_PAR_NONE);
	  // Enable the Modbus Protocol Stack.
    eMBEnable();								

    while(1)
    {
        // Reset the flag. It will only be set if the modbus pooling has a request
		Modbus_Request_Flag = 0;
  		// Call the main polling loop of the Modbus protocol stack.
        eMBPoll();				        
  		if (Modbus_Request_Flag) GPIO_SetBits(GPIOB , GPIO_Pin_0);
		Delay(0xffff);
		if (Modbus_Request_Flag) GPIO_ResetBits(GPIOB , GPIO_Pin_0);
        
        
        cnt++;

        if (cnt == 4) \
        {            
            writeInputRegister(1, 111);
            writeInputRegister(2, 222);
            writeInputRegister(98, 111);
            writeInputRegister(99, 222);
                        
            writeHoldingRegister(1, 333);
            writeHoldingRegister(2, 444);
            writeHoldingRegister(98, 333);
            writeHoldingRegister(99, 444);
            
            writeCoil(1, 0);           
            writeCoil(2, 1);                       
            writeCoil(58, 1);
            writeCoil(59, 0);
        }
        
        if (cnt == 8) 
        {                      
            writeInputRegister(1, 222);
            writeInputRegister(2, 111);
            writeInputRegister(98, 222);
            writeInputRegister(99, 111);
                        
            writeHoldingRegister(1, 444);
            writeHoldingRegister(2, 333);
            writeHoldingRegister(98, 444);
            writeHoldingRegister(99, 333);
            
            writeCoil(1, 1);           
            writeCoil(2, 0);                       
            writeCoil(58, 0);
            writeCoil(59, 1);            
            
            cnt = 0;
        }
        
        
								   
    }
}
int main(void)
{
	/*Ждем пока все включится*/
	_delay_ms(100);
	
	/*Настраиваем порты ввода-вывода*/
	DDRB = 1<<PORTB0|1<<PORTB1|1<<PORTB2|1<<PORTB3|1<<PORTB4|1<<PORTB5|1<<PORTB6|1<<PORTB7;
	DDRC = 1<<PORTC0|1<<PORTC1|1<<PORTC2|0<<PORTC3|0<<PORTC4|0<<PORTC5|0<<PORTC6|0<<PORTC7;
	DDRD = 0<<PORTD0|0<<PORTD1|0<<PORTD2|0<<PORTD3|1<<PORTD4|0<<PORTD5|0<<PORTD6|1<<PORTD7;

	PORTB = 1;
	PORTD = 1 << PORTD2;
    
	/*Тяга двигателей на минимум*/
    for(uint8_t k = 0; k < CHANNELS_COUNT; ++k)
    {
        counter[k] = LOW;
    }
	
	/*Настраиваем I2C*/
	TWSR = 0x00;
	TWBR = ((F_CPU / I2C_SPEED) - 16) / 2;  
	_delay_us(10);

	/*Включаем Таймер0*/
	TCCR0 = 1<<CS02 | 0<<CS01 | 0<<CS00;
	
	/*Включаем Таймер1*/
	OCR1A=HIGH; //TOP
	TCCR1A=0<<COM1A1|0<<COM1A0|1<<COM1B1|0<<COM1B0|0<<FOC1A|0<<FOC1B|1<<WGM11|1<<WGM10;
	TCCR1B=0<<ICNC1|0<<ICES1|1<<WGM13|1<<WGM12|0<<CS12|0<<CS11|1<<CS10;
	TIMSK= 1<<TOIE2 | 1<<OCIE1A|1<<OCIE1B|0<<TOIE1|1<<TOIE0|0<<OCIE0;
	OCR1B=LOW;
	
	/*Включаем АЦП*/
	ADC_Init();   
    
	/*Включаем прерывание INT0(высотомер)*/
	INT0_Init();
	
	/*Разрешаем работу прерываний*/
	sei();
	
	/*Настраиваем Modbus*/
	eMBErrorCode eStatus = eMBInit( MB_RTU, 0x01, 0, 57600, MB_PAR_NONE );
	eStatus = eMBEnable();
    
	/*Настраиваем сенсоры*/    
	SensorsInit();
	
	/*Загружаем в Holding Registers и в массив параметров значения из EEPROM*/
	ModbusInitValues();
	
	filterInit();	
		
	while(1)
	{
		/*Актуализируем значения Modbus-регистров в соответствии со значениями параметров*/
		ModbusLoader();
		/*Актуализируем значения параметров в соответствии со значениями Holding Registers*/
		ModbusSaver();
		
		/*Итерация Modbus*/
		eMBPoll();
		
		/*Ресурсоемкий расчет курса*/		
		Course_Calc();
	}
}
Example #25
0
static void setupHardware(void) {
	// TODO: Put hardware configuration and initialisation in here
	SystemInit();

	resetGPIO();

	setInput_P2();

	ADCInit(ADC_CLK);

	//resetto il termometro
	pinMode(OUTPUT);
	digitalWrite(HIGH);

	Initial_Hardware();	//init lcd hardware

	Initial_GLCD_Hor();	//init lcd "software"

	bg_color(BLACK);


	int sto_premendo = 0;

	eMBErrorCode    eStatus;

	eStatus = eMBInit( MB_RTU, 0x0A, 0, 38400, MB_PAR_NONE );

	/* Initialize the holding register values before starting the
	 * Modbus stack
	 */
	int i;

	for( i = 0; i < REG_HOLDING_NREGS; i++ )
	{
		usRegHoldingBuf[i] = 0;
	}

	sensors.distance1 = 1;
	sensors.distance2 = 2;
	sensors.lumino = 3;
	sensors.mic = 4;
	sensors.vibro = 5;
	actual_DHT11.humidity = 666;
	actual_DHT11.temperature = 666;

	//associo ai registri holding il valore dei sensori
	*(usRegHoldingBuf     ) = (USHORT *) &sensors.distance1;
	*(usRegHoldingBuf + 1 ) = (USHORT *) &sensors.distance2;
	*(usRegHoldingBuf + 2 ) = (USHORT *) &sensors.lumino;
	*(usRegHoldingBuf + 3 ) = (USHORT *) &sensors.mic;
	*(usRegHoldingBuf + 4 ) = (USHORT *) &sensors.vibro;
	*(usRegHoldingBuf + 5 ) = (USHORT *) &actual_DHT11.humidity;
	*(usRegHoldingBuf + 6 ) = (USHORT *) &actual_DHT11.temperature;


	/* Enable the Modbus Protocol Stack. */
	eStatus = eMBEnable(  );


	// Warning: If you do not initialize the hardware clock, the timings will be inaccurate
}
Example #26
0
int main( int argc, char *argv[] )
{
  int c;
  int option_index = 0;

  char *ttydev = DEFAULT_TTY;
  char *parity_s = DEFAULT_PAR;
  int parity;
  int baud = DEFAULT_BAUD;
  int reg_start = DEFAULT_REGISTER_START;
  int address = DEFAULT_ADDRESS;
  char *reg_type = NULL;
  int regt = -1;
  char *reg_action = NULL;

  USHORT usLen;
  UCHAR *pucFrame;
  eMBErrorCode err = MB_ENOERR;

  /* Parse cmd-line options */
  while ( (c = getopt_long (argc, argv, "hVd:s:p:r:t:c:a:", long_options, &option_index)) != EOF ) {    
    switch (c) {
      case 'h':
        fprintf(stderr, "%s", helptext);
        exit(EXIT_SUCCESS);
      case 'V':
        exit(EXIT_SUCCESS);
      case 'd':
        ttydev = strndup(optarg, MAXLEN);
        break;
      case 's':
        baud = atoi(optarg);
        break; 
      case 'p':
        parity_s = strndup(optarg, MAXLEN);
        break;
      case 'r':
        reg_start = (int)strtod(optarg, NULL);
        break;
      case 't':
        reg_type = strndup(optarg, MAXLEN);
        break;
      case 'c':
        reg_action = strndup(optarg, MAXLEN);
        break; 
      case 'a':
        address = (int)strtod(optarg, NULL);
        break;
      case '?':
        /* getopt_long already printed an error message. */
      default:
        fprintf(stderr, "%s", helptext);
        exit(EXIT_SUCCESS);
    }
  }

  if(argc <= 1) {
    fprintf(stderr, "%s", helptext);
    exit(EXIT_FAILURE);
  }


  /* Allocate space for an ADU frame */
  pucFrame = eMBAllocateFrame(&usLen);

  /* Parse user inputs... */
  if(strcmp(parity_s, "even") == 0)
    parity = MB_PAR_EVEN;
  else if(strcmp(parity_s, "odd") == 0)
    parity = MB_PAR_ODD;
  else
    parity = MB_PAR_NONE;

  if(reg_start < 0 ||  reg_start > 0xffff) {
    fprintf(stderr, "Error! Modbus register out of range. Must be within (0x0-0xffff)\n");
    exit(EXIT_FAILURE);
  }

  if(reg_type) {
    if(strcmp(reg_type, "coils" ) == 0) {
      regt = MB_TYPE_COILS;
    } else if(strcmp(reg_type, "input" ) == 0) {
      regt = MB_TYPE_INPUT;
    } else if(strcmp(reg_type, "holding" ) == 0) {
      regt = MB_TYPE_HOLDING;
    } else if(strcmp(reg_type, "slaveid" ) == 0) {
      regt = MB_TYPE_SLAVEID;
      build_eMBMasterGetSlaveID (pucFrame, &usLen);
    } else {
      fprintf(stderr, "Error! Unknown register type (%s). Known types are: coils\n", reg_type);
      exit(EXIT_FAILURE);
    }
  } else {
    fprintf(stderr, "Error! No register type (-t) specified\n");
    exit(EXIT_FAILURE);
  }

  if(reg_action) {
    if(regt == MB_TYPE_COILS) {
      if(strncmp(reg_action, "read", 4) == 0) {
        int val;
        if(sscanf(reg_action, "%*s %i", &val) != 1) {
          fprintf(stderr, "Error! No number of coils specified.\n");
          exit(EXIT_FAILURE); 
        }
        if(val%8 == 0) {
          build_eMBMasterReadCoils (pucFrame, reg_start, val, &usLen);
        } else {
          fprintf(stderr, "Error! Invalid coil value (%d). Must be a multiple of 8.\n", val);
          exit(EXIT_FAILURE);
        }
      } else if(strncmp(reg_action, "writesingle", 11) == 0) {
        char buf[4];
        if(sscanf(reg_action, "%*s %3[FNO]", buf) != 1) {
          fprintf(stderr, "Error! No coil value specified (ON/OFF).\n");
          exit(EXIT_FAILURE); 
        }
        if(strcmp(buf, "ON") == 0)
          build_eMBMasterWriteCoils (pucFrame, reg_start, 0xff, &usLen);
        else
          build_eMBMasterWriteCoils (pucFrame, reg_start, 0x0, &usLen);
      } else if(strncmp(reg_action, "writemultiple", 13) == 0) {
        int no;
        char buf[4];
        if( sscanf(reg_action, "%*s %i %3[FNO]", &no, buf) != 2) {
          fprintf(stderr, "Error! Invalid value specified.\n");
          exit(EXIT_FAILURE); 
        }
        if(strcmp(buf, "ON") == 0)
          build_eMBMasterWriteMultipleCoils (pucFrame, reg_start, no, 0xff, &usLen);
        else
          build_eMBMasterWriteMultipleCoils (pucFrame, reg_start, no, 0x0, &usLen);
      } else {
        fprintf(stderr, "Error! Unknown command type (%s).\n", reg_action);
        exit(EXIT_FAILURE); 
      }
      
    } else if(regt == MB_TYPE_INPUT) {
      if(strncmp(reg_action, "read", 4) == 0) {
        int val;
        
        if(sscanf(reg_action, "%*s %i", &val) != 1) {
          fprintf(stderr, "Error! No number of registers specified.\n");
          exit(EXIT_FAILURE); 
        }
        if(build_eMBMasterReadInput (pucFrame, reg_start, val, &usLen) != MB_ENOERR) {
          fprintf(stderr, "Error! Wrong register count. Must be between 1 and 125 (0x7d)\n");
            exit(EXIT_FAILURE); 
        }
      }
    } else if(regt == MB_TYPE_HOLDING) {
      if(strncmp(reg_action, "read", 4) == 0) {
        int val;
        
        if(sscanf(reg_action, "%*s %i", &val) != 1) {
          fprintf(stderr, "Error! No number of registers specified.\n");
          exit(EXIT_FAILURE); 
        }
        if(build_eMBMasterReadHolding (pucFrame, reg_start, val, &usLen) != MB_ENOERR) {
          fprintf(stderr, "Error! Wrong register count. Must be between 1 and 125 (0x7d)\n");
          exit(EXIT_FAILURE); 
        }
        printf("%s():%d -  build_eMBMasterReadHolding(pucFramem, %d, %d, %d)\n", 
               __FUNCTION__, __LINE__,
               reg_start, val, usLen);
      } else if(strncmp(reg_action, "writesingle", 11) == 0) {
        int val;
        if( sscanf(reg_action, "%*s %i", &val) != 1) {
          fprintf(stderr, "Error! Invalid value specified.\n");
          exit(EXIT_FAILURE); 
        }
        if(build_eMBMasterWriteSingleHolding (pucFrame, reg_start, val, &usLen) != MB_ENOERR) {
          fprintf(stderr, "Error!\n");
          exit(EXIT_FAILURE); 
        }
      }
    }
  } else {
    fprintf(stderr, "Error! No command (-c) specified.\n");
    exit(EXIT_FAILURE); 
  }

  /* mode, port, baud, parity */
  eMBMasterInit(MB_RTU, ttydev, baud, parity);

  /* ? */
  eMBEnable();
  
  /* Set the address of the device in question */
  eMBSetSlaveAddress(address);
  
  /* Send the frame */
  if( (err = eMBSendFrame(pucFrame, usLen)) != MB_ENOERR) {
    printf("Error sending frame (%d).\n", err);
    exit(EXIT_FAILURE);
  }

  eMBException    eException;
  eException = MB_EX_ILLEGAL_FUNCTION;
  UCHAR ucFuncType = pucFrame[MB_PDU_FUNC_OFF];
  
  USHORT retval[255];

  if(ucFuncType & 0x80) {
    UCHAR ucExceptType = pucFrame[MB_PDU_FUNC_OFF+1];
    /* We encountered some sort of error */
    switch(ucExceptType) {
      case MB_EX_ILLEGAL_FUNCTION:
        fprintf(stderr, "Error! Illegal function!\n");
        break;
      case MB_EX_ILLEGAL_DATA_ADDRESS:
        fprintf(stderr, "Error! Illegal data address!\n");
        break;
      case MB_EX_ILLEGAL_DATA_VALUE:
        fprintf(stderr, "Error! Illegal data value!\n");
        break;
      case MB_EX_SLAVE_DEVICE_FAILURE:
        fprintf(stderr, "Error! Slave device failure!\n");
        break;
      default:
        fprintf(stderr, "Unknown error (%d)!\n", eException);
        break;
    }
  } else {
    switch(ucFuncType) {
      case MB_FUNC_READ_COILS:
        eException = parse_eMBMasterReadCoils(pucFrame, &usLen, (void *)retval);
        printf("Reply: %04x\n", retval[0]);
        break;
     case MB_FUNC_WRITE_SINGLE_COIL:
        eException = parse_eMBMasterWriteCoils(pucFrame, &usLen, (void *)retval);
        printf("Reply: %04x\n", retval[0]);
        break;
      case MB_FUNC_READ_INPUT_REGISTER:
        eException = parse_eMBMasterReadInput(pucFrame, &usLen, (void *)retval);
        printf("Reply (%d): %04x\n", eException, retval[0]);
        break;
      case MB_FUNC_READ_HOLDING_REGISTER:
        eException = parse_eMBMasterReadHolding(pucFrame, &usLen, (void *)retval);
        printf("Reply: %04x\n", retval[0]);
        break;
      case MB_FUNC_WRITE_REGISTER:
        eException = parse_eMBMasterWriteSingleHolding(pucFrame, &usLen, (void *)retval);
        printf("Reply: %04x\n", retval[0]);
        break;
      case MB_FUNC_WRITE_MULTIPLE_COILS:
        usLen = 5;
        eException =  parse_eMBMasterWriteMultipleCoils(pucFrame, &usLen, (void *)retval);
        if(eException == MB_EX_NONE)
          printf("Write multiple coils SUCCESS!\n");
        else
          printf("Write multiple coils FAIL!\n");
        break;

      default:
        printf("Unknown function type : %x\n", ucFuncType);
        printf("%d : %s()\n", __LINE__, __FUNCTION__);
        {
         
          int n;
          for(n=0; n<10; n++)
            printf("%02x ",pucFrame[n]);
          printf("\n");            
         
        }
        break;
    }
  }
    
#ifdef DBG
  printf("%d : %s()\n", __LINE__, __FUNCTION__);
  {
    int j;
    for(j=0; j<usLen; j++)
      printf("%02x ", pucFrame[j]); 
    printf("\n");
  }
#endif

  eMBClose();
  
  return 0;
}
Example #27
0
int main(void)
{
    systemInit();

    TIM_Cmd(TIM3, ENABLE);
    //启动FreeModbus
    eMBEnable();
    while(1)
    {
        //FreeModbus不断查询
        eMBPoll();
        //Botton_Control();

        //本地按键控制查询
        bottonValue=Botton_Scan(1);
        if(bottonValue)
        {
            bottonPressed=True;
            switch(bottonValue)
            {
            case BottonUp:
                bollardControlType=Control_Bollard_Up;
                break;
            case BottonDown:
                bollardControlType=Control_Bollard_Down;
                break;
            case BottonStop:
                bollardControlType=Control_Bollard_Stop;
                break;
            }
        }

        //限位到达查询
        limitValuePre=limitValue;
        limitValue=Limit_Scan();
        if((limitValue)&&(limitValue!=limitValuePre))
        {
            limitReach=True;
        }

        //升降柱状态查询
        bollardStatusPre=bollardStatus;
        bollardStatus=Bollard_Status_Scan();
        if(bollardStatus!=bollardStatusPre)
        {
            statusChange=True;
        }

        if(synchroOnOff==1)
        {
            //级联输入查询
            cascadeConnectionPre=cascadeConnection;
            cascadeConnection=Cascade_Connection_Scan();
            if(cascadeConnection&&(cascadeConnection!=cascadeConnectionPre))
            {
                cascadeConnectionAft=cascadeConnection;
                cascadeChange=True;
            }
        }

        if(groundCoilOnOff==1)
        {
            groundCoilStatus=Ground_Coil_Scan();
            if((bollardStatus!=Emergency) && groundCoilStatus && controlOn && (BollardControlUp==ControlEnable))
            {
                BollardControlUp=ControlDisable;
                controlOn=0;
                TIM_Cmd(TIM2,DISABLE);
                TIM_SetCounter(TIM2,0);//
                //event save

            }
        }

    }
}
Example #28
0
void
main( void )
{
    eMBErrorCode    eStatus;

    /* Use external 32.768 Hz crystal to generate 4.194.304 Hz bus clock */
    ICGC1 = 0x38;               // ??=0,RANGE=0,REFS=1,CLKS=1:1,OSCSTEN=0,??=0:0
    while( ICGS2_DCOS == 0 );

#if 0
    /* Test code for porting
     */
#if 1
    /* Timer test
     * Comment out call to pxMBPortCBTimerExpired() in prvvTIMERExpiredISR when testing the timer
     */

    /* Disable the COP watchdog */
    SOPT = 0x53;                // COPE=0,COPT=1,STOPE=0,??=1:0:0,BKGDPE=1,??=1

    ( void )xMBPortTimersInit( 20000 );

    EnableInterrupts;
    for( ;; )
    {
        vMBPortTimersEnable(  );
        _Wait;                  // wait for an interrupt

        /* toggle LED1 */
        PTFD_PTFD0 = !PTFD_PTFD0;
        PTFDD_PTFDD0 = 1;
    }

#else
    /* Receiver test
     * Comment out call to pxMBFrameCBByteReceived() in prvvUARTRxISR() when testing the receiver
     */

    /* Disable the COP watchdog */
    SOPT = 0x53;                // COPE=0,COPT=1,STOPE=0,??=1:0:0,BKGDPE=1,??=1

    /* Enable the receiver. */
    assert( xMBPortSerialInit( 0, 9600, 8, MB_PAR_NONE ) );

    EnableInterrupts;
    for( ;; )
    {
        UCHAR           ucByte;

        vMBPortSerialEnable( TRUE, FALSE );
        _Wait;                  // wait for an interrupt
        assert( xMBPortSerialGetByte( &ucByte ) );

        /* toggle LED1 */
        PTFD_PTFD0 = !PTFD_PTFD0;
        PTFDD_PTFDD0 = 1;

        /* Transmitter test
         * Comment out call to pxMBFrameCBTransmitterEmpty() in prvvUARTTxReadyISR() when testing the transmitter
         */
#if 0
        vMBPortSerialEnable( FALSE, TRUE );
        assert( xMBPortSerialPutByte( ucByte ) );
        _Wait;                  // wait for an interrupt

        /* toggle LED1 */
        PTFD_PTFD0 = !PTFD_PTFD0;
#endif // Transmitter test
    }
#endif // Receiver test

#else
    /* Demo
     * NOTE: Make sure the callbacks in the three ISPs have been restored after above testing
     */

    /* Initialization */
    eStatus = eMBInit( MB_RTU, 0x0A, 0, 38400, MB_PAR_EVEN );
//      eStatus = eMBInit( MB_ASCII, 0x0A, 0, 38400, MB_PAR_EVEN );

    /* Enable the Modbus Protocol Stack. */
    eStatus = eMBEnable(  );

    /* Start polling */
    EnableInterrupts;
    for( ;; )
    {
        /* Poll for Modbus events */
        ( void )eMBPoll(  );

        /* Count the number of polls */
        usRegInputBuf[0]++;

        /* Count the number of timer overflows */
        if( TPM1SC_TOF )
        {
            TPM1SC_TOF = 0;
            ENTER_CRITICAL_SECTION(  );
            if( ++usRegInputBuf[1] == 0 )       // Happens every 2 seconds
                usRegInputBuf[2]++;     // Happens every 36.4 hours
            EXIT_CRITICAL_SECTION(  );
        }

        /* Keep the COP watchdog happy */
        __RESET_WATCHDOG(  );
    }
#endif // Test code when porting
}
static inline int modbus_initialize(void)
{
  eMBErrorCode mberr;
  int status;

  /* Verify that we are in the stopped state */

  if (g_modbus.threadstate != STOPPED)
    {
      fprintf(stderr, "modbus_main: "
              "ERROR: Bad state: %d\n", g_modbus.threadstate);
      return EINVAL;
    }

  /* Initialize the ModBus demo data structures */

  status = pthread_mutex_init(&g_modbus.lock, NULL);
  if (status != 0)
    {
      fprintf(stderr, "modbus_main: "
              "ERROR: pthread_mutex_init failed: %d\n",  status);
      return status;
    }

  status = ENODEV;

  /* Initialize the FreeModBus library.
   *
   * MB_RTU                        = RTU mode
   * 0x0a                          = Slave address
   * CONFIG_EXAMPLES_MODBUS_PORT   = port, default=0 (i.e., /dev/ttyS0)
   * CONFIG_EXAMPLES_MODBUS_BAUD   = baud, default=B38400
   * CONFIG_EXAMPLES_MODBUS_PARITY = parity, default=MB_PAR_EVEN
   */

  mberr = eMBInit(MB_RTU, 0x0a, CONFIG_EXAMPLES_MODBUS_PORT,
                  CONFIG_EXAMPLES_MODBUS_BAUD, CONFIG_EXAMPLES_MODBUS_PARITY);
  if (mberr != MB_ENOERR)
    {
      fprintf(stderr, "modbus_main: "
              "ERROR: eMBInit failed: %d\n", mberr);
      goto errout_with_mutex;
    }

  /* Set the slave ID
   *
   * 0x34        = Slave ID
   * true        = Is running (run indicator status = 0xff)
   * g_slaveid   = Additional values to be returned with the slave ID
   * 3           = Length of additional values (in bytes)
   */

  mberr = eMBSetSlaveID(0x34, true, g_slaveid, 3);
  if (mberr != MB_ENOERR)
    {
      fprintf(stderr, "modbus_main: "
              "ERROR: eMBSetSlaveID failed: %d\n", mberr);
      goto errout_with_modbus;
    }

  /* Enable FreeModBus */

  mberr = eMBEnable();
  if (mberr != MB_ENOERR)
    {
      fprintf(stderr, "modbus_main: "
              "ERROR: eMBEnable failed: %d\n", mberr);
      goto errout_with_modbus;
    }

  /* Successfully initialized */

  g_modbus.threadstate = RUNNING;
  return OK;

errout_with_modbus:
  /* Release hardware resources. */

  (void)eMBClose();

errout_with_mutex:

  /* Free/uninitialize data structures */

  (void)pthread_mutex_destroy(&g_modbus.lock);

  g_modbus.threadstate = STOPPED;
  return status;
}