Пример #1
0
void setup_interrupts()
{
	enable_interrupts(GLOBAL);
	enable_interrupts(INT_RDA2);

	if(DEVICE_CONFIG.USBDETECT_ENABLE == 0) {
		IS_USB_CONNECTED = true;
		disable_interrupts(INT_EXT1); 
	} else {
		// Check initial plug state
		if(input(PIN_B1)) {
			if(DEBUG){
				fprintf(RS232,"[DEBUG] Initial state of USB is high. Setting IS_USB_CONNECTED to true\r\n");
			}
			IS_USB_CONNECTED = true;
			ext_int_edge(1,H_TO_L); 
		} else {
			if(DEBUG){
				fprintf(RS232,"[DEBUG] Initial state of USB is low. Setting IS_USB_CONNECTED to false\r\n");
			}
			ext_int_edge(1,L_TO_H); 
		}

		clear_interrupt(INT_EXT1); 
   		enable_interrupts(INT_EXT1);

	
	}
}
Пример #2
0
void main()
{
clock_int_4MHz(); //Função necessária para habilitar o dual clock (48MHz para USB e 4MHz para CPU)

   disparo=read_eeprom(10);  //carrega o último valo ajustado
   if (disparo==0xff) {disparo=0; write_eeprom(10,0);} //inicio de operação após gravação

   enable_interrupts(GLOBAL);
   enable_interrupts(INT_EXT);
   //enable_interrupts(INT_EXT1);
   ext_int_edge(L_TO_H);

 while(true)
   {
   ++i; if (i>=50000) {i=0; output_toggle(pin_b7);} //Led de visualização

      if(!input(botao))//botão de incremento de fase
      {  delay_ms(100);   while(!input(botao))  delay_ms(100); //filtro botão
         disparo++; // na prática está identificando o zero só uma vez por ciclo
         if(disparo>=7) {disparo=7;} //o botão no pino E3 regula o ângulo de disparo
         write_eeprom(10, disparo);
         
      }

    if(!input(botao1))
      {  delay_ms(100);   while(!input(botao1))  delay_ms(100);
         disparo--;
         if(disparo<=1) {disparo=1;}
         write_eeprom(10, disparo);
        }

   }
}
Пример #3
0
void main()
{
    setup_comparator(NC_NC_NC_NC);// This device COMP currently not supported by the PICWizard
    // enable_interrupts(INT_EXT);
    setup_timer_0(RTCC_INTERNAL|RTCC_DIV_256); //32.7 ms overflow
    enable_interrupts(INT_TIMER0);
    enable_interrupts(INT_RDA);
    //enable_interrupts(INT_TIMER1);
    enable_interrupts(GLOBAL);

//  setup_timer_1(T1_INTERNAL|T1_DIV_BY_8);//128ms overflow

    ext_int_edge( H_TO_L );   // Sets up EXT
    setup_timer_1 (T1_DISABLED );
    printf("NguyenHung \n \r DT5 - K53 - DHBKHN \n \r");
    printf("Ready to use !! \n\r ");
    TC3 = 0;
    RC3 = 1;

    while(true)
    {
        if(get_timer1() > MAX_PULSE_WIDTH)
        {
            if(pulse_count>FILTER_VALUE)
            {
                printf("W");
                IDLE_MODE();
            }
        }
    }
}
Пример #4
0
void main()
{

   setup_adc_ports(NO_ANALOGS|VSS_VDD);
   setup_adc(ADC_OFF);
   setup_spi(SPI_SS_DISABLED);
   setup_wdt(WDT_OFF);
   setup_timer_0(RTCC_INTERNAL);
   setup_timer_1(T1_DISABLED);
   setup_timer_2(T2_DISABLED,0,1);
   setup_comparator(NC_NC_NC_NC);
   setup_vref(FALSE);
   enable_interrupts(INT_EXT);
   ext_int_edge(L_to_H);
   enable_interrupts(GLOBAL);
   output_low(PIN_B7);
//Setup_Oscillator parameter not selected from Intr Oscillator Config tab

   // TODO: USER CODE!!
   
   while(TRUE)
   {
   }

}
Пример #5
0
void Configurar_interrupciones(){

   enable_interrupts(INT_EXT);    // Habilita la interrupcion RB0
   ext_int_edge(L_TO_H);         // Flag INTF si flanco de bajada / H_TO_L bajada
   enable_interrupts(GLOBAL);

}
void Configurar_interrupciones() {
    setup_timer_0(RTCC_INTERNAL|RTCC_DIV_2);   //Configuración timer0
    set_timer0 (0x00);                 //Carga del timer0
    ext_int_edge(L_TO_H);         // Flag INTF si flanco de bajada / H_TO_L bajada
    enable_interrupts(INT_EXT);   // habilitar interrupcion del RB0 /INTE
    enable_interrupts(INT_RB);   // habilitar interrupcion del RB
    enable_interrupts(GLOBAL);
}
Пример #7
0
/* Habilita los sensores segun corresponda para comenzar la lectura*/
void startReading(int sensors)
{
	// Sensor1
	if (bit_test(sensors, 0) == 1)
		sensor1 = SENSOR_ON;

	// Sensor2
	if (bit_test(sensors, 1) == 1)
		sensor2 = SENSOR_ON;

	// Sensor3
	if (bit_test(sensors, 2) == 1)
		sensor3 = SENSOR_ON;

	// Sensor4
	if (bit_test(sensors, 3) == 1)
		sensor4 = SENSOR_ON;

	// Sensor5
	if (bit_test(sensors, 4) == 1)
		sensor5 = SENSOR_ON;

	// Sensor6
#if TRIGGER_TYPE == ULTRASONIC_SENSOR
	// Sensor6 -> ULTRASONIC_SENSOR
	if (bit_test(sensors, 5) == 1)
	{
		// Comienza el pulso de habilitacion -> TRIGGER como escritura
		bit_clear(trisB_value, 0);
		set_tris_b(trisB_value);
		// Pin en estado habilitado -> envio del pulso INIT
		trigger = 1;
		delay_us(ULTRASONIC_INIT_PULSE_WIDTH_US);
		trigger = 0;
		// Termina el pulso de habilitacion -> TRIGGER como lectura
		bit_set(trisB_value, 0);
		set_tris_b(trisB_value);
		// Setea la interrupcion sobre RB0 en flanco ascendente
		ext_int_edge(L_TO_H);
		// Seteo el estado actual del pulso del sensor de ultrasonido
		usonic_state = USONIC_STATE_START;
		// Habilita la interrupcion
		enable_interrupts(INT_EXT);
	}
#elif TRIGGER_TYPE == SWITCH_SENSOR
	// Sensor6 -> SWITCH_SENSOR
	if (bit_test(sensors, 5) == 1)
	{
		if (trigger == 1)
			values[5] = 0xFFFF;
		else
			values[5] = 0;		
	} 
#endif

	return;
}	
Пример #8
0
void ACTIVE_MODE(void)
{
    disable_interrupts(INT_TIMER0);
    RC3 =1 ;
    wait(0x100);// so luyen: 01686269854
//   wait(0xffff);
    set_timer0(0);
    enable_interrupts(INT_TIMER0);
    set_timer1(0);
    enable_interrupts(INT_EXT);
    ext_int_edge( H_TO_L );   // higt to low
    pulse_count =0;
}
Пример #9
0
//======================================
//Chuong trinh chinh
//======================================
void main()
{
enable_interrupts(int_rda); //Cai datngattruyen thong
ext_int_edge( H_TO_L );
   setup_timer_1(T1_INTERNAL | T1_DIV_BY_8); //Cai dat bo chia Timer 1
enable_interrupts(INT_TIMER1); //Timer1 65536
   set_timer1(3036); //Cai dat Timer 1 ngat trong 0.1s
enable_interrupts(INT_EXT);
enable_interrupts(global);
   //Datcac gia tri ban dau cho cacbien
xung = 0;
vantoc = 0;
Vdat = 0;
kp = 0;
ki = 0;
kpi = 0;
kii = 0;
kd = 0; //Bien TG khoi dong
//Cai dat vao ra
set_tris_a(0xFF);
set_tris_b(0xFF);
set_tris_c(0xc0);
set_tris_d(0x00);
delay_ms(50);
   //Cai dat ADC
setup_adc(ADC_CLOCK_INTERNAL);
setup_adc_ports(RA0_ANALOG);
set_adc_channel(0);
setup_comparator(NC_NC_NC_NC); 
setup_vref(FALSE); 
delay_ms(50);
while(1)
   {
   //Do dong dien
do_dong();
delay_ms(50); 
do_dong();
delay_ms(50);
   //Xuat len may tinh
printf("!%4.0f|%1.3f@",(float)vantoc,(float)ampe);
  }
}
Пример #10
0
//Incluye las cabeceras antes descritas
void main(){                           //Rutina principal
    output_high(LED);                  //Enciende el LED indicador
    lcd_init();                         
    //Rutina de incializacion del LCD
    lcd_putc("\fListo      \n");        
    //Despliega el mensaje "Listo" en el LCD
    setup_adc_ports(AN0);               
    //Fija el pin 0 del puerto A como entrada analogica
    setup_adc (adc_clock_internal);     
    //El tiempo para la conversion AD esta dado por el oscilador 
    //interno
    set_adc_channel(0);                 //El puerto AD activo es el 0
    enable_interrupts(INT_EXT);        
    //Habilita la interrupcion externa en RB0
    ext_int_edge(L_to_H);
    //Fija la interrupcion por flanco de subida.
    setup_timer_2(T2_DIV_BY_16,129,16);
    //El tiempo de oscilacion del timer 2 sirve tanto para la
    //interrupcion por timer2 como para el PWM. 
    setup_ccp1(CCP_PWM);              
    //Da de alta el modulo CCP1 como PWM 
    //y lo inicializa en duty cycle 0
    set_pwm1_duty(0);
    setup_ccp2(CCP_PWM);
    //Da de alta el modulo CCP2 como PWM 
    //y lo inicializa en duty cycle 0
    set_pwm2_duty(0);
    enable_interrupts(GLOBAL);          
    //Habilita las interrupciones globales
    output_low(LED);        //Apaga el led antes encendido.
    
    while(TRUE){           
        //Esta rutina espera a la interrupcion y parpadea el LED
        //indicador
        output_low(LED);
        delay_ms(100);
        output_high(LED);
        delay_ms(100);
    }
   }
Пример #11
0
void int_trigger(void)
{
#if TRIGGER_TYPE == ULTRASONIC_SENSOR
	if (usonic_state == USONIC_STATE_START)
	{
		// Tomo el tiempo en que comienza el pulso
		pulseStart = get_timer1();
		// Cambio el tipo de flanco
		ext_int_edge(H_TO_L);
		// Cambio el estado
		usonic_state = USONIC_STATE_STOP;
	} else {
		// Tomo el tiempo y guardo el valor
		values[5] = (get_timer1() - pulseStart)/2;
		// Deshabilita la interupcion
		disable_interrupts(INT_EXT);
	}
#elif TRIGGER_TYPE == SWITCH_SENSOR
	triggerAlarm = 1;
#endif


}
Пример #12
0
void main()
{
   disable_interrupts(GLOBAL);
   
   setup_spi(SPI_MASTER | SPI_MODE_0_0 | SPI_CLK_DIV_16 );
   setup_spi2(SPI_MASTER | SPI_MODE_0_0 | SPI_CLK_DIV_16 );
   
   setup_adc_ports(sAN0|sAN1|sAN2|sAN3|sAN4|VSS_4V096);
   setup_adc(ADC_CLOCK_INTERNAL|ADC_TAD_MUL_0);

   // TIMER 0 is being used to service the WTD
   setup_timer_0(T0_INTERNAL|T0_DIV_256);
   /* sets the internal clock as source and prescale 256. 
      At 10 Mhz timer0 will increment every 0.4us (Fosc*4) in this setup and overflows every
      6.71 seconds. Timer0 defaults to 16-bit if RTCC_8_BIT is not used.
      Fosc = 10 MHz, Fosc/4 = 2.5 Mhz, div 256 = 0.0001024 s, 65536 increments = 6.71 sec
      Fosc = 64 MHz, Fosc/4 = 16 Mhz, div 256 = 0.000016 s, 65536 increments = 1.05 sec
      .. pre-load with 3036 to get exact 1.0000 sec value
   */
   
   // TIMER 1 is used to extinguish the LED
   setup_timer_1(T1_INTERNAL|T1_DIV_BY_8);
   /* sets the internal clock as source and prescale 4. 
      At 10Mhz timer0 will increment every 0.4us in this setup and overflows every
      104.8 ms. Timer1 is 16-bit.
      Fosc = 10 Mhz ... 2.5 MHz / div 4  = 0.00000160 s * 65536 = 0.104858 sec
      Fosc = 64 Mhz ... 16 MHz /  div 4  = 0.00000025 s * 65536 = 0.016384 sec
      Fosc = 64 Mhz ... 16 MHz /  div 8  = 0.00000200 s * 65536 = 0.032768 sec
   */   
   
   setup_stepper_pwm();  // Uses TIMER 2
   
   // TIMER 3 is used for stepper motor intervals
   setup_timer_3(T3_INTERNAL | T3_DIV_BY_1);   // 16 bit timer
   
   // TIMER 4 is use for serial time-outs. 8-bit timer.
   setup_timer_4(T4_DIV_BY_4, 127, 1);           
   
   setup_comparator(NC_NC_NC_NC);
   
   setup_oscillator(OSC_16MHZ | OSC_PLL_ON);  // Fosc = 64 MHz
          
   ext_int_edge(0, H_TO_L);         // Set up PIC18 EXT0
   enable_interrupts(INT_EXT);
   
   start_heartbeat();
   
   enable_interrupts(GLOBAL);

   init_hardware();
   motor_sleep_rdy();
   
   sleep_mode = FALSE;   
   busy_set();
   
   init_nv_vars();
   get_step_vars();
   init_aws();
   
   blink();
   
   //Add for TCP/IP interface
   //delay_ms(15000);
   
   signon();
   
   RTC_read();
   RTC_last_power();
   RTC_reset_HT();  
   RTC_read();    
   RTC_read_flags();
   
   if(nv_sd_status>0) fprintf(COM_A,"@SD=%Lu\r\n", nv_sd_status);
   init_rtc(); // This is the FAT RTC
   sd_status = init_sdcard();
   if(sd_status>0) msg_card_fail();
   
   reset_event();
   
   if(m_error[0] > 0 || m_error[1] > 0) msg_mer();  
   
   if (m_comp[0]==FALSE) {
      e_port[0]=0;
      write16(ADDR_E1_PORT,0);
      fprintf(COM_A, "@MC1,%Lu,%Ld\r\n", m_comp[0],e_port[0]);
   }
   if (m_comp[1]==FALSE) {
      m_lin_pos[1]=-1;
      write16(ADDR_M2_LIN_POS, -1);
      fprintf(COM_A, "@MC2,%Lu,%Ld\r\n", m_comp[1],m_lin_pos[1]);
   }
   
   if (nv_cmd_mode == FALSE){
      for(dt=0; dt<100; ++dt){
         blip();
         if (nv_cmd_mode == TRUE) {
            busy_clear();
            fputs("@OK!", COM_A);
            command_prompt();
            dt = 100;
         }
      }
   }
   else command_prompt();
   
   user_quit = auto_sample_ready();
   
   reset_cpu();
}
Пример #13
0
main()   {

   ext_buffer_next_in = 0;                      // init variables
   ext_buffer_next_out = 0;

   ext_int_edge(H_TO_L);                        // init interrupts
   enable_interrupts(INT_EXT);
   enable_interrupts(GLOBAL);

   while(TRUE)                                  // loop always
   {
      int i;

      if(MESSAGE_SEND)                          // if button pushed
      {
         packet_buffer[0] = SEND_ADDRESS;
         packet_buffer[1] = MACHINE_ADDRESS;
         packet_buffer[2] = 0;
         packet_buffer[3] = 0;
         packet_buffer[4] = 9;
         packet_buffer[5] = 'H';
         packet_buffer[6] = 'i';
         packet_buffer[7] = ' ';
         packet_buffer[8] = 't';
         packet_buffer[9] = 'h';
         packet_buffer[10] = 'e';
         packet_buffer[11] = 'r';
         packet_buffer[12] = 'e';
         packet_buffer[13] = '!';
         send_packet(packet_buffer, 14);        // send message
      }

      delay_ms(100);

      if(!DATA_IN)                              // if no data in
         continue;                              // loop back

      if(get_packet(packet_buffer))             // if valid packet
      {
         int16 length,i;
         int16 CRC;

         printf("Message from unit# %U\n",packet_buffer[1]);

         length = ((int16)(packet_buffer[3]<<8)) + packet_buffer[4];

         if(packet_buffer[2] == ACK)
            printf("Previous message sent was received by unit.\n");

         if(length)                             // display message
         {
            printf("Message is:\n\n");
            for(i=0;i<length; i++)
               putc(packet_buffer[i+5]);
         }
         printf("\n\n... Message End ...\n\n\n");

         if(length)
         {
            packet_buffer[0] = packet_buffer[1];//send an ACK
            packet_buffer[1] = MACHINE_ADDRESS;
            packet_buffer[2] = ACK;
            packet_buffer[3] = 0;
            packet_buffer[4] = 0;
            send_packet(packet_buffer, 5);
         }
      }
      else                                      // if not valid packet
      {
         if(packet_buffer[0] != MACHINE_ADDRESS)
            break;                              // message is not for this PIC
         else if(packet_buffer[2] == NACK)      // tried to send and failed error
            printf("Previous message sent was not received by unit.\n");
         else
         {                                      // tried to receive and failed error
            printf("Message received was corrupted.\n");

            packet_buffer[0] = packet_buffer[1];//send a NACK
            packet_buffer[1] = MACHINE_ADDRESS;
            packet_buffer[2] = NACK;
            packet_buffer[3] = 0;
            packet_buffer[4] = 0;
            send_packet(packet_buffer, 5);

         }
      }
   }
}
Пример #14
0
/* Verifica que el comando sea valido y lo ejecuta */
void doCommand(struct command_t * cmd)
{
	int crc, i, len;
		
	// Calculo del CRC
	crc = generate_8bit_crc((char *)cmd, cmd->len, CRC_PATTERN);
	
	// CRC ok?
	if (cmd->crc != crc)
	{		
		// Creo respuesta de error
		response.len = MIN_LENGTH + cmd->len + 2 + 1;
		response.to = cmd->from;
		response.from = THIS_CARD;
		response.cmd = COMMON_ERROR;
		response.data[0] = 0x00;
		// Agrego el paquete que contiene el error de CRC
		response.data[1] = cmd->len;
		response.data[2] = cmd->to;
		response.data[3] = cmd->from;
		response.data[4] = cmd->cmd;
		// Campo data
		len = cmd->len - MIN_LENGTH;
		for (i = 0; i < len; i++)
			response.data[5 + i] = (cmd->data)[i];
		// CRC erroneo
		response.data[5 + len] = cmd->crc;
		// CRC esperado
		response.data[5 + len + 1] = crc;
		// CRC de la respuesta
		response.crc = generate_8bit_crc((char *)(&response), response.len, CRC_PATTERN);
	
		crcOK = false;
		return;
	}

	crcOK = true;
	
	// Minimo todos setean esto
	response.len = MIN_LENGTH;
	response.to = cmd->from & 0x77;
	response.from = THIS_CARD;
	response.cmd = cmd->cmd | 0x80;

	switch (cmd->cmd)
	{
		// Comandos comunes
		case COMMON_INIT:
			init();
			// Enviar la descripcion de la placa en texto plano
			strcpy(response.data, DESC);
			response.len += strlen(response.data);
		break;
		case COMMON_RESET:
			// Enviar la descripcion de la placa en texto plano
			strcpy(response.data, DESC);
			response.len += strlen(response.data);
			// Reset!
			reset = true;
		break;
		case COMMON_PING:
			// No hace falta hacer mas nada
		break;
 		case COMMON_ERROR:
			// Por ahora se ignora el comando
		break;
		
		/* Comandos especificos */

 		case DISTANCE_SENSOR_ON_DISTANCE_SENSOR:
			/* Enciende el sensor de distancia indicado.
			:DATO:
			Valor de 0x00 a 0x05 que representa el ID del sensor a encender.
			El ID 0x05 hace referencia al led de la placa si esta presente, 
			en caso contrario se ignora.
			:RESP:
			-
			*/
			// Enciende los sensores segun corresponda
			if ((cmd->data)[0] == 0)
				// Sensor1
				sensor1 = SENSOR_ON;
			else if ((cmd->data)[0] == 1)
				// Sensor2
				sensor2 = SENSOR_ON;
			else if ((cmd->data)[0] == 2)
				// Sensor3
				sensor3 = SENSOR_ON;
			else if ((cmd->data)[0] == 3)
				// Sensor4
				sensor4 = SENSOR_ON;
			else if ((cmd->data)[0] == 4)
				// Sensor5
				sensor5 = SENSOR_ON;
#if TRIGGER_TYPE == LED
			else if ((cmd->data)[0] == 5)
				// Led
				led1 = 1;
#endif
		break;
 		case DISTANCE_SENSOR_OFF_DISTANCE_SENSOR:
			/* Apaga el sensor de distancia indicado.
			:DATO:
			Valor de 0x00 a 0x05 que representa el ID del sensor a apagar. El
			ID 0x05 hace referencia al sensor de ultrasonido o switch de la placa.
			:RESP:
			-
			*/
			// Apaga los sensores segun corresponda
			if ((cmd->data)[0] == 0)
				// Sensor1
				sensor1 = SENSOR_OFF;
			else if ((cmd->data)[0] == 1)
				// Sensor2
				sensor2 = SENSOR_OFF;
			else if ((cmd->data)[0] == 2)
				// Sensor3
				sensor3 = SENSOR_OFF;
			else if ((cmd->data)[0] == 3)
				// Sensor4
				sensor4 = SENSOR_OFF;
			else if ((cmd->data)[0] == 4)
				// Sensor5
				sensor5 = SENSOR_OFF;
#if TRIGGER_TYPE == LED
			else if ((cmd->data)[0] == 5)
				// Led
				led1 = 0;
#endif
		break;
 		case DISTANCE_SENSOR_SET_MASK:
			/* Habilita o deshabilita cada uno de los sensores de distancia conectados al
			controlador. Permite identificar los sensores a los que se debera tener en
			cuenta para futuras lecturas.
			:DATO:
			Valor de 0x00 a 0x3F donde cada bit representa el ID del sensor a
			habilitar o deshabilitar. Si 2^ID = 1 entonces el sensor ID esta habilitado.
			Si 2^ID = 0 entonces el sensor ID esta deshabilitado.
			:RESP:
			-
			*/
			sensorMask = (cmd->data)[0];
		break;
 		case DISTANCE_SENSOR_GET_MASK:
			/* Obtiene el estado de habilitacion de cada uno de los sensores de distancia
			conectados al controlador.
			:DATO:
			-
			:RESP:
			Valor de 0x00 a 0x3F donde cada bit representa el ID del sensor a
			habilitar o deshabilitar. Si 2^ID = 1 entonces el sensor ID esta habilitado.
			Si 2^ID = 0 entonces el sensor ID esta deshabilitado.
			*/
			// Envio la mascara de sensores
			response.data[0] = sensorMask;
			// Corrijo el largo del paquete
			response.len++;
		break;
 		case DISTANCE_SENSOR_GET_VALUE:
			/* Obtiene el valor promedio de la entrada de los sensores indicados.
			:DATO:
			Valor de 0x00 a 0x3F donde cada bit representa el ID del sensor
			del cual obtener la lectura.
			:RESP:
			Valor de 0x00 a 0x3F donde cada bit representa el ID del sensor
			del cual proviene el la lectura de distancia. Secuencia de numeros enteros
			positivos de 16 bits en el rango desde 0x0000 hasta 0x03FF, con el valor de
			la lectura que representa la distancia al objeto. En la secuencia de numeros
			el orden esta dado de izquierda a derecha comenzando por el bit menos
			significativo.
			En el caso del sensor de ultrasonido el rango es desde 0x0000 hasta 0x7594
			que representa la minima y maxima lectura del sensor.
			En el caso del switch, un estado logico bajo se lee como 0x0000 y un estado
			logico alto se lee como 0xFFFF.
			*/
			readSensor = (cmd->data)[0];
			requestFrom = 	response.to;
			requestCmd = response.cmd;
			sendResponse = false;
			samples = SAMPLES_DEFAULT;
		break;
 		case DISTANCE_SENSOR_GET_ONE_VALUE:
			/* Obtiene el valor de la entrada del sensor indicado. Igual al comando 8.5 pero
			sin realizar un promedio de lecturas.
			:DATO:
			Valor de 0x00 a 0x3F donde cada bit representa el ID del sensor
			del cual obtener la lectura.
			:RESP:
			Valor de 0x00 a 0x3F donde cada bit representa el ID del sensor
			del cual proviene el la lectura de distancia. Secuencia de numeros enteros
			positivos de 16 bits en el rango desde 0x0000 hasta 0x03FF, con el valor de
			la lectura que representa la distancia al objeto. En la secuencia de numeros
			el orden esta dado de izquierda a derecha comenzando por el bit menos
			significativo.
			En el caso del sensor de ultrasonido el rango es desde 0x0000 hasta 0x7594
			que representa la minima y maxima lectura del sensor.
			En el caso del switch, un estado logico bajo se lee como 0x0000 y un estado
			logico alto se lee como 0xFFFF.
			*/
			readSensor = (cmd->data)[0];
			requestFrom = 	response.to;
			requestCmd = response.cmd;
			sendResponse = false;
			samples = 1;
		break;
		case DISTANCE_SENSOR_ALARM_ON_STATE:
			/* Cuando un switch esta presente en el ID: 0x05, establece si se desea o no
			recibir una alarma ante cierto cambio de estado en el mismo. Puede ser ante
			cualquier cambio o sobre un anco ascendente o descendente.
			:DATO:
			Valor entre 0x00 y 0x03 con el tipo de cambio ante el cual generar
			la alarma. Con un 0x00 ignora cualquier cambio en el switch. Se utiliza
			0x01 para que cualquier cambio en el switch genere el mensaje, 0x02 para
			que sea solo ante un flanco ascendente y 0x03 para que sea solo ante un
			flanco descendente.
			:RESP:
			-
			*/
#if TRIGGER_TYPE == SWITCH_SENSOR
			switch ((cmd->data)[0])
			{
				case 0x00:
					// Ignorar
					disable_interrupts(INT_EXT);
					break;
				case 0x01:
					// Cualquier cambio
					enable_interrupts(INT_EXT);
					break;
				case 0x02:
					// flanco ascendente
					ext_int_edge(H_TO_L);
					enable_interrupts(INT_EXT);
					break;
				case 0x03:
					// flanco descendente
					ext_int_edge(L_TO_H);
					enable_interrupts(INT_EXT);
					break;
				default:
					(cmd->data)[0] = 0x00;
					break;
			}
			alarmType = (cmd->data)[0];
#endif
		break;
		default:
			response.len++;
			response.cmd = COMMON_ERROR;
			response.data[0] = 0x01; // Comando desconocido
		break;
	}	

	// CRC de la respuesta
	response.crc = generate_8bit_crc((char *)(&response), response.len, CRC_PATTERN);

	return;
}
Пример #15
0
void init()
{
	// Inicializa puertos
	set_tris_a(0b11111111);
	set_tris_b(trisB_value);

	// ***ADC***
	setup_port_a(sAN0);
	setup_adc(ADC_CLOCK_INTERNAL);
	set_adc_channel(0);
	setup_adc_ports(sAN0);
	setup_vref(VREF_HIGH | 8);
	
	// Seteo el Timer1 como fuente interna
	setup_timer_1(T1_INTERNAL | T1_DIV_BY_8);
	set_timer1(26786);
	
	// Interrupcion sobre el Timer1
	enable_interrupts(INT_TIMER1);

	// Seteo el pin RB0 - Sensor de ultrasonido :)
	ext_int_edge(L_TO_H);
	enable_interrupts(INT_EXT);

	// Habilito las interrupciones
	enable_interrupts(GLOBAL);
	
	// Variable para hacer el reset
	reset = false;

	// Apaga todos los sensores
	sensor1 = SENSOR_OFF;
	sensor2 = SENSOR_OFF;
	sensor3 = SENSOR_OFF;
	sensor4 = SENSOR_OFF;
	sensor5 = SENSOR_OFF;

	// Inicializa los valores
	values[0] = 0x0000;
	values[1] = 0x0000;
	values[2] = 0x0000;
	values[3] = 0x0000;
	values[4] = 0x0000;
	values[5] = 0x0000;

	// Muestras iniciales
	samples = SAMPLES_DEFAULT;
	
	// Inicializa la mascara -> todos habilitados (0x3F)
	sensorMask = DEFAULT_MASK;
	
	//Determina el estado actual
	state = STATE_FREE;
	
	// Sin lectura temprana
	readSensor = 0x00;
	bufferedReadSensor = 0x00;
	actalTO = 0x00;
	requestFrom = 0x00;
	bufferedFrom = 0x00;
	actalCmd = 0x00;
	requestCmd = 0x00;
	bufferedCmd = 0x00;

	alarmType = 0x00;
	triggerAlarm = 0;
#if TRIGGER_TYPE == SWITCH_SENSOR
	disable_interrupts(INT_EXT);
#endif

#if TRIGGER_TYPE == LED
	// TRIGGER como escritura
	bit_clear(trisB_value, 0);
	set_tris_b(trisB_value);
#endif

	return;	
}	
Пример #16
0
void Configurar_interrupciones(){
   enable_interrupts(INT_EXT);   // habilitar interrupcion del RB0 /INTE
   ext_int_edge(L_TO_H);         // Flag INTF si flanco de bajada / H_TO_L bajada
   enable_interrupts(INT_RB);
   enable_interrupts(GLOBAL);
}