Exemple #1
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]++;
    }
}
Exemple #2
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;
}
Exemple #4
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);
}
Exemple #5
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]++;
    }
}
void Protocol_Init(void)
{
	eMBErrorCode    eStatus;

	RS485SerialContextInit(&stContext_RS485);
	RS485TimerContextInit(&stContext_RS485);

	RS232SerialContextInit(&stContext_RS232);
	RS232TimerContextInit(&stContext_RS232);

	USB_CDC_SerialContextInit(&stContext_USB_CDC);
	USB_CDC_TimerContextInit(&stContext_USB_CDC);

	eStatus = eMBInit(&stContext_RS485, MB_RTU, MODBUS_RS485_DEV_ADDR, 0, MODBUS_BAUDRATE, 0 );
	eStatus = eMBInit(&stContext_RS232, MB_RTU, MODBUS_RS232_DEV_ADDR, 0, MODBUS_BAUDRATE, 0 );
	eStatus = eMBInit(&stContext_USB_CDC, MB_RTU, MODBUS_USB_DEV_ADDR, 0, MODBUS_BAUDRATE, 0 );

	xTaskCreate(Modbus_RS485_Task,(signed char*)"Modbus RS485",MODBUS_TASK_STACK_SIZE,NULL, tskIDLE_PRIORITY + 1, NULL);
	xTaskCreate(Modbus_RS232_Task,(signed char*)"Modbus RS232",MODBUS_TASK_STACK_SIZE,NULL, tskIDLE_PRIORITY + 1, NULL);
	xTaskCreate(Modbus_USB_CDC_Task,(signed char*)"Modbus USB",MODBUS_TASK_STACK_SIZE,NULL, tskIDLE_PRIORITY + 1, NULL);
}
Exemple #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(  );
    }
}
Exemple #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(  );
    }
}
Exemple #9
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]++;
  }
}
Exemple #11
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]++;
    }
}
Exemple #12
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;
}
Exemple #13
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 );
    }
}
Exemple #14
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;
    }      
    }
    
  }
}
Exemple #15
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]++;
    }
}
Exemple #16
0
/* ----------------------- 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;
    }
}
Exemple #17
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]++;
    }
}
Exemple #18
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(  );
    }
}
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();
	}
}
Exemple #20
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
}
Exemple #21
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
}
Exemple #22
0
/**
 * Main entry point for Program Utility.
 *
 * Process option flags and execute commands.
 *
 * @param argc
 * @param argv
 * @return
 */
