void _send_nibble(unsigned char data) {
    LCD_DATA_W &= ~DATA_MASK;       // clear old data bits
    LCD_DATA_W |= DATA_MASK & data; // put in new data bits

    // clock
    Delay100TCYx(4);
    LCD_EN = 1;
    Delay100TCYx(4);
    LCD_EN = 0;
    Delay100TCYx(4);
}
Exemplo n.º 2
0
void main(void)
{
	unsigned char data = 0;
	signed char err0 = 0, err1 = 0, err2 = 0;
	Delay100TCYx(10); //let the device startup

	//initialize uart
	usart_init();
	spi_init();
	printf("Var is %i\r\n", data);
	printf("Starting\r\n");
	printf("SSPCON1 is x%x\r\n", SSPCON1);
	printf("SSPADD is x%x\r\n", SSPADD);
	printf("SSPSTAT is x%x\r\n", SSPSTAT);

	PORTCbits.RC2 = 1;	// pin high
	while(1){
		PORTCbits.RC2 = 0;	// CS low
		Delay1TCY();		// delay at least 5 ns
		WriteSPI(0x80);		// b'10000000, read single byte 000000
		//WriteSPI(0xB2);		// b'10101100, read single byte 
		data = ReadSPI();
		PORTCbits.RC2 = 1;	// CS high
		Delay1TCY();		// delay at least 5 ns
		//data = data>>1;
		printf("Data is 0x%02X \r\n", data);
	}	
}
Exemplo n.º 3
0
void main()
{
	LEDTris = 0;//Set LED Pin data direction to OUTPUT
	LEDPin = 1;//Set LED Pin

	OpenUSART( USART_TX_INT_OFF  &
           USART_RX_INT_OFF  &
           USART_ASYNCH_MODE &
           USART_EIGHT_BIT   &
           USART_CONT_RX     &
           USART_BRGH_HIGH,
           77); // 38400 bps, set your virtual com port to that speed!


	cls();
	hideCursor();
	while(1)
	{
		int i, carb0,carb1,carb2,carb3;
	    LEDPin = ~LEDPin;//Toggle LED Pin
		carb0 = ADC_call(0);
		carb1 = ADC_call(1);
		carb2 = ADC_call(2);
		carb3 = ADC_call(3);

		i = 1;
		while(i--)
			Delay100TCYx(5);
	}

}
/*call function release*/
void release(void)
{
	/*	this function halts execution 
	 *until switchs are released
	 */
	
	unsigned char count = 0;

	
	while(1)
	{
		
		Delay100TCYx(100);
		if(SWITCH_0==1&&SWITCH_1==1)
			count++;
		else
			count = 0;
		

		if(count >= 5)
			break;

	}//end while

}//end release
Exemplo n.º 5
0
void main(void)
{
	//timer vars
	int result;
	float final_result;

	Delay100TCYx(10); //let the device startup
	usart_init();
	i2c_init();
	printf("Starting\r\n");


	// let sonar initialize, delay 250 ms
	Delay1KTCYx(625);
	TRISBbits.TRISB3 = 1;	// data pin input
	
	while(1)
	{
		while(PORTBbits.RB3 == 0);
		// configure timer0
		OpenTimer0(TIMER_INT_OFF & T0_16BIT & T0_SOURCE_INT & T0_PS_1_1);
 		WriteTimer0( 0 );         // restart timer
		while(PORTBbits.RB3 == 1);
		//Delay1TCY();
		result = ReadTimer0();    // read timer
		printf("Timer is %u \r\n", result);
		final_result = (float)result / (float)(2.5*147);
		printf("X / (4*147) = %i \r\n", (int)final_result);
		
	}
	
}
Exemplo n.º 6
0
void lcd_init(){
  PIN_LCD_E  = 0;
  PIN_LCD_RS = 0;
  PIN_LCD_D4 = 0;
  PIN_LCD_D5 = 0;
  PIN_LCD_D6 = 0;
  PIN_LCD_D7 = 0;

  LCD_DELAY_LONG();

  lcd_send_nibble(3);
  Delay10KTCYx(6); //5ms

  lcd_send_nibble(3);
  Delay100TCYx(25); //200us

  lcd_send_nibble(3);
  Delay100TCYx(25); //200us

  lcd_send_nibble(2);
  Delay10KTCYx(6); //5ms

  lcd_send_nibble(2);
  lcd_send_nibble(8);      //4bits 2lines
  Delay10KTCYx(6); //5ms

  lcd_send_nibble(0);
  lcd_send_nibble(8);      //no shift, hide cursor
  Delay10KTCYx(6); //5ms

  lcd_send_nibble(0);
  lcd_send_nibble(1);      //clear
  Delay10KTCYx(6); //5ms

  lcd_send_nibble(0);
  lcd_send_nibble(6);      //left to right
  Delay10KTCYx(6); //5ms

  lcd_send_nibble(0);
  lcd_send_nibble(0xC);    //turn on
  Delay10KTCYx(6); //5ms

  LCD_DELAY_LONG();

}
Exemplo n.º 7
0
/*******************************
 * DisplayLCD(char * tempPtr, int init):
 * This subroutine is called with a string to be displayed on the LCD
 * It sends the bytes of the string to the LCD.  The first
 * byte sets the cursor position.  The remaining bytes are displayed, beginning
 * at that position.
 * This subroutine expects a normal one-byte cursor-positioning code, 0xhh, or
 * an occasionally used two-byte cursor-positioning code of the form 0x00hh. The
 * init variable defines if the LCD is being initialized (init = 1) or if just
 * displaying a message on the LCD (init = 0)
 *******************************/
void DisplayLCD(char * tempPtr, int init)
{
        char currentChar;
        
        

        if (init == 1)
        {
            Delay1KTCYx(250);               // Wait 0.1 s to bypass LCD startup
            PORTEbits.RE0 = 0;              // Drive RS pin low for cursor-positioning code
            while (*tempPtr != 0)           // if the byte is not zero
            {
              currentChar = *tempPtr;
              PORTEbits.RE1 = 1;            // Drive E pin high
              PORTD = currentChar;          // Send upper nibble
              PORTEbits.RE1 = 0;            // Drive E pin low so LCD will accept nibble
              Delay100TCYx(250);			// Wait 10 ms
              currentChar <<= 4;            // Shift lower nibble to upper nibble
              PORTEbits.RE1 = 1;            // Drive E pin high again
              PORTD = currentChar;          // Write lower nibble
              PORTEbits.RE1 = 0;            // Drive E pin low so LCD will process byte
              Delay100TCYx(250);            // Wait 10 ms
              tempPtr++;                    // Increment pointerto next character
            }
        }
        else
        {
            PORTEbits.RE0 = 0;              // Drive RS pin low for cursor-positioning code
            while (*tempPtr)                // if the byte is not zero
            {
              currentChar = *tempPtr;
              PORTEbits.RE1 = 1;            // Drive E pin high
              PORTD = currentChar;          // Send upper nibble
              PORTEbits.RE1 = 0;            // Drive E pin low so LCD will accept nibble
              currentChar <<= 4;            // Shift lower nibble to upper nibble
              PORTEbits.RE1 = 1;            // Drive E pin high again
              PORTD = currentChar;          // Write lower nibble
              PORTEbits.RE1 = 0;            // Drive E pin low so LCD will process byte
              Delay10TCYx(10);              // Wait 40 usec
              PORTEbits.RE0 = 1;            // Drive RS pin high for displayable characters
              tempPtr++;                    // Increment pointerto next character
            }

        }
}
Exemplo n.º 8
0
/******************************************************************************
	int Delay()
	This function is called to create a 1ms delay multiplied 
	by the integer given to it to make a specific delay time
******************************************************************************/
void Delay()
{   
	int delay = 2;
    int index = 0;

	for( index = 0; index < delay; index++ )
	{
		Delay100TCYx(25);		// each delay cost .001 of a second (1ms)
	}
	
	
}
Exemplo n.º 9
0
void DelayRXBitUART (void)		// p/ detalhes do delay veja no cabeçalho deste arquivo
{
	Delay1KTCYx (1);
	Delay100TCYx (2);
	Delay10TCYx  (2);
	nop() ;
	nop() ;
	nop() ;
	nop() ;
	nop() ;
	nop() ;

}//
Exemplo n.º 10
0
void sendString(rom char* data, int length)		///Works
{
	int i;
	unsigned char temp;
	Delay10KTCYx(100);
	while(BusyUSART());
	for(i = 0; i < length; i++)
	{
		temp = data[i];
		putcUSART(temp);
		Delay100TCYx(100);
	}	
}
void sawtooth (unsigned char m)
{
PORTD=0x00;
                                                                                                                                                                                                                                                                                                                                                                                                                            
while (SWITCH_1==1) //if RA5 not pressed
{

PORTD=PORTD+4;//output sawtooth
Delay100TCYx(m);//f=(double) 1/ (1/15600 + n*0.000709+0.00007);

}

}
Exemplo n.º 12
0
//----------------------------------------------------------------------------------
char sht_measure(unsigned char mode)
//----------------------------------------------------------------------------------
// makes a measurement (humidity/temperature) with checksum
{ 
  unsigned error=0;
  unsigned int i;
  unsigned char LSB;
  unsigned char MSB;
  unsigned char tmp = 0;
  unsigned char bits = 8;

  sht_crc_init();
  sht_transstart();                   //transmission start
  switch(mode){                     //send command to sensor
    case TEMP	: error+=sht_write_byte(MEASURE_TEMP); sht_crc_shuffle_byte(MEASURE_TEMP);break;
    case HUMI	: error+=sht_write_byte(MEASURE_HUMI); sht_crc_shuffle_byte(MEASURE_HUMI);break;
    default     : break;	 
  }
  for (i=0;i<40000;i++) {
  	if(DATA_IN==0) {
            break; //wait until sensor has finished the measurement
        }
	Delay100TCYx(4);      //50 us
  }
  
  if(DATA_IN)
  {
      error+=1;                // or timeout (~2 sec.) is reached
  }
  MSB  = sht_read_byte(ACK);    //read the first byte (MSB)
  sht_crc_shuffle_byte(MSB);
  LSB  = sht_read_byte(ACK);    //read the second byte (LSB)
  sht_crc_shuffle_byte(LSB);
  CurrentValue = MSB * 256 + LSB;
  CheckSum = sht_read_byte(noACK);  //read checksum

  	while( bits--)
	{
		tmp >>=1;
		if( sht_crc & 0b10000000)
			tmp |= 0b10000000;
		sht_crc <<=1;
	}

  if (tmp != CheckSum) {
      SHTdevice_table[CurrentSensorIndex].crc++;
      return 1;
  }
  return error;
  
}
void main(void)
{
    unsigned char outputData[2];
    unsigned int result = 0;
    unsigned char data = 0;
    Delay100TCYx(10); //let the device startup
    usart_init();
    i2c_init();
    printf("Starting\r\n");



    /*	******************************* Compass code and ADSL Code ********************** */
    //Tests compass by getting slave address
    //it should be 0x21
    Delay10TCYx(0);
    printf("Slave Address: 0x%02X \r\n", HMC6352_getSlaveAddress());
    HMC6352_setOpMode(HMC6352_CONTINUOUS , 1, 20);
    printf("Op Mode: 0x%02X \r\n", HMC6352_getOpMode());
    printf("Output Mode: 0x%02X \r\n", HMC6352_getOutputMode());


    while(1)
    {
        StartI2C();
        WriteI2C((HMC6352_I2C_ADDRESS << 1) | 1);
        outputData[0] = ReadI2C();
        NotAckI2C();
        outputData[1] = ReadI2C();
        NotAckI2C();
        StopI2C();

        result = outputData[0];
        result = result << 8;
        result = result | outputData[1];

        /*
        if(data2 <275 || data2 > 3599)
        	printf("North \r\n");
        */

        printf("Heading: %i \r\n", result-255);
    }

}
Exemplo n.º 14
0
/*
 * move the motor to the given location
 */
void move(int location) {
    int posn = 0;
    ADCON0bits.GO = 1; //ConvertADC();
    while (0 == ADCON0bits.GO); // spin while busy
    posn = ((((unsigned int)ADRESH)<<8)|(ADRESL) - location) / ADC_PRECISION;
    while (0 != posn) { // move forward or back depending on the location
        if (posn < 0) {
            adjustMotor(1);
        } else {
            adjustMotor(0);
        }
        Delay100TCYx(1);
        ADCON0bits.GO = 1; //ConvertADC(); // determine new location and if any change is needed
        while (0 == ADCON0bits.GO); // spin while busy
        posn = ((((unsigned int)ADRESH)<<8)|(ADRESL) - location) / ADC_PRECISION;
    }
    PORTDbits.RD6 = 1; // lock the reader
    PORTDbits.RD7 = 1;
}
void sinewave (unsigned char m)
{ unsigned char i,n;
 unsigned char s[31];
float PI=3.141593;
n=31;//32 samples
for(i=0;i<=n;i++)
{s[i]=(unsigned char)(sin(2*PI/(n+1)*i)*127+128);
}
while (SWITCH_1==1)//if RA5 not pressed 
{
for(i=0;i<=n;i++)
{
PORTD=s[i];
//PORTD=(unsigned char)(sin(2*PI/(n+1)*i)*127+128);//output sine wave
Delay100TCYx(m);//f=(double) 1/ (1/44.6 + n*0.00035);
}

}
}
void transmit_data( unsigned char *TX_Data )
{
    unsigned char i, data, cmd;   
    
    SPI_CSN = 0;
    
	//clear previous ints
  	spi_Send_Read(0x27);
 	spi_Send_Read(0x7E);
	SPI_CSN = 1;
    SPI_CSN = 0;
    
	//PWR_UP = 1
   	spi_Send_Read(0x20);
 	spi_Send_Read(0x3A);
    SPI_CSN = 1;
    SPI_CSN = 0;
    
    //clear TX fifo
    //the data sheet says that this is supposed to come up 0 after POR, but that doesn't seem to be the case
   	spi_Send_Read(0xE1);
    SPI_CSN = 1;
    SPI_CSN = 0;
    
	//fill byte payload
   	spi_Send_Read(0xA0);
   	
	for (i = 0; i< RF_PAYLOAD; i++)
		spi_Send_Read( TX_Data[i] );

    SPI_CSN = 1;
    
    //Pulse CE to start transmission
    SPI_CE = 1;
    Delay100TCYx(2);
    SPI_CE = 0;
}//
Exemplo n.º 17
0
void main(void) {

    char mensagem[]="Pronto > ";

    ADCON1=0xF;    // torna todas portas AN0 a AN12 como digitais
                    // na PIC18F2525 somente AN0 a AN4 e AN8 a AN12
                    // nas PICs com 40 pinos, todos ANs de 0 a 12
                    //
                    // PCFG3:PCFG0: A/D Port Configuration Control bits
                    // Note 1:
                    // The POR value of the PCFG bits depends on the value of
                    // the PBADEN Configuration bit. When PBADEN = 1,
                    // PCFG<2:0> = 000; when PBADEN = 0, PCFG<2:0> = 111.


    TRISB=0;    // output do LCD na PORTB / LCD output in PORTB
    initLCD();  // inicia comandos de configuracao do LCD
                // LCD init commands
    /*
     * obs: a biblioteca XLCD.H da PLIB para PIC18, considera como default o LCD
     * conectado na PORTB com as seguintes pinagens:
     *
     Lower Nibble = LCD DATA in PORT B0, B1, B2, B3 (DATA_PORT)
     RW_PIN   in B6   		( PORT for LCD RW , can also be grounded)
     RS_PIN   in B5   		( PORT for LCD RS )
     E_PIN    in B4  		( PORT for LCD Enable Pin )
     */

    TRISA2=1;   // entrada do BOTAO / push-BOTTON input

    TRISC0=0;   // led verde 1
    TRISC1=0;   // led verde 2
    TRISC2=0;   // led verde 3
    TRISC3=0;   // led verde 4
    TRISC4=0;   //buzzer
    TRISC5=0;   //led vermelho

    LED_VERMELHO=1;
    LED1=1;

    Delay10KTCYx(1000);


    while(BusyXLCD());
    WriteCmdXLCD(0x01); // comando para limpar LCD / command to clear LCD

    while(BusyXLCD());
    putrsXLCD ("Serial IO EUSART"); // somente logotipo / just a start logo
    SetDDRamAddr(0x40);     // Linha 2 do Display LCD / second line of LCD

    while(BusyXLCD());
    putrsXLCD ("RS232 PIC18F2525"); // somente logotipo / just a start logo

    SetDDRamAddr(0x00); // volta cursor para linha 0 e posicao 0 do LCD
                        // put cursor in position 0,0 of LCD

    contadorDisplay=0;      // zerando a posicao de caracteres do LCD
                            // reseting the LCD character count

    // Habilitacao dos pinos C6 e C7 para uso da EUSART (explicacao abaixo):
    // Enabling pins C6 and C7 for EUSART (explanation bellow):
    TRISC6=1;
    TRISC7=1;
    RCSTAbits.SPEN=1;
    /*
    The pins of the Enhanced USART are multiplexed
    with PORTC. In order to configure RC6/TX/CK and
    RC7/RX/DT as a USART:
    ? SPEN bit (RCSTA<7>) must be set (= 1)
    ? TRISC<7> bit must be set (= 1)
    ? TRISC<6> bit must be set (= 1)
    Note:
    The EUSART control will automatically
    reconfigure the pin from input to output as
    needed.

     */


    LED1=1;
    LED2=0;
    LED_VERMELHO=0;

    CloseUSART();   // fecha qualquer USART que estaria supostamente aberta antes
                    // just closes any previous USART open port

    
    Delay10KTCYx(1); //Passing 0 (zero) results in a delay of 2,560,000 cycles
    Delay10KTCYx(1000);

    //PORTC=1; Delay10TCYx(50); PORTC=0;

    OpenUSART(  USART_TX_INT_OFF &
                USART_RX_INT_ON &
                USART_ASYNCH_MODE &
                USART_EIGHT_BIT &
                USART_CONT_RX &
                USART_BRGH_LOW,
                51
                );
    // Baud Rate "51" para 2400bps @ 8mhz em modo assincrono
    // de acordo com DS39626E-page 207 do Datasheet em PDF da PIC18F2525

    // These are common comands for 2400 bps running at 8 mhz, assyncronous mode
    // just as being showed in PIC18F2525 Datasheet (DS39626E-page 207)

    //baudUSART (BAUD_8_BIT_RATE | BAUD_AUTO_OFF);

    // page 1158 do pic18_plib.pdf (capitulo 8.17.1.3.3 baud_USART)
    // Set the baud rate configuration bits for enhanced usart operation
    // These functions are only available for processors with
    // enhanced usart capability (EUSART)
    /*
          The Enhanced Universal Synchronous Asynchronous
    Receiver Transmitter (EUSART) module is one of the
    two serial I/O modules. (Generically, the USART is also
    known as a Serial Communications Interface or SCI.)
    The EUSART can be configured as a full-duplex
    asynchronous system that can communicate with
    peripheral devices, such as CRT terminals and
    personal computers. It can also be configured as a half-
    duplex synchronous system that can communicate
    with peripheral devices, such as A/D or D/A integrated
    circuits, serial EEPROMs, etc.
    The Enhanced USART module implements additional
    features, including automatic baud rate detection and
    calibration, automatic wake-up on Sync Break recep-
    tion and 12-bit Break character transmit. These make it
    ideally suited for use in Local Interconnect Network bus
    (LIN bus) systems. (DS39626E-page 201)
     */


    INTCONbits.PEIE = 1;  // interrupcoes para perifericos
    INTCONbits.GIE  = 1;  // interrupcoes globais

    while(BusyUSART());
    putrsUSART("\n\rLed1 e LedVermelho = Interrupcao; Led2 = while wait; Led3/4 = Err");

    while(BusyUSART());
    putrsUSART("\n\rComandos ^E (echo), ^P (lcd), ^L (cls), ^S (status)");

    while(BusyUSART());
    putrsUSART("\n\rTerminal Serial: ");

    while(BusyUSART());
    putsUSART(mensagem);

    LED_VERMELHO=0;
    LED1=1;
    LED2=1;
    
    //LED4=1;

    while (1){

        //LED4=RCIF;
        // o LED4 mostra o status da Interrupcao da RX Serial
        // Led4 shows the status of RX interrupt
      
        //LED3=TXIF;
        // o LED3 mostra o status da suposta interrupcao de TX
        // Led3 shows the suposed TX interrupt state

        LED3=OERR;

        LED4=FERR;
        /*
        bit 2 FERR: Framing Error bit
        1 = Framing error (can be cleared by reading RCREG register and receiving next valid byte)
        0 = No framing error
         *
        bit 1 OERR: Overrun Error bit
        1 = Overrun error (can be cleared by clearing bit, CREN)
        0 = No overrun error
         */


        LED2=~LED2;
        Delay10KTCYx(10);
        // quando esta no modo de espera de tecla* (interrupcao), fica piscando
        // os tres leds para demonstrar a despreocupacao do loop while
        // *na verdade essa espera de tecla eh o RX da serial

        // when being in wait mode (for interrupt *keypress )just flashes the tree
        // leds to demonstrate the un-commitment of while loop to keypress
        // * this keypress event is the serial RX



        // Check for overrun error condition
		if (OERR == 1)
		{
			// Clear the overrun error condition
                        BUZZ=1;
			CREN = 0;
			CREN = 1;
                        Delay100TCYx(10); BUZZ=0;
                }
        LED_VERMELHO = RCIF;    // buffer de recepcao cheio

    }

    return;
}
Exemplo n.º 18
0
 void DelayPORXLCD(void)   // minimum 15ms
 {
 Delay100TCYx(0xA0);   // 100TCY * 160
 return;
 }
Exemplo n.º 19
0
 void DelayXLCD(void)     // minimum 5ms
 {
 Delay100TCYx(0x36);      // 100TCY * 54
 return;
 }
Exemplo n.º 20
0
void main(void)
{
    WDTCON = 0x00;


    
    //TRISA = 0xC0;
    TRISB = 0xFF;
    TRISC = 0xFF;

    UartTxCnt = 0;
    UartRxCnt = 0;

    CanRxBuff = 0;
    UartTxBuff = 0;

	// Initialize TIMER0
    INTCON2bits.TMR0IP = 0; //Timer0 INT-LOW
    OpenTimer0(TIMER_INT_ON & T0_16BIT & T0_SOURCE_INT & T0_PS_1_128);
	//  24Mhz/4/128 := 46875 -> 65536 - 46875 = 18661
    WriteTimer0(49911); // 1Sec interval at 8Mhz
    
/*    EEAddres.Bytes[0] = Read_b_eep(0);
    EEAddres.Bytes[1] = Read_b_eep(1);
    EEAddres.Bytes[2] = Read_b_eep(2);
    EEAddres.Bytes[3] = Read_b_eep(3);
    EEAddres.SE_ID = 0x20123456;
*/

	// Initialize CAN module with no message filtering
    // 8MHz Fosc 250Kb/s
    // 8MHz -> 2MHz @ 250Khz = 8Tq (1+2+3+2)
    CANInitialize(1 ,0x02 ,2 ,3 ,2 , CAN_CONFIG_VALID_XTD_MSG); //256kb at 8Mhz crystal
    /*CANSetOperationMode(CAN_OP_MODE_CONFIG);
    CANSetFilter(CAN_FILTER_B1_F1, Can_bootF.SE_ID, CAN_CONFIG_XTD_MSG);
    CANSetFilter(CAN_FILTER_B1_F2, Can_nodeF.SE_ID, CAN_CONFIG_XTD_MSG);
    CANSetMask(CAN_MASK_B1, Can_Mask1.SE_ID, CAN_CONFIG_XTD_MSG);
    CANSetFilter(CAN_FILTER_B2_F1, Can_addrLO.SE_ID, CAN_CONFIG_XTD_MSG);
    CANSetMask(CAN_MASK_B2, Can_Mask2.SE_ID, CAN_CONFIG_XTD_MSG);
	*/    
	CANSetOperationMode(CAN_OP_MODE_NORMAL);

	//ADC configuration
	//reference is connected to A0
	//voltage output connected to A1
	LATA = 0x00;
	PORTA=0;
	TRISA=0xFF; //A port as input
    ADCON1 = 0b00111101;//VSS,VDD ref. AN0 analog only
	//ADCON2 = 0b00001001;//ADCON2 setup: Left justified, Tacq=2Tad, Tad=2*Tosc (or Fosc/2)
	ADCON2 = 0b10101011;
	ADCON0bits.ADON = 0x01;//Enable A/D module
	
    INTCONbits.GIE = 1; //enable global interrupts
    Tcombo int2byte;
					UartRx_Msg.Data[4] = 1;//CanRx_Msg.Data[0];
	  				UartRx_Msg.Data[5] = 2;//CanRx_Msg.Data[0];
					UartRx_Msg.Data[6] = 3;//CanRx_Msg.Data[7];
	  				UartRx_Msg.Data[7] = 4;//CanRx_Msg.Data[7];

    while(1)
    {
        ClrWdt();
		/********************************/
		//cobtinuasly reading of current*/
		/********************************/		
		//ADC chanel A0	- voltage	
	    ADCON0bits.CHS0 = 0;//clear ADCON0 to select channel 0 (AN0)
	    ADCON0bits.CHS1 = 0;//clear ADCON0 to select channel 0 (AN0)
		ADCON0bits.CHS2 = 0;//clear ADCON0 to select channel 0 (AN0)
	    ADCON0bits.CHS3 = 0;//clear ADCON0 to select channel 0 (AN0)
		Delay100TCYx (2);
	    ADCON0bits.GO = 1;
	    while (ADCON0bits.GO);  //wait for conversion
		current_ad_value=ADRES;
	    ClrWdt();    
		
		Delay100TCYx (2);
		//ADC chanel A1 - rederence		    
		ADCON0bits.CHS0 = 1; //select channel 1 (AN1)
	    Delay100TCYx (2);
	    ADCON0bits.GO = 1;
	    while (ADCON0bits.GO);  //wait for conversion
		reference_ad_value= ADRES;
	 	
		//delta ADC = reference votlatge - real voltage
		//we filter it thru buffer
		count++;
		if(count>=100) count=0;
		delta_ad[count] = reference_ad_value-current_ad_value;
	
		if (UTicTac >= 1) {
		    UTicTac = 0;
            
			//current conversion
			//I=1.6V*200/1024*0.625  * delta_ad ==0.52083333333333333333333333333333 *delta_ad
			//reference votlatge - real voltage
			current=0;
			for(char i=0;i<100;i++){
				current+=delta_ad[i];
			}
			//current *= 0.0052083; //above formula /100

			current *= 0.00463541637; //above formula with correction factor of 0.89
		

			int2byte.Int = (int)current;
	  		UartRx_Msg.Data[0] = int2byte.Char[1];
	  		UartRx_Msg.Data[1] = int2byte.Char[0];

			//capcity
			capacity += (current/3600);	
			int2byte.Int=(int)capacity;
   			UartRx_Msg.Data[2] = int2byte.Char[1];
   			UartRx_Msg.Data[3] = int2byte.Char[0];

					
			// CAN adresses
		    UartRx_Msg.Address.SE_ID = 0x010000F2;
		    CANSendMessage(UartRx_Msg.Address.SE_ID, &UartRx_Msg.Data[0], 8, CAN_TX_PRIORITY_0 & CAN_TX_XTD_FRAME & CAN_TX_NO_RTR_FRAME);
			ClrWdt();

		}



        if (CANIsRxReady())                        // Check for CAN message
        {
            CANReceiveMessage(&CanRx_Msg.Address.SE_ID, &CanRx_Msg.Data[0], &CanRx_Msg.Length.Len, &RecFlags);
//            if ( RecFlags & CAN_RX_OVERFLOW )
//            {
//                                                 // Rx overflow occurred; handle it
//            }
            if ( RecFlags & CAN_RX_INVALID_MSG )
            {                                      // Invalid message received; handle it
            } 
            else
            {
               /* if ( RecFlags & CAN_RX_RTR_FRAME )
                {                                  // RTR frame received
                    //UartRx_Msg.Data[6]++;
			   		
					CanRxBuff++;
                    if (CanRxBuff >= BuffNO) 
                        CanRxBuff = 0; 
                }
                else
                {                                  // Regular frame received.
					//UartRx_Msg.Data[7]++;
			   		CanRxBuff++;
                    if (CanRxBuff >= BuffNO) 
                        CanRxBuff = 0; 

                    
                }*/
				    
					if(CanRx_Msg.Address.SE_ID==0x020000F2) capacity=(char)CanRx_Msg.Data[0];
					/*UartRx_Msg.Data[4] = CanRx_Msg.Data[0];
	  				UartRx_Msg.Data[5] = CanRx_Msg.Data[1];
					UartRx_Msg.Data[6] = CanRx_Msg.Data[6];
	  				UartRx_Msg.Data[7] = CanRx_Msg.Data[7];*/


            }
//            if ( RecFlags & CAN_RX_XTD_FRAME )
//            {
//                                                 // Extended Identifier received; handle it
//            }
//            else
//            {
//                                                 // Standard Identifier received.
//            }
//                                                 // Extract receiver filter match, if it is to be used
//            RxFilterMatch = RecFlags & CAN_RX_FILTER_BITS;
        }
    


                                             // Process received message
      /*  if ((BusyUSART() == 0) && (UartSync == 1))
        {
            if (UartTxCnt > 0)                   // Preveri èe posiljamo CAN telegram na UART
            {
                WriteUSART(CanRx_Msg[UartTxBuff].Array[UartTxCnt]);  // Pošlji znak
                UartTxCnt++;                     // poveèaj stevec za naslednji znak
                if ((UartTxCnt) >= (J1939_MSG_LENGTH + J1939_DATA_LENGTH)) // Preveri èe je zadni znak
                {
                    UartTxCnt = 0;               // Postavi na prvi znak
                    UartTxBuff++;                // Premakni na novi Buffer
                    if (UartTxBuff >= BuffNO)    // Preveri da nismo cez mejo
                        UartTxBuff =0;
                }
            }
            else
            {
                if (CanRxBuff != UartTxBuff)
                {
                    WriteUSART(CanRx_Msg[UartTxBuff].Array[UartTxCnt]);  // Pošlji ga na UART
                    UartTxCnt++;                // Poveèaj števec na naslednji znak
                }
            }
        }

        if (UartRxCnt >= (J1939_MSG_LENGTH + J1939_DATA_LENGTH)) // Ali imamo vse znake.
        {
            if (CANIsTxReady())                  // Preveri ali ja CAN prost
            {
//              void CANSendMessage(unsigned long id, BYTE *Data, BYTE DataLen enum CAN_TX_MSG_FLAGS MsgFlags);
                CANSendMessage(UartRx_Msg.Address.SE_ID, &UartRx_Msg.Data[0], 8, CAN_TX_PRIORITY_0 & CAN_TX_XTD_FRAME & CAN_TX_NO_RTR_FRAME);
                UartRxCnt = 0;                   // Pripravi za sprejem novega telegrama iz UART-a
                LATAbits.LATA5 = !LATAbits.LATA5;
            }
        }
        if DataRdyUSART()                        // Preveri ali v UART èaka nov znak
        {
            UTicTac = 0;
            tp_char = ReadUSART();               // Preber znak v polje
            if (UartSync)
            {
                UartRx_Msg.Array[UartRxCnt] = tp_char;
                UartRxCnt++;                     // in poveèaj stevec prebranih znakov iz UART-a
            }
            else
            {
                 if (tp_char == '#') 
                    UartSync = 1;
            }
        }

        if (UTicTac > 5)                         // Èe je števec èez mejo, telegram ni veljeven
        {
            UartRxCnt = 0;                       // Postavi na prvi znak v telegramu
            UTicTac = 0;
        }*/
    }                                            // Do this forever
}
Exemplo n.º 21
0
void DelayMS(UINT08 x)
{
	while(x--)Delay100TCYx(40);
}
Exemplo n.º 22
0
void high_isr(void)
{
	
	//Timer for servo
	if(INTCONbits.TMR0IF)  
	{						
		PORTBbits.RB3 = 1;
		if(servoState == 0){
			Delay1TCY();
  	 	  	Delay1TCY();
  	 	  	//Delay10TCYx(6);
		}else{
			Delay1TCY();
      		Delay1TCY();
      		Delay1TCY();
      		Delay1TCY();
      		Delay1TCY();
      		Delay1TCY();
      		Delay1TCY();
  	 	  	Delay10TCYx(5);
  	 	  	Delay100TCYx(4);
  		}	 
  		PORTBbits.RB3 = 0;	  
		INTCONbits.TMR0IF = 0;	// Clear interrupt flag for timer 0
		WriteTimer0(64911);

	}
	//code for servo state = 1 and regular timer
	if(PIR1bits.TMR1IF && servoState == 1){
		valveCounter++;	
		if(valveCounter == valveTotalTick){
			closeValve();	
			valveCounter = 0;
		}	
		PIR1bits.TMR1IF = 0;	// Clear interrupt flag for timer 0
	}
	else if(PIR1bits.TMR1IF && plantTimerCount == totalTimerCount){
		//Waters all the plants	
	
		moveToLocation(plantBeingWatered);
		openValve();
		
		if(plantBeingWatered == totalplants){
			plantTimerCount = 0;
			plantBeingWatered = -1;
		}
	
		plantBeingWatered++;
		PIR1bits.TMR1IF = 0;	// Clear interrupt flag for timer 0
	}	
	
	//Timer for timed water sequence
	else if(PIR1bits.TMR1IF)  
	{		
		plantTimerCount++;
		PIR1bits.TMR1IF = 0;	// Clear interrupt flag for timer 0
	}
	
	// interupt for button to water plant 0
	if(INTCONbits.INT0IF){
		moveToLocation(0);
		openValve();
		INTCONbits.INT0IF = 0;
		
		
	}	
	// interupt for button to water plant 1
	if(INTCON3bits.INT1IF){
		moveToLocation(1);
		openValve();
		INTCON3bits.INT1IF = 0;

	}	
	// interupt for button to water plant 2
	if(INTCON3bits.INT2IF){
		moveToLocation(2);
		openValve();
		INTCON3bits.INT2IF = 0;
	}	
}
Exemplo n.º 23
0
/**
 * Entering this method could mean that the transceiver is malfunctioning.
 * Xbee may be down or may have lost sync with his neighbor.
 * So, try to send a reset message to the transceiver and rejoin the mote.
 * A 100 ms delay is necessary to perform a full reset before send any command.
 */
void BSP_onDsWdtWakeUp(void) {
    XBee_reset();
    Delay100TCYx(UINT_MAX);
    XBee_join();
}
Exemplo n.º 24
0
/*! **********************************************************************
 * Function: range(void)
 *
 * Include: Range.h
 *
 * @brief Samples the range
 *
 * Description: Takes a number of samples of the ultrasonic sensor at a specified
 *              rate. Continues to sample the IR sensor at a different rate while
 *              sampling the ultrasonic. Then combines the ranges and sets the
 *              target state
 *
 * Arguments: None
 *
 * Returns: the range
 *************************************************************************/
unsigned int range(void)
{
#define range_IR sumIR      //Come conenient name changes
#define range_US sumUS
    char i;
    unsigned int k;
    unsigned int temp;
    unsigned long int sumUS = 0;
    unsigned long int sumIR = 0;
    int IR_samples = 0;
    unsigned char delayUS = 100 / rateUS;       //100Hz will give 1 delay increment of 10ms
    unsigned char delayIR = 10000 / rateIR;     //10KHz will give 1 delay increment of 0.1ms

    //Multiplex onto the IR sensor
//    SetChanADC(ADC_IR_READ);
    ADCON0 = ADC_IR_READ;

    for (i = 0; i < numSamples; i++)
    {
        configureRange();   //Still have to reconfigure each time???
        beginUS();

        //Continue sampling the IR while waiting for the ultrasonic
        while (measuringUS)
        {
            ADCON0bits.GO = 1;
            while (ADCON0bits.GO_NOT_DONE);
            temp = ADRES;
            if (temp > 100) sumIR += IR_CONV(temp);
            else IR_samples--;
            //sumIR += IR_CONV(ADRES >> 6);
            IR_samples++;

            Delay100TCYx(delayIR);  //Delays in inrements of 100Tcy, which is 100 x 1us for 4MHz clock -> 0.1ms or 10KHz
        }
        //get range of ultrasonic reading
        sumUS += rangeUS(25);   ///Standard room temperature for now @todo Read in temperature for US calculation
        Delay10KTCYx(delayUS);  //Delays in increments of 10KTcy, which is 10,000 * 1us for a 4MHz clock
    }

    if (numSamples) sumUS = sumUS / numSamples;     //Calculate the average Ultrasonic range
    else sumUS = 0;

    //Average all IR samples taken, and convert to distance
    if (IR_samples) range_IR = sumIR / IR_samples;
    else sumIR = 0;

    // Save the range value for printing raw rang
    lastIRRange = range_IR;
    lastUSRange = range_US;

    // Eliminate out of range values
    if (range_IR > m_maxRange) range_IR = 0;
    if (range_US > m_maxRange) range_US = 0;
    if (range_IR < m_minRange) range_IR = 0;
    if (range_US < m_minRange) range_US = 0;

    return lastRange = fuseRange(range_US, range_IR);
#undef range_IR
#undef range_US
}
Exemplo n.º 25
0
void Delay1KTCYx(unsigned char unit) {
	int i;
	for(i = 0; i < 10; i++) {
		Delay100TCYx(unit);
	}
};