Exemplo n.º 1
0
void getIMU(nav_struct* nav_data)
{
	
	/// getMagnetometerData(magn); No magnetometer
	getAccelerometerData(acc);
	getGyroscopeData(gyro);
	convertTemp(gyro);

	if (bias_flag == true)
	{
		bias_flag = computeBias(acc,acc_bias,ACC_VAR,&acc_bias_count);
		bias_flag = computeBias(gyro,gyro_bias,GYRO_VAR,&gyro_bias_count);
	}
	else
	{
		removeBias(acc,acc_bias,ACC_VAR);
		removeBias(gyro,gyro_bias,GYRO_VAR);
		setGravity(acc); 

		// Eliminate Hard-Iron offsets
		magn[0] = magn[0] - MX_OFFSET;
		magn[1] = magn[1] - MY_OFFSET;
		
		/// set IMU values
		nav_data->imu_lan.abbx = (double)acc[0];
		nav_data->imu_lan.abby = (double)acc[1];
		nav_data->imu_lan.abbz = -(double)acc[2];
		
		nav_data->imu_lan.wbbx = -(double)gyro[0];
		nav_data->imu_lan.wbby = -(double)gyro[1];
		nav_data->imu_lan.wbbz = -(double)gyro[2];
	}
	
}
/**
  * @brief Temperature monitoring thread
  * @param none
  * @retval none
  */