int
main( int argc, char *argv[] )
{
    int     iExitCode = EXIT_SUCCESS;
    UCHAR   ucMBAddr = 1;
    ULONG   ulOptFlags = 0;
    UCHAR   ucBank = 0;
    UCHAR   ucStartThread = FALSE;
    CHAR   *pucVersion;
    UCHAR  ucStatus;

    int     c;
    int     timeout;
    char   *infile = NULL;
    char   *outfile = NULL;
    char   *endptr;
    opterr = 0;
    ucPort = 2; /* Default to first USB serial dongle */
    printf("Secure Bootloader Program Utility\n\n");
    /*
     * Process command line options
     */
    while ((c = getopt(argc, argv, "a:b:ce:fklp:s:uvDV")) != -1)
    {
        switch (c)
        {
        case 'a':
            ulOptFlags |= FLAG_ADD_HEADER;
            pucVersion = optarg;
            break;
        case 'b':
            ucBank = strtoul(optarg, NULL, 0);
            break;
        case 'c':
            ulOptFlags |= FLAG_CHECK_HEADER;
            break;
        case 'e':
            ulOptFlags |= FLAG_ENCRYPT;
            pBlowfishKeyString = optarg;
            break;
        case 'f':
            ulOptFlags |= FLAG_LOCK_FILE;
            ucBank = BANK_F;
            ucStartThread = TRUE;
            break;
        case 'k':
            ulOptFlags |= FLAG_CREATE_KEYFILE;
            break;
        case 'l':
            ulOptFlags |= FLAG_LOCK_FILE;
            ucBank = BANK_BOOT;
            ucStartThread = TRUE;
            break;
        case 'p':
            ucPort = strtoul(optarg, &endptr, 0);
            /* If argument is not a pure number, it must be a string */
            if (endptr)
            {
            	ucPort = 255;
            	devString = optarg;
            }
            break;
        case 's':
            ulOptFlags |= FLAG_SIGN;
            pRSAKeyFile = optarg;
            break;
        case 'u':
            ulOptFlags |= FLAG_UPLOAD;
            ucStartThread = TRUE;
            break;
        case 'v':
            ulOptFlags |= FLAG_GET_VERSION;
            ucStartThread = TRUE;
            break;
        case 'D':
            debugflags = 1;
            break;
        case 'V':
            ulOptFlags |= FLAG_VALIDATE;
            ucStartThread = TRUE;
            break;
        case '?':
            if (optopt == 'v')
                fprintf(stderr, "Option -%c requires an argument.\n", optopt);
            else if (isprint(optopt))
                fprintf(stderr, "Unknown option `-%c'.\n", optopt);
            else
                fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt);
            return 1;
        default:
            abort();
            break;
        }
    }
    if (optind < argc)
    {
        infile = argv[optind++];
    }
    if (optind < argc)
    {
        outfile = argv[optind++];
    }

    if (argc < 2)
    {
        print_usage();
    }

    if ((ulOptFlags & FLAG_ADD_HEADER) && (ulOptFlags & FLAG_CREATE_KEYFILE))
    {
        printf("Error: cannot specify both -a and -k options\n");
        abort();
    }
    if ((ulOptFlags & FLAG_CREATE_KEYFILE) && (infile == 0))
    {
        /* Request to upload keyfile */
        ucStartThread = TRUE;
    }

    /*
     * Enable signal handlers
     */
    if( !bSetSignal( SIGQUIT, vSigShutdown ) ||
        !bSetSignal( SIGINT, vSigShutdown ) || !bSetSignal( SIGTERM, vSigShutdown ) )
    {
        fprintf( stderr, "%s: can't install signal handlers: %s!\n", PROG, strerror( errno ) );
        iExitCode = EXIT_FAILURE;
    }
    else if (ucStartThread)
    {
        DEBUG_PUTSTRING("Starting MobBus thread");
        if( eMBInit( MB_RTU, 0x0A, ucPort, 115200, MB_PAR_EVEN ) != MB_ENOERR )
        {
            fprintf( stderr, "%s: can't initialize modbus stack!\n", PROG );
            iExitCode = EXIT_FAILURE;
        }
        else
        {
            /* Register Callbacks */
            (void)eMBRegisterCB(MB_FUNC_BOOT_GETHEADER, cmd_getheader_callback);
            (void)eMBRegisterCB(MB_FUNC_BOOT_PREPAREFLASH, cmd_prepareflash_callback);
            (void)eMBRegisterCB(MB_FUNC_BOOT_UPLOADBLOCK, cmd_uploadblock_callback);
            (void)eMBRegisterCB(MB_FUNC_BOOT_VALIDATEIMAGE, cmd_validatesig_callback);
            (void)eMBRegisterCB(MB_FUNC_BOOT_SETKEYS, cmd_setkeys_callback);
            (void)eMBRegisterCB(MB_FUNC_BOOT_LOCK, cmd_lockfile_callback);
            (void)eMBRegisterIllegalFuncCB(cmd_illegalfunc_callback);

            (void)eMBRegisterTimeoutCB( cmd_timeout_callback );

            /* Start polling thread */
            vSetPollingThreadState(STOPPED);

            if (bCreatePollingThread() != TRUE)
            {
                printf("Can't start protocol stack! Already running?\n");
            }
            //vMBPortTimersEnable(  );

        }
    }
    if (iExitCode == EXIT_SUCCESS)
    {
        vSetPollingThreadState(RUNNING);

        /* Process commands and options */
        if (ulOptFlags & FLAG_GET_VERSION)
        {
            timeout = 10;
            ucStatus = cmd_getheader(ucMBAddr, ucBank);
            while ((ucStatus == BOOT_TIMEOUT)
                    && (--timeout))
            {
                ucStatus = cmd_getheader(ucMBAddr, ucBank);
            }
            if ((ucStatus != BOOT_OK) && (ucStatus != BOOT_BANKEMPTY))
            {
                fprintf(stderr, "Get Version Failed: %s", cmd_errorString(ucStatus));
            }

        }
        else if (ulOptFlags & FLAG_UPLOAD)
        {
            if (infile)
            {
                util_upload(ucMBAddr, infile, ucBank);
            }
            else
            {
                fprintf(stderr, "Upload: missing filename\n");
            }
        }
        else if (ulOptFlags & FLAG_ADD_HEADER)
        {
            if (infile && outfile)
            {
                util_addheader(infile, outfile, pucVersion, pRSAKeyFile, pBlowfishKeyString);
            }
            else
            {
                fprintf(stderr, "Add Header: missing filenames\n");
            }
        }
        else if (ulOptFlags & FLAG_CREATE_KEYFILE)
        {
            util_createkeyfile(ucMBAddr, infile, pRSAKeyFile, pBlowfishKeyString);
        }
        else if (ulOptFlags & FLAG_LOCK_FILE)
        {
            timeout = 10;
            ucStatus = cmd_lockfile(ucMBAddr, ucBank);
            while ((ucStatus == BOOT_TIMEOUT)
                    && (--timeout))
            {
                ucStatus = cmd_lockfile(ucMBAddr, ucBank);
            }
            if (ucStatus != BOOT_OK)
            {
                fprintf(stderr, "Lock Failed: %s", cmd_errorString(ucStatus));
            }
            else
            {
                printf("Lock Successful\n");
            }

        }
        if (ulOptFlags & FLAG_CHECK_HEADER)
        {
            if (infile)
            {
                util_checkheader(infile);
            }
            else
            {
                fprintf(stderr, "Check Header: missing filename\n");
            }
        }
        if (ulOptFlags & FLAG_VALIDATE)
        {
            cmd_validatesig(ucMBAddr);
        }
        /* Release hardware resources. */
        if (ucStartThread)
        {
            ( void )eMBClose(  );
        }
        iExitCode = EXIT_SUCCESS;
    }
    return iExitCode;
}
Exemple #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;
        }
        
        
								   
    }
}
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;
}