void Thread_Temperature (void const *argument) {

  while(1) {
    HAL_ADC_Start(&ADC1_Handle);                                        /* start ADC conversion */

    if (HAL_ADC_PollForConversion(&ADC1_Handle, 10000) == HAL_OK) {     /* wait for the conversion to be done and get data */
      adc_val = HAL_ADC_GetValue(&ADC1_Handle);                         /* get the value */
      kalmanUpdate(&adcState, adc_val);                                 /* filter the data and update the filter parameters */
      temperature = convertTemp(adcState.x);
      __HAL_ADC_CLEAR_FLAG(&ADC1_Handle, ADC_FLAG_EOC);
    }


    // check if the alarm needs to be triggered
    if (temperature > THRESHHOLD_TEMP_URGENT) {
      flash_alarm = 2;
    } else if (temperature > THRESHHOLD_TEMP) {
      flash_alarm = 1;
    } else {
      flash_alarm = 0;
    }

    osDelay(TEMP_DELAY);
  }
}
Exemplo n.º 3
0
void manage_temperatures()
{
	static uint8 tempMeasureCount = 0;
	uint16 *result; // Va servir à récupérer les données des ADCs en pointant vers le régistre correspondant
	uint8 i;
	int32 val;

	// Timeout reached, we start measure procedure
	if(gTempState == START)
	{
		
	}
	
	// Les mesures de temperatures sont pretes a etre récupérées et utilisées
	else if (gFlags.ADC0done && gFlags.ADC1done)  // gTempState = 2, but no need to test the value
	{
		tempMeasureCount++;

		// ------------ Récupération des mesures des ADC ---------------
		
		// ####### ADC0 ######
		result = (uint16*) &ATD0DR0H; // &ATD0DR0H Pointe sur le début du registre de l'ADC0
		
		// On récupère les données dans le premier registre et les registres subséquents
		for(i=0; i < 8; i++){
			gTempRaw[gTempIndex[i]] = *result; // On récupère les données en les mettant en ordre (T0, T1, ...) dans gTempRaw[]
			result++;
		}
		
		// ####### ADC1 #######
		result = (uint16*) &ATD1DR0H; // Pointe sur le registre de l'ADC1
		
		// On récupère les données dans le premier registre et les registres subséquents
		for(i=0; i < 4; i++){
			gTempRaw[gTempIndex[i + 8]] = *result; // On récupère les données en les mettant en ordre (T0, T1, ...) dans gTempRaw[]
			result++;
		}
		
		
		// Arithmetic average on the values measured since the last temperature message sent to the master
		for(i = 0; i < NB_CELL; i++) {
			val = (int32)convertTemp(gTempRaw[i]) + ((int32)gTemp[i] * (tempMeasureCount - 1));
			gTemp[i] = val / tempMeasureCount;
		}

	    #ifdef CAN_ENABLE
	    // Send the temperatures to master via CAN
	    if(tempMeasureCount >= NB_TEMP_SAMPLES) {
	      // TODO: we do nothing with this flag so far...
	      gFlags.canTxError = CAN_SendTemperatures(gSlaveID, gTemp);
	      tempMeasureCount = 0;
	    }
	    #endif

	    gFlags.ADC0done = 0;
	    gFlags.ADC1done = 0;
		gTempState = T_STANDBY;
	}
}
Exemplo n.º 4
0
void ds18x20Process(void)
{
	if (getTempTimer() == 0) {

		/* Convert temperature */
		if (ds18x20IsOnBus())
			convertTemp();
	}

	return;
}
Exemplo n.º 5
0
/* =================================================
FUNCTION: getIMU

CREATED: 16-05-2014

DESCRIPTION: This main loop function for the IMU
sensor suite

PARAMETERS: vec

GLOBAL VARIABLES: None.

RETURNS: vec.

AUTHOR: P. Kantue

================================================== */
void getIMU(int vec[], unsigned int time_el)
{
  
  getMagnetometerData(magn);
  getAccelerometerData(acc);
  getGyroscopeData(gyro);
  convertTemp(gyro);

  if (bias_flag == true){
    bias_flag = computeBias(acc,acc_bias,ACC_VAR,&acc_bias_count);
    bias_flag = computeBias(gyro,gyro_bias,GYRO_VAR,&gyro_bias_count);
  }
  else{
    removeBias(acc,acc_bias,ACC_VAR);
    removeBias(gyro,gyro_bias,GYRO_VAR);
    setGravity(acc); 

    // Eliminate Hard-Iron offsets
    magn[0] = magn[0] - MX_OFFSET;
    magn[1] = magn[1] - MY_OFFSET;
    
    // Compute Euler angles from acceleration raw values
    PitchandRoll(acc,temp_euler);
    
    // Apply LPF to both pitch and roll angles
    LPF_euler(Euler,temp_euler,EULER_LPF);    
    
    // Compute tilt compensation for magnetic heading - NOT WORKING
    heading = tiltCompensation(magn,Euler);

    // Store IMU data to be passed to other subsystems
    storeIMU(acc,gyro,magn,Euler,heading,vec, time_el);
    
    //----ADD EXTRA CODE HERE ------------//
  }

}
Exemplo n.º 6
0
int main(void)
{
	unsigned char dev1_access, dev2_access, dev3_access, dev4_access, dev5_access, dev6_access, dev7_access, dev8_access;						// Indique si les informations ont bien été prise du capteur

	init();									// Initialisations globales
	
	dev1_access = initDS7505(ADD1_DS7505);	// Initialiser le capteur de T° n°1
	dev2_access = initDS7505(ADD2_DS7505);	// Initialiser le capteur de T° n°2
	dev3_access = initDS7505(ADD3_DS7505);	// Initialiser le capteur de T° n°3
	dev4_access = initDS7505(ADD4_DS7505);	// Initialiser le capteur de T° n°4
	dev5_access = initDS7505(ADD5_DS7505);	// Initialiser le capteur de T° n°5
	dev6_access = initDS7505(ADD6_DS7505);	// Initialiser le capteur de T° n°6
	dev7_access = initDS7505(ADD7_DS7505);	// Initialiser le capteur de T° n°7
	dev8_access = initDS7505(ADD8_DS7505);	// Initialiser le capteur de T° n°8


	/* boucle infinie */
	for(;;)
	{	
		if( data[0] != 0x00 ) // Envoie des informations à la foxboard
		{
			switch(data[0])
			{
				case CMD_INCLINAISON : // Envoie les informations d'inclinaisons du sous-marin
					transmission(CMD_INCLINAISON, ACCL, ACCH);
					break;

				case CMD_HYGROMETRE1 : // Envoie les informations d'humidité du premier capteur hygrométrique
					transmission(CMD_HYGROMETRE1, HUM1L, HUM1H);
					break;

				case CMD_HYGROMETRE2 : // Envoie les informations d'humidité du deuxième capteur hygrométrique
					transmission(CMD_HYGROMETRE2, HUM2L, HUM2H);
					break;

				case CMD_BALLAST : // Envoie les informations de la position du ballast
					transmission(CMD_BALLAST, IMP1L, IMP1H);
					break;

				case CMD_SYSTEME_BALLAST : // Envoie les informations de la position du chariot portant le ballast
					transmission(CMD_SYSTEME_BALLAST, IMP2L, IMP2H);
					break;

				case CMD_TEMP1 : // Envoie les informations de température du premier capteur
					dev1_access = get_DS7505_Devices(ADD1_DS7505, listTemp); // Récupérer T° capteur n°1
					convertTemp(listTemp, tempResult);

					TEMP1H = tempResult[0];
					TEMP1L = tempResult[1];

					transmission(CMD_TEMP1, TEMP1L, TEMP1H);
					break;

				case CMD_TEMP2 : // Envoie les informations de température du deuxième capteur
					dev2_access = get_DS7505_Devices(ADD3_DS7505, listTemp); // Récupérer T° capteur n°2
					
					convertTemp(listTemp, tempResult);

					TEMP2H = tempResult[0];
					TEMP2L = tempResult[1];

					transmission(CMD_TEMP2, TEMP2L, TEMP2H);
					break;

				case CMD_TEMP3 : // Envoie les informations de température du troisième capteur
					dev3_access = get_DS7505_Devices(ADD3_DS7505, listTemp); // Récupérer T° capteur n°3
					
					convertTemp(listTemp, tempResult);

					TEMP3H = tempResult[0];
					TEMP3L = tempResult[1];

					transmission(CMD_TEMP3, TEMP3L, TEMP3H);
					break;

				case CMD_TEMP4 : // Envoie les informations de température du quatrième capteur
					dev4_access = get_DS7505_Devices(ADD4_DS7505, listTemp); // Récupérer T° capteur n°3
					
					convertTemp(listTemp, tempResult);

					TEMP4H = tempResult[0];
					TEMP4L = tempResult[1];

					transmission(CMD_TEMP4,TEMP4L, TEMP4H);
					break;

				case CMD_TEMP5 : // Envoie les informations de température du cinquième capteur
					dev5_access = get_DS7505_Devices(ADD5_DS7505, listTemp); // Récupérer T° capteur n°3
					
					convertTemp(listTemp, tempResult);

					TEMP5H = tempResult[0];
					TEMP5L = tempResult[1];

					transmission(CMD_TEMP5, TEMP5L, TEMP5H);
					break;

				case CMD_TEMP6 : // Envoie les informations de température du sixième capteur
					dev6_access = get_DS7505_Devices(ADD6_DS7505, listTemp); // Récupérer T° capteur n°3
					
					convertTemp(listTemp, tempResult);

					TEMP6H = tempResult[0];
					TEMP6L = tempResult[1];

					transmission(CMD_TEMP6, TEMP6L, TEMP6H);
					break;

				case CMD_TEMP7 : // Envoie les informations de température du septième capteur
					dev7_access = get_DS7505_Devices(ADD7_DS7505, listTemp); // Récupérer T° capteur n°3
					
					convertTemp(listTemp, tempResult);

					TEMP7H = tempResult[0];
					TEMP7L = tempResult[1];

					transmission(CMD_TEMP7, TEMP7L, TEMP7H);
					break;

				case CMD_TEMP8 :  // Envoie les informations de température du huitième capteur
					dev8_access = get_DS7505_Devices(ADD8_DS7505, listTemp); // Récupérer T° capteur n°3
					
					convertTemp(listTemp, tempResult);

					TEMP8H = tempResult[0];
					TEMP8L = tempResult[1];

					transmission(CMD_TEMP8, TEMP8L, TEMP8H);
					break;
				
				case CMD_PROFONDEUR : // Envoie les informations de pression reçue par le capteur de pression comme indicatif de la profondeur
					StartADC(0);
					ReadADC(listTemp);
					ADC1L = listTemp[0];
					ADC1H = listTemp[1];
					transmission(CMD_PROFONDEUR, ADC1L, ADC1H);
					cbiBF(PORTD,2);
					cbiBF(PORTD,3);
					sbiBF(PORTD,4);
					break;

				case CMD_ADC2 : // Envoie les informations du deuxième convertisseur ADC
					StartADC(1);
					ReadADC(listTemp);
					ADC2L = listTemp[0];
					ADC2H = listTemp[1];
					transmission(CMD_ADC2, ADC2L, ADC2H);
					sbiBF(PORTD,2);
					cbiBF(PORTD,3);
					sbiBF(PORTD,4);
					break;

				case CMD_ADC3 : // Envoie les informations du troisième convertisseur ADC
					StartADC(2);
					ReadADC(listTemp);
					ADC3L = listTemp[0];
					ADC3H = listTemp[1];
					transmission(CMD_ADC3, ADC3L, ADC3H);
					cbiBF(PORTD,2);
					sbiBF(PORTD,3);
					sbiBF(PORTD,4);
					break;

				case CMD_ADC4 : // Envoie les informations du quatrième convertisseur ADC
					StartADC(3);
					ReadADC(listTemp);
					ADC4L = listTemp[0];
					ADC4H = listTemp[1];
					transmission(CMD_ADC4, ADC4L, ADC4H);
					sbiBF(PORTD,2);
					sbiBF(PORTD,3);
					sbiBF(PORTD,4);
					break;

				case CMD_SENS_0_POSITIF :
					Sens_0 = 1 ;
					transmission(CMD_SENS_0_POSITIF,Conf_sens0p, 0x00 );
					break;

				case CMD_SENS_0_NEGATIF :
					Sens_0 = 0 ;
					transmission(CMD_SENS_0_NEGATIF,Conf_sens0n, 0x00 );
					break;

				case CMD_SENS_1_POSITIF :
					Sens_1 = 1 ;
					transmission(CMD_SENS_1_POSITIF,Conf_sens1p, 0x00 );
					break;

				case CMD_SENS_1_NEGATIF :
					Sens_1 = 0 ;
					transmission(CMD_SENS_1_NEGATIF, Conf_sens1n, 0x00 );
					break;

				default :
					asm("nop");
			}

			for(decalage=0;decalage<=4;decalage++) // Décale les demandes pour supprimer la première et passer au traitement de la demande suivante
			{
				data[decalage]=data[decalage+1];	
			}
			data[4] = 0x00 ;
		}
		else
		{
			asm("nop");
		}
	}
	return 0;	
}
/**************************************************************************************************
 * @fn          DataUpdate_ProcessEvent
 *
 * @brief       Update values from A/D sensor and diags
 *
 * @param       uint8 task_id
 * @param       uint16 events - event mask
 *
 * @return      uint16 - 0 (for now)
 **************************************************************************************************
 */
uint16 DataUpdate_ProcessEvent(uint8 task_id, uint16 events)
{
    #if ADV_DEBUG_MESSAGE_FORMAT==1
    // variables that are needed if we're running the advanced debugging message format
    int vdd_div_3;
    int vdd;
    int16 tempvalCC2541;
    int spare;
    #endif
    
    int tempval;
    int16 tempval2;
    int16 tempval3;
    int16 tempval4;
    int16 tempavg;
    uint16 timeval;
    uint16 sensorval;
    
#if USE_SEPARATE_TEMP_AD_CHANNEL==0
    uint8 lmp_configured;
    uint8 lmp_configure_tries;
#endif

#ifdef FAKE_SENS_DATA

#ifdef O2_SENSOR
    uint16 max_fake = 1000;
    uint16 min_fake = 600;
    static int16  fake_adj = 1;
    static uint16 fakesensorval = 600;
#endif
#ifdef CO_SENSOR
    uint16 max_fake = 1300;
    uint16 min_fake = 380;
    static int16  fake_adj = 1;
    static uint16 fakesensorval = 380;
#endif

    
#endif    
    if (events & 1)
    {

      timeval = (uint16) (osal_GetSystemClock() & 0xffff);
      cyclecount++;
      if (cyclecount>9)
      {
        cyclecount=0;
        // Also, set P1_0 (the LED) as an output, and drive high
        P1DIR = P1DIR | 0x01; 
        P1 = P1 | 0x01;
      }
      
      
       /* Enable channel */
       ADCCFG |= 0x80;
       P0DIR = 0x83; // force P0.0, P0.1, and P0.7 to be inputs
       APCFG = 0x83;
       HalAdcSetReference (0x40); // use AIN7 for ref (0x08 would be AVDD5, 0x00 would be internal ref

#if USE_SEPARATE_TEMP_AD_CHANNEL==0
       // Configure LMP9100 to output temperature
       if (lmp91KinitComplete)
       {
         // Because the processor may have been sleeping, re-configure I2C intf. before 
         // performing the I2C transaction
         HalI2CExitSleep();
         lmp_configure_tries=0;
         lmp_configured=0;
       
         // We can't hang out in this loop forever, but we can retry a couple
         // of times, to get over any instability on the I2C bus
         while ((lmp_configure_tries<4) && (!lmp_configured))
         {
            // Set this flag so that we presume that communication is working.
           // The flag will get cleared (quickly) as a side-effect in the
           // communication routines if we fail again.
           lmp91kOK=1; 

           lmp_configured=LMP91000_I2CSwitchVoutToTempSensor();
           
           lmp_configure_tries++;
         } // end while 
         
          // Because the processor may go into sleep mode, save the state of the I2C
          // interface before continuing.
          HalI2CEnterSleep();
       } // end if (lmp91KinitComplete)
#endif       
       
       
       // Read temperature from LMP9100
       if (!lmp91kOK)
       {
         // If we're not communicating, then the LMP91000 may not be in the right
         // state, so just use a previous value.
         tempval = oldtempval;
       }
       else
       {
         tempval =  HalAdcRead(HAL_ADC_CHANNEL_0, HAL_ADC_RESOLUTION_12);
         tempval2 =  HalAdcRead(HAL_ADC_CHANNEL_0, HAL_ADC_RESOLUTION_12);
         tempval3 =  HalAdcRead(HAL_ADC_CHANNEL_0, HAL_ADC_RESOLUTION_12);
         tempval4 =  HalAdcRead(HAL_ADC_CHANNEL_0, HAL_ADC_RESOLUTION_12);
         // Get a bit of noise out of the temperature measurment by averaging 4
         // samples.
         // By the way, we expect nominal values to be around 1100 or so
         // at room temperature, so we can fairly safely add 4 16-bit values
         // together without thinking too much about overflow.
         // If the nominal values were larger, we'd promote to a larger
         // data type before averaging.
         tempavg = (tempval+tempval2+tempval3+tempval4)/4;
         oldtempval=tempavg;
       }
       
       
       // Convert temp to tenths of degrees C, based on the table in
       // the datasheet for the LMP91000, and assuming a 2.5v ref
       
       tempval = convertTemp(tempavg);

       // Now, get ready to measure the oxygen sensor
       HalAdcSetReference (0x40); // use AIN7 for ref 
       
#if USE_SEPARATE_TEMP_AD_CHANNEL==0
       
       if (lmp91KinitComplete)
       {
         // Because the processor may have been sleeping, re-configure I2C intf. before 
         // performing the I2C transaction(s)
         HalI2CExitSleep();
         
         lmp_configure_tries=0;
         lmp_configured=0;
         // we can't hang out in this loop forever, but we can retry a couple
         // of times, to get over any instability on the I2C
         while ((lmp_configure_tries<4) && (!lmp_configured))
         {
           // Set this flag so that we presume that communication is working.
           // The flag will get cleared (quickly) as a side-effect in the
           // communication routines if we fail again.
           lmp91kOK=1; 
           
           // Likely redundant, but doesn't hurt
           LMP91000_I2CConfigureForO2Sensor( SensTIAGain , SensRLoad, SensRefVoltageSource, SensIntZSel);
           
           if (lmp91kOK)
           {
             lmp_configured = LMP91000_I2CSwitchVoutToO2Sensor(SensModeOp);
           }
 
           lmp_configure_tries++;
         } // end while
         
         // Because the processor may go into sleep mode, save the state of the I2C
         // interface before continuing.
         HalI2CEnterSleep();
       } // end  if (lmp91KinitComplete)

#endif
       
       if (!lmp91kOK)
       {
         // If we're not communicating, then the LMP91000 may not be in the right
         // state, so just use a previous value.
         sensorval = oldsensorval;
       }
       else
       {
#if    USE_SEPARATE_TEMP_AD_CHANNEL==1
       sensorval =  HalAdcRead(HAL_ADC_CHANNEL_1,HAL_ADC_RESOLUTION_12);
#else
       sensorval =  HalAdcRead(HAL_ADC_CHANNEL_0,HAL_ADC_RESOLUTION_12);
#endif
         oldsensorval = sensorval;
       }
       
       // Depending on compile options, build the message, or gather
       // additional diagnostic info and then build the debug mode message
#ifdef FAKE_SENS_DATA
fakesensorval += fake_adj;
if ((fakesensorval >= max_fake) || (fakesensorval <= min_fake))
  fake_adj = -1 * fake_adj;
sensorval = fakesensorval;
#endif
     
       #if ADV_DEBUG_MESSAGE_FORMAT==0
         updateSensorData ((uint16)timeval, (uint16)tempval, (uint16)sensorval);
         DataReadyFlag = 1;
       #else
         // Gather additional interesting diagnostic info before updating structure
         spare = HalAdcRead(0x01, HAL_ADC_RESOLUTION_12); // Spare A/D chan - use for battery measurement later
  
         // Turn on the test mode to enable temperature measurement 
         // from the CC2544's internal temp sensor
         ATEST=1; // ATEST.ATEST_CTRL=0x01;
         TR0=1;   //  TR0.ADCTM=1;
        
         HalAdcSetReference(0); // use internal ref voltage (1.15 V)
         //HalAdcSetReference ( 0x80); // use AVDD5 pin for ref
         
         // CC2541 Internal temp sensor is A/D input 14 (0x0e)
         tempvalCC2541 = HalAdcRead(0x0E, HAL_ADC_RESOLUTION_12); 

         /* Turn off test modes */
         TR0=0; //        TR0.ADCTM=0;
         ATEST=0;

        // The analog temperature sensor in the CC2544 should give back a value 
        // of 1480 at 25 degrees C and VDD=3, 
        // and will change by a value of 4.5 per degree C
        //     
        // So, to get temperature in 0.1 degrees C units, consider the 
        // following formula:
        //  
        tempval2 = tempvalCC2541-1480;
        tempvalCC2541 = (int16) (250.0 + (tempval2/4.5));
      
        HalAdcSetReference(0); // use internal ref voltage (1.15 V)
          
        // Pick up VDD divided by 3
        vdd_div_3 = HalAdcRead(0x0F, HAL_ADC_RESOLUTION_12); // VDD/3
        // Convert to millivolts (and get rid of the divide by 3, since we're doing math
        // vdd = (int) (1.15*vdd_div_3*3.0*1000.0 / 2047.0); // convert to millivolts
        // vdd = (int) (vdd_div_3 * 1.6853932584269662921348314606742); // more precisely
        vdd = (int) (vdd_div_3 * 1.6853); // close enough
        
        // Pick up the spare A/D input
        HalAdcSetReference (0x40); // use AIN7 for ref
        spare = HalAdcRead(0x01, HAL_ADC_RESOLUTION_12); 

        updateSensorData ((uint16)timeval, (uint16)tempval, (uint16)sensorval, (uint16)tempvalCC2541, (uint16)vdd, (uint16)spare);
        DataReadyFlag = 1;
        
        #endif
       
         // Set the light control I/O (LightOn=1 =>  P1_1=0)
        nuSOCKET_updateLight();
        
        // Also, set P1_0 (the LED) as an output, and drive low  
        P1DIR = P1DIR | 0x01; 
        P1 = P1&0xFE;

        
        return (events ^ 1);;
    }
    
    return (0);
} // end DataUpdate_ProcessEvent()
Exemplo n.º 8
0
	int main(void)
	{
		initADCPotentiometer(); //Initialize ADC for Potentiometer
		initUART(); //Initialize UART
		initLCD();  //Initialize LCD
		TRISDbits.TRISD6 = 1; //Botão
		TRISDbits.TRISD13 = 1; 		
		TRISAbits.TRISA0 = 0; //Led
		long int i = 0;
		char buff[100];			  	//Support buffer
		char password[100];          //Buffer that stores the password
		int potentiometerValue = 0; //Value of potentiometer
		int temperatureValue = 0;   //Value of temperature
		int alarm = 0;
		int enteredPassword = 0;
		long int flux = 20000;
		int eraseBuff = 0;
	
	
	
		while(1){
	
			/***************** Potentiometer Value **************/
				AD1PCFG = 0xFFDF;
				AD1CHS = 0x0005; 
				AD1CON1bits.SAMP = 1; 		// start sampling...
				for( i = 0 ; i < 200 ; i++){}; // Ensure the correct sampling time has elapsed before starting conversion.
				AD1CON1bits.SAMP = 0; 		// start Converting
				while (!AD1CON1bits.DONE); 	// conversion done?
				potentiometerValue = ADC1BUF0; // yes then get ADC value
				sprintf(buff,"P: %4d",potentiometerValue);
			/***************** Potentiometer Value **************/	
	
			/***************** Temperature Value ****************/
				AD1PCFG = 0xFFFB;
				AD1CHS = 0x0002; 
				AD1CON1bits.SAMP = 1; 		// start sampling...
				for( i = 0 ; i < 200 ; i++){}; // Ensure the correct sampling time has elapsed before starting conversion.
				AD1CON1bits.SAMP = 0; 		// start Converting
				while (!AD1CON1bits.DONE); 	// conversion done?
				temperatureValue = ADC1BUF0; // yes then get ADC value
				temperatureValue = convertTemp(temperatureValue, 1);
				sprintf(buff,"T: %4d",temperatureValue);
			/***************** Temperature Value ****************/
	
			/******************* UART Receiving ***************/
			if(U2STAbits.URXDA){ //If there is something to receive
				char c = getcharUART();
					if(c == 'T' || c == 't'){
						putcharUART(c);
						putstringUART("\n");
						sprintf(buff,"Temperature: %d\n", temperatureValue); //buff is the pointer to an array of char elements where the resulting C string is stored.
						putstringUART(buff); //Sends the temperature value to UART in normal state
						}
					
					if(c == 'P' || c == 'p'){
						putcharUART(c);
						putstringUART("\n");
						sprintf(buff,"Potentiometer: %d\n", potentiometerValue); //buff is the pointer to an array of char elements where the resulting C string is stored.
						putstringUART(buff); //Sends the potentiometer value to UART in normal state
					} 	
			}
			/******************* UART Receiving ***************/
			
			/******************* Set Sprinklers Flux ***************/
			if(potentiometerValue >= 0 && potentiometerValue <= 200){
				flux = 4000;
			}
			if(potentiometerValue > 200 && potentiometerValue <= 400){
				flux= 2350;
			}
			if(potentiometerValue > 600 && potentiometerValue <= 800){
				flux = 1000;
			}
			if(potentiometerValue > 800 && potentiometerValue <= 1023){
				flux = 750;
			}
			if(potentiometerValue > 1023){
				flux = 100;
			}
			/******************* Set Sprinklers Flux ***************/
	
	
			/******************* Set Led's Blinking if alarm is ON ***************/
			if(alarm == 1){
				PORTAbits.RA0 = 1; //LED On
				for( i = 0 ; i < flux ; i++){}; //Time that the LED stays on
				PORTAbits.RA0 = 0; //LED  Off
				for( i = 0 ; i < flux ; i++){}; //Time that LED stays off
			}
			/******************* Set Led's Blinking if alarm is ON ***************/
	
			/******************* Set Alarm State ***************/
			
			if(temperatureValue >= 8 && alarm == 0){
				alarm = 1;
				putstringUART(stringAlarmeAtivadoUART);
				putstringUART(stringAlarmeUART);
				clearLCD();
				homeLCDL1();
				putStringLCD(stringAlarmeAtivadoLCD);
				homeLCDL2();
				putStringLCD(stringAlarmeLCD);
			}
			else if(temperatureValue < 8 && alarm == 1){
					putstringUART(stringSystemClearUART);
					clearLCD();
					homeLCDL1();
					putStringLCD(stringSystemClearLCD);
					homeLCDL2();	
					sprintf(buff,"T: %d     P: %d", temperatureValue, potentiometerValue); //buff is the pointer to an array of char elements where the resulting C string is stored.
					putStringLCD(buff);
				}
			else if(temperatureValue < 7 && alarm == 0){
					clearLCD();
					homeLCDL1();
					putStringLCD(stringSituacaoNormal);
					homeLCDL2();	
					sprintf(buff,"T: %d     P: %d", temperatureValue, potentiometerValue); //buff is the pointer to an array of char elements where the resulting C string is stored.
					putStringLCD(buff);
				}
			/******************* Set Alarm State ***************/
			
			
			/******************* Reset Alarm ***************/
	
			if(alarm == 1 && !PORTDbits.RD6 && !PORTDbits.RD13){  
				enteredPassword = 0;
				putstringUART(stringEnterPasswordUART);
				
				while(!enteredPassword){
					if(U2STAbits.URXDA){ //If there is something to receive
						char c;
						int x = 0;
						
						while(x < 11){
							c = getcharUART();
							buff[x] = c;
							x++;
						}	
						buff[x] = '\0';					
							
				  			if (strcmp(buff, stringPassword) == 0){
								  putstringUART(stringCarriageReturnLineFeed);
								  putstringUART(stringCorrectPasswordUART);
								  putstringUART(stringSystemClearUART);			  
							      clearLCD();
								  homeLCDL1();
								  putStringLCD(stringCorrectPasswordLCD);
								  homeLCDL2();    
								  putStringLCD(stringSystemClearLCD);
								  alarm = 0;
							} else{
								  putstringUART(stringCarriageReturnLineFeed);
								  putstringUART(stringWrongPasswordUART);
							      putstringUART(stringAlarmeAtivadoUART);
								  clearLCD();
								  homeLCDL1();
								  putStringLCD(stringWrongPasswordLCD);
								  homeLCDL2();    
								  putStringLCD(stringAlarmeAtivadoLCD);
							}							
						  enteredPassword = 1;
					}	
				}
			}
			/******************* Reset Alarm ***************/
			
		}
	}
Exemplo n.º 9
0
int main(void)
{
  /* MCU Configuration----------------------------------------------------------*/

  HAL_Init();	  													/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  SystemClock_Config(); 									/* Configure the system clock */
	ADC1_Config(); 													/* configure ADC1 */
	Display_GPIO_Config(); 									/* Configure 7-Segment Displays */
	Alarm_GPIO_Config(); 										/* Configure alarm pins */	
	initLCD(); 															/* configure LCD */

	/* print temperature on the first line of the LCD */
	returnHome(); 													/* just makes sure that start writing at the right place */
	LCD_WriteString("  Temperature"); 			/* The 2 initial space are for centering */
	

	
	adcState = malloc(sizeof(kalmanState)); /* Init Kalman Filter */
	kalmanInit(adcState, INIT_q, INIT_r, INIT_x, INIT_p, INIT_k);

	/* main program to run in this infinite loop */
	while (1)	{

		
		if (adcTimer >= ADC_PERIOD) { 								/* 100Hz */
			adcTimer = 0;
			HAL_ADC_Start(&ADC1_Handle); 								/* start ADC conversion */
			
			/* wait for the conversion to be done and get data */
			if (HAL_ADC_PollForConversion(&ADC1_Handle, 1000000) == HAL_OK) { 
				adc_val = HAL_ADC_GetValue(&ADC1_Handle); /* get the value */
				
				kalmanUpdate(adcState, adc_val); 					/* filter the data and update the filter parameters */
				/* DON'T DELETE printf for matlab script */
				//printf("%f,%f,%f,%f,%f,%f\n",adc_val, adcState->q,adcState->r, adcState->x, adcState->p, adcState->k);
				
				temp = convertTemp(adcState->x); 					/* convert the filterd value of the ADC into temperature */
				
				/* Alarm triggering  */
				if (temp > THRESHHOLD_TEMP) {
					if ( filterAlarmCounter > 5 ){ 					/* 5 consecutive to avoid false positive */
						trigger_alarm();
					}
					else {
					filterAlarmCounter++;
					}
				} 
				else {
					shutoff_alarm();
					filterAlarmCounter = 0;
				}
		
				/* Update Measurement to Display at 2Hz */
				if (updateMeasureForDisplayTimer >= UPDATE_MEASURE_PERIOD) {
					updateMeasureForDisplayTimer = 0; 						/* reset the displayTimer tick */
					displayTemp = temp;
					displayTemp = floor(10 * displayTemp) / 10; 	/* truncate to 1 decimal without rounding */
								
					/* LCD DISPLAY */	
					SetAdress(64); 																/* go to line 2 of LCD */
					sprintf(tempToLCD, "     %.1f", displayTemp); /* convert the float to a string and formats it */
					LCD_WriteString(tempToLCD);										/* print value to the LCD display */
					/* LCD DISPLAY END */
				}
			}
		}
		
		/* here display runs at DISPLAY_7_SEGMENT_PERIOD speed, but displayTemp gets updated at 2Hz */
		if(display7segTimer >= DISPLAY_7_SEGMENT_PERIOD) {
			display7segTimer = 0;
			display(displayTemp); 														/* display on 7-segment display */
		}
	
	}
}