Пример #1
0
void *GPSLoop(void *some_void_ptr)
{
	unsigned char Line[100];
	int id, Length;
	struct i2c_info bb;
	struct TGPS *GPS;

	GPS = (struct TGPS *)some_void_ptr;
	
	Length = 0;

    while (1)
    {
        int i;
		unsigned char Character;

		printf ("SDA/SCL = %d/%d\n", Config.SDA, Config.SCL);
		
		if (OpenI2C(&bb, 0x42, Config.SDA, Config.SCL, 10, 100))		// struct, i2c address, SDA, SCL, us clock delay, timeout ms
		{
			printf("Failed to open I2C\n");
			exit(1);
		}
	
		SetFlightMode(&bb);

        while (!bb.Failed)
        {
            Character = I2CGetc(&bb);

			if (Character == 0xFF)
			{
				delayMilliseconds (100);
			}
            else if (Character == '$')
			{
				Line[0] = Character;
				Length = 1;
			}
            else if (Length > 90)
			{
				Length = 0;
            }
            else if ((Length > 0) && (Character != '\r'))
            {
               	Line[Length++] = Character;
               	if (Character == '\n')
               	{
               		Line[Length] = '\0';
					// puts(Line);
               		ProcessLine(&bb, GPS, Line, Length);
					delayMilliseconds (100);
               		Length = 0;
               	}
            }
		}
		
		ResetI2C(&bb);
	}
}
Пример #2
0
void Init_I2C(void)
{
	#ifdef MASTER
		OpenI2C(MASTER,SLEW_OFF);
		// In Master Mode:
		// Clock = Fosc/(4 * (SSPADD + 1)
		// SSPADD = Fosc/(4 * Fi2c) - 1 = 8meg/4*100k - 1 = 19
		// 19 = 0x13
		// SSPADD = 19;
		SSPADD = 27; //This is so I can actually see stuff on my old O-Scope
	#endif
	//SSPCON2bits.SEN = 1;
	OpenI2C(SLAVE_7,SLEW_OFF);
	SSPADD = 0x10;
	PIR1bits.SSPIF = 0; 
	PIE1bits.SSPIE = 1;		//Enable Interrupt	
}
Пример #3
0
void configDS1307 (void)
{
    //CloseI2C();               // close i2c if was operating earlier
    OpenI2C(MASTER,SLEW_OFF);	// I2C MODULE MASTER MODE / 100KHz
    SSPADD= 49;             	// clock i2c
    TRISBbits.TRISB2 = 0;       // vcc rtc
    LATBbits.LATB2 = 1;         // vcc rtc
    Delay10KTCYx(50);
}
Пример #4
0
void i2c_setup(void)
{
    //-------------------
    //Setup I2C
    //-------------------

    SSPADD = 0x78;                  //120
    OpenI2C(MASTER, SLEW_OFF);      //Init I2C module

    printf("\n\n\rConfiguring I2C...");

    StartI2C();
        WriteI2C(0x98);
        WriteI2C(0x07);                //mode register
        WriteI2C(0x00);                //Standby mode
    StopI2C();
    IdleI2C();
    StartI2C();
        WriteI2C(0x98);
        WriteI2C(0x05);                //SPCNT register
        WriteI2C(0x00);                //No sleep count
    StopI2C();
    IdleI2C();
    StartI2C();
        WriteI2C(0x98);
        WriteI2C(0x06);                //interrupt register (INTSU)
        WriteI2C(0xE4);                //shake INT on 3-axis, and tap detect
    StopI2C();
    IdleI2C();
    StartI2C();
        WriteI2C(0x98);
        WriteI2C(0x09);                //PDET register
        WriteI2C(0x84);                //tap detection on  z-axis
    StopI2C();
    IdleI2C();
    StartI2C();
        WriteI2C(0x98);
        WriteI2C(0x08);                //SR register
        WriteI2C(0x00);                //Sample rate at 32/sec
    StopI2C();
    IdleI2C();
    StartI2C();
        WriteI2C(0x98);
        WriteI2C(0x0A);                //PD register
        WriteI2C(0x2F);                //test tap detection, debounce
    StopI2C();
    IdleI2C();
    StartI2C();
        WriteI2C(0x98);            
        WriteI2C(0x07);             //select the mode register
        WriteI2C(0x41);             //active mode, int push pull
    StopI2C();

    printf("Finished!\r\n");
}
Пример #5
0
void main(void)
{
    /* Configure the oscillator for the device */
    ConfigureOscillator();

    /* Initialize I/O and Peripherals for application */
    InitApp();
    
    // i2c conf
    // /* // i2c slave
    TRISBbits.TRISB3 = 1;
    TRISBbits.TRISB4 = 1; //Statement to configure the DATA pin as an input.
    OpenI2C(SLAVE_7, SLEW_OFF);
    SSPADD = 0xB0;
   //  */
    /* //i2c master
        TRISBbits.TRISB3 = 1;
        TRISBbits.TRISB4 = 1; //Statement to configure the DATA pin as an input.
        OpenI2C( MASTER, SLEW_OFF);
        SSPADD = 0x27; //SSPADD Baud Register used to calculate I2C clock speed in MASTER mode (in this case 100Khz)
     */

    unsigned char addr;
    unsigned char data;

    int delayVal = 5;
    LEDPin = 1;//Set LED Pin

    while(1)
    {
     //   /* //i2c slave
        if(DataRdyI2C() == 1)
        {
            addr = ReadI2C();
            while(DataRdyI2C() == 0);
            data = ReadI2C();
        }
    //*/
        /* //i2c master
            StartI2C();
            IdleI2C();
            putcI2C( 0xB0 ); //send address
            IdleI2C();
            putcI2C( 0x11 ); //send data
            IdleI2C();
            StopI2C();

         */

        LEDPin = ~LEDPin;//Toggle LED Pin
        Delay10KTCYx(delayVal);//Delay 250K cycles (1 second at 1MHz since each instruction takes 4 cycles)
    }

}
Пример #6
0
void main()
{
	long temperature = 0;
	long pressure = 0;
	long altitude = 0;
	double temp = 0;

	OSCCON = 0x70;		// 8 MHz OSC
	
	// I2C
	TRISCbits.TRISC3 = 1;		// SCL
	TRISCbits.TRISC4 = 1;		// SDA
	
	// UART
	// Initialize UART
	openTxUsart();
	
	// Initialize I2C
	OpenI2C(MASTER, SLEW_OFF);
	
	
	
	delay_ms(100);
	
	
	BMP085_Calibration();
	BMP_dump_calibration();
	
	printf((const far rom char*) "=========================\r\n");
	printf((const far rom char*) "=========RESTART=========\r\n");
	printf((const far rom char*) "=========RESTART=========\r\n");
	printf((const far rom char*) "=========RESTART=========\r\n");
	printf((const far rom char*) "=========================\r\n");
	
	while(1)
	{
		bmp085Convert(&temperature, &pressure);
		
		printf((const far rom char*)"Temperature: %ld (in 0.1 deg C)\r\n", temperature);
		printf((const far rom char*)"Pressure: %ld Pa\n\r\n", pressure);
		
		// For fun, lets convert to altitude
		temp = (double) pressure/101325;
		temp = 1-pow(temp, 0.19029);
		altitude = floor(44330*temp);
		printf((const far rom char*)"Altitude: %ldm\r\n", altitude);
		printf((const far rom char*) "=========================\r\n");
		
		delay_ms(10000);
	}
}
Пример #7
0
// Initialise the PIC
static void initialisePic(void)
{
    // PIC port set up --------------------------------------------------------

	// Default all pins to digital
    ADCON1 = 0x0F;

    // Configure ports as inputs (1) or outputs(0)
    TRISA = 0b00000000;
    TRISB = 0b00000000;
    TRISC = 0b00000000;
    TRISD = 0b00000000;
    TRISE = 0b00000000;

    // Clear all ports
    PORTA = 0b00000000;
    PORTB = 0b00000000;
    PORTC = 0b00000000;
    PORTD = 0b00000000;
    PORTE = 0b00000000;

    // initialise the atmega IC
    atmegaFeederRunningTRIS = 1;
    atmegaResetPin = 1;
    
    
    // initialise i2c communication
    OpenI2C( MASTER, SLEW_OFF);
    SSPADD = 0x70;
    
    // Application specific initialisation
    applicationInit();
    
    // Initialise the USB device
    USBDeviceInit();

    // Initialise the output pins
    setVac1off;
    setVac2off;
    setVibrationoff;
    OpenTimer2( TIMER_INT_OFF & T2_PS_1_1);

    // load pwm values from eeprom
    led1_duty_cycle = Read_b_eep(baseLED_EEPROM_address);
    led2_duty_cycle = Read_b_eep(headLED_EEPROM_address);

    // initialise the stepper driver and start timer 0 at 1 microsecond intervals
    
    
}
Пример #8
0
void pcfLCDInit(BYTE addr)
{
#ifndef _WINDOWS
	WORD i;
	BYTE sync_mode=0;
	BYTE slew=0; 

	// Set lcd reset pin as output
	// Set lcd reset pin low
	LCD_RESET_TRIS = 0;
	LCD_RESET = 0;
	DelayMs(500); // tW(RESL)
	LCD_RESET = 1;
	DelayMs(500); // tW(RESH)
	LCD_RESET = 0;
	DelayMs(1); // tW(RESL)
	LCD_RESET = 1;
	DelayMs(3); // tR(OP)
	
	//***************************************************
	//* Lcd init commands *
	//***************************************************
    for(i=0;i<20;i++)
    I2C_Recv[i]=0;

    addr=PCF8535_BUS_ADDRESS;        //address of the device (slave) under communication

    CloseI2C();    //close i2c if was operating earlier

	//---INITIALISE THE I2C MODULE FOR MASTER MODE WITH 100KHz ---
    sync_mode = MASTER;
    slew = SLEW_OFF;

    OpenI2C(sync_mode,slew);

    SSPADD=0x0A;             //400kHz Baud clock(9) @8MHz
    //check for bus idle condition in multi master communication
    IdleI2C();

    //---START I2C---
    //StartI2C();
    LCDSendCommand(addr,(BYTE*)INIT_SEQUENCE,sizeof(INIT_SEQUENCE));
#else 
    UNUSED(addr); // заглушка
#endif
}
int main(int argc, char** argv) {
    /**************INICJALICACJA*****************/
    for (int i=0; i>10; i++) {
        __delay_ms(30);
    }
    OpenI2C(MASTER, SLEW_OFF);
    //SSPADD = ((Fosc/predkosc magistrali)/4)-1
    SSPADD = 49; //dla zegara 20 MHz i predkosci 100kHz: ((20 000 000/100 000)/4)-1 = 49
    
    Init_lcd();
    LcdCmd(DISP_ON_CURSOR_OFF_BLINK_OFF);
    LcdCmd(_4_BIT_2_LINES_FONT_5X8);

    Init_adxl345(-5, -3, 1, _16G, Hz_100); //x offset, y offset, z offset, zakres 16 G, pr?dko?? przesy?u danych 100 Hz
/********************************************/

    


    while(1) {
        LcdText(3, 1, "       "); //czyszczenie danych na wy?wietlaczu
        LcdText(12, 0, "    ");
        LcdText(3, 2, "             ");

        LcdText(0, 1, "X= ");
        LcdText(3, 1, getX());

        LcdText(9, 0, "Y= ");
        LcdText(11, 0, getY());

        LcdText(0, 2, "Z= ");
        LcdText(3, 2, getZ());

        for (unsigned char i=0; i<100; i++) { //czekaj 1 s
            __delay_ms(10);
        }
    }


    return (EXIT_SUCCESS);
}
Пример #10
0
void main(void) {
    char c;
    signed char length;
    unsigned char msgtype;
    int test_var = 0;
    unsigned char last_reg_recvd;
    uart_comm uc;
    i2c_comm ic;
    unsigned char msgbuffer[MSGLEN + 1];
    unsigned char i;
    uart_thread_struct uthread_data; // info for uart_lthread
    timer1_thread_struct t1thread_data; // info for timer1_lthread
    timer0_thread_struct t0thread_data; // info for timer0_lthread

#ifdef __USE18F2680
    OSCCON = 0xFC; // see datasheet
    // We have enough room below the Max Freq to enable the PLL for this chip
    OSCTUNEbits.PLLEN = 1; // 4x the clock speed in the previous line
#else
    OSCCON = 0x82; // see datasheeet
    OSCTUNEbits.PLLEN = 0; // Makes the clock exceed the PIC's rated speed if the PLL is on
#endif

    // initialize my uart recv handling code
 //   init_uart_recv(&uc);

    // initialize the i2c code
   init_i2c(&ic);
   i2c_configure_master(0x02);
   OpenI2C(MASTER, SLEW_OFF);

    // init the timer1 lthread
   init_timer1_lthread(&t1thread_data);

    // initialize message queues before enabling any interrupts
    init_queues();

    // set direction for PORTB to output
    TRISB = 0x0;
    LATB = 0x0;

    // how to set up PORTA for input (for the V4 board with the PIC2680)
    /*
            PORTA = 0x0;	// clear the port
            LATA = 0x0;		// clear the output latch
            ADCON1 = 0x0F;	// turn off the A2D function on these pins
            // Only for 40-pin version of this chip CMCON = 0x07;	// turn the comparator off
            TRISA = 0x0F;	// set RA3-RA0 to inputs
     */

    // initialize Timers
    //OpenTimer0(TIMER_INT_ON & T0_16BIT & T0_SOURCE_INT & T0_PS_1_128);
     OpenTimer1(TIMER_INT_ON & T1_PS_1_1 & T1_16BIT_RW & T1_SOURCE_INT & T1_OSC1EN_OFF & T1_SYNC_EXT_OFF);
 //    WriteTimer1(65086);

  //   OpenI2C(MASTER, SLEW_OFF);

    // Peripheral interrupts can have their priority set to high or low
    // enable high-priority interrupts and low-priority interrupts
    enable_interrupts();

    // Decide on the priority of the enabled peripheral interrupts
    // 0 is low, 1 is high
    // Timer1 interrupt
    IPR1bits.TMR1IP = 0;
    // USART RX interrupt
   IPR1bits.RCIP = 1;
    // USART TX interrupt
   IPR1bits.TXIP = 0;
    // I2C interrupt
   IPR1bits.SSPIP = 1;

  //  OpenUSART( USART_TX_INT_OFF & USART_RX_INT_ON &  USART_ASYNCH_MODE & USART_EIGHT_BIT & USART_CONT_RX  & USART_BRGH_HIGH & USART_ADDEN_OFF, 38);
    //38 gives us baud rate of approx 19230

    //enable rx interrupts
     PIE1bits.RCIE = 1;
    PIE1bits.TXIE = 0; //disable send interrupt until we have something in mesage queue

  // PIE1bits.SSPIE = 1;



  //  OpenADC( ADC_FOSC_16 & ADC_RIGHT_JUST & ADC_4_TAD, ADC_CH0 & ADC_INT_ON
  //              & ADC_VREFPLUS_VDD & ADC_VREFMINUS_VSS, ADC_0ANA);

    // configure the hardware i2c device as a slave (0x9E -> 0x4F) or (0x9A -> 0x4D)
#if 1
    // Note that the temperature sensor Address bits (A0, A1, A2) are also the
    // least significant bits of LATB -- take care when changing them
    // They *are* changed in the timer interrupt handlers if those timers are
    //   enabled.  They are just there to make the lights blink and can be
    //   disabled.
  //  i2c_configure_slave(0x9E);
#else
    // If I want to test the temperature sensor from the ARM, I just make
    // sure this PIC does not have the same address and configure the
    // temperature sensor address bits and then just stay in an infinite loop
    i2c_configure_slave(0x9A);
    LATBbits.LATB1 = 1;
    LATBbits.LATB0 = 1;
    LATBbits.LATB2 = 1;
    for (;;);
#endif

    // must specifically enable the I2C interrupts
    PIE1bits.SSPIE = 1;

    // configure the hardware USART device
   // OpenUSART(USART_TX_INT_OFF & USART_RX_INT_ON & USART_ASYNCH_MODE & USART_EIGHT_BIT &
     //       USART_CONT_RX & USART_BRGH_LOW, 0x19);

    /* Junk to force an I2C interrupt in the simulator (if you wanted to)
    PIR1bits.SSPIF = 1;
    _asm
    goto 0x08
    _endasm;
     */

    // printf() is available, but is not advisable.  It goes to the UART pin
    // on the PIC and then you must hook something up to that to view it.
    // It is also slow and is blocking, so it will perturb your code's operation
    // Here is how it looks: printf("Hello\r\n");


    // loop forever
    // This loop is responsible for "handing off" messages to the subroutines
    // that should get them.  Although the subroutines are not threads, but
    // they can be equated with the tasks in your task diagram if you
    // structure them properly.
    while (1) {
        // Call a routine that blocks until either on the incoming
        // messages queues has a message (this may put the processor into
        // an idle mode)
        block_on_To_msgqueues();

        // At this point, one or both of the queues has a message.  It
        // makes sense to check the high-priority messages first -- in fact,
        // you may only want to check the low-priority messages when there
        // is not a high priority message.  That is a design decision and
        // I haven't done it here.
        length = ToMainHigh_recvmsg(MSGLEN, &msgtype, (void *) msgbuffer);
        if (length < 0) {
            // no message, check the error code to see if it is concern
            if (length != MSGQUEUE_EMPTY) {
                // This case be handled by your code.
            }
        } else {
            switch (msgtype) {
                case MSGT_TIMER0:
                {
                    timer0_lthread(&t0thread_data, msgtype, length, msgbuffer);
                    break;
                };
                case MSGT_I2C_DATA:
                case MSGT_I2C_DBG:
                {
                    // Here is where you could handle debugging, if you wanted
                    // keep track of the first byte received for later use (if desired)
                    last_reg_recvd = msgbuffer[0];
                    break;
                };
                case MSGT_I2C_RQST:
                {
                    // Generally, this is *NOT* how I recommend you handle an I2C slave request
                    // I recommend that you handle it completely inside the i2c interrupt handler
                    // by reading the data from a queue (i.e., you would not send a message, as is done
                    // now, from the i2c interrupt handler to main to ask for data).
                    //
                    // The last byte received is the "register" that is trying to be read
                    // The response is dependent on the register.
                    switch (last_reg_recvd) {
                        case 0xaa:
                        {
                            length = 2;
                            
//                            msgbuffer[0] = x[test_var];
                            msgbuffer[1] = 0xAA;
                            

                            
                            test_var++;
                            if(test_var > 299)
                                test_var = 0;

                            break;
                        }
                        case 0xa8:
                        {
                            length = 1;
                            msgbuffer[0] = 0x3A;
                            break;
                        }
                        case 0xa9:
                        {
                            length = 1;
                            msgbuffer[0] = 0xA3;
                            break;
                        }
                    };
                    start_i2c_slave_reply(length, msgbuffer);
                    break;
                };
                default:
                {
                    // Your code should handle this error
                    break;
                };
            };
        }

        // Check the low priority queue
        length = ToMainLow_recvmsg(MSGLEN, &msgtype, (void *) msgbuffer);
        if (length < 0) {
            // no message, check the error code to see if it is concern
            if (length != MSGQUEUE_EMPTY) {
                // Your code should handle this situation
            }
        } else {
            switch (msgtype) {
                case MSGT_TIMER1:
                {
                    timer1_lthread(&t1thread_data, msgtype, length, msgbuffer);
                    break;
                };
                case MSGT_OVERRUN:
                case MSGT_UART_DATA:
                {
                    uart_lthread(&uthread_data, msgtype, length, msgbuffer);
                    break;
                };
                default:
                {
                    // Your code should handle this error
                    break;
                };
            };
        }
    }

}
int main(int argc, char** argv) {

    /*ADRESY USTALONE DLA WEJSC A0, A1, A2 PODLACZONYCH DO MASY*/

    unsigned char Aout_addr = 0x70; //adres dla PCF8574A 0b01110000
  //unsigned char out_addr = 0x40; //adres dla PCF8574 0b01000000
    
    OpenI2C(MASTER, SLEW_OFF);
    //SSPADD = ((Fosc/predkosc magistrali)/4)-1
    SSPADD = 49; //dla zegara 20 MHz i predkosci 100kHz: ((20 000 000/100 000)/4)-1 = 49
     while(1) {

        IdleI2C(); //sprawdzanie, czy magistrala jest w stanie bezczynnosci
        StartI2C();
        IdleI2C();
        WriteI2C(Aout_addr);
        IdleI2C();
        WriteI2C(0b00000001);
        IdleI2C(); 
        StopI2C();
        for (unsigned char i=0; i<40; i++) { //czekaj 40 * 10ms = 400 ms
            __delay_ms(10);
        }

        IdleI2C();
        StartI2C();
        IdleI2C();
        WriteI2C(Aout_addr);
        IdleI2C();
        WriteI2C(0b00000010);
        IdleI2C();
        StopI2C();
        for (unsigned char i=0; i<40; i++) {
            __delay_ms(10);
        }

        IdleI2C();
        StartI2C();
        IdleI2C();
        WriteI2C(Aout_addr);
        IdleI2C();
        WriteI2C(0b00000100);
        IdleI2C();
        StopI2C();
        for (unsigned char i=0; i<40; i++) {
            __delay_ms(10);
        }

        IdleI2C();
        StartI2C();
        IdleI2C();
        WriteI2C(Aout_addr);
        IdleI2C();
        WriteI2C(0b00001000);
        IdleI2C();
        StopI2C();
        for (unsigned char i=0; i<40; i++) {
            __delay_ms(10);
        }

        IdleI2C();
        StartI2C();
        IdleI2C();
        WriteI2C(Aout_addr);
        IdleI2C();
        WriteI2C(0b00010000);
        IdleI2C();
        StopI2C();
        for (unsigned char i=0; i<40; i++) {
            __delay_ms(10);
        }

        IdleI2C();
        StartI2C();
        IdleI2C();
        WriteI2C(Aout_addr);
        IdleI2C();
        WriteI2C(0b00100000);
        IdleI2C();
        StopI2C();
        for (unsigned char i=0; i<40; i++) {
            __delay_ms(10);
        }

        IdleI2C();
        StartI2C();
        IdleI2C();
        WriteI2C(Aout_addr);
        IdleI2C();
        WriteI2C(0b01000000);
        IdleI2C();
        StopI2C();
        for (unsigned char i=0; i<40; i++) {
            __delay_ms(10);
        }

        IdleI2C();
        StartI2C();
        IdleI2C();
        WriteI2C(Aout_addr);
        IdleI2C();
        WriteI2C(0b10000000);
        IdleI2C();
        StopI2C();
        for (unsigned char i=0; i<40; i++) {
            __delay_ms(10);
        }
    }


    return (EXIT_SUCCESS);
}
Пример #12
0
void main(void)
{
	unsigned char address;
	unsigned char byte1, byte2, slope, counter;
	int temp, old_temp;
	int diff, last_diff;

	// zero our variables to save iteration values
	old_temp = 0;
	last_diff = 0;

	// Set internal oscillator to 4Mhz
	OSCCON = 0x6C;

	// Set PORT C (TRISC<3:4> bits) as digital outputs 
	TRISC = 0x18;
	LATC = 0x18;

	// Set Port B for digital output (LEDs)
	TRISB = 0x00;
	LATB = 0x3F;

	address = 0x07; // don't use this right now!
	setTempSensorAddress(address);

	// According to the datasheet, with a 4Mhz clock we
	// need SSPADD set to 0x28 to get a 100KHz clock for
	// the i2c master.  However, this is clearly wrong
	// when you look at the i2c clock with the logic tool.
	// The i2c frequency is about 23 KHz.  An errata sheet
	// for the processor says there is an error in the data
	// sheet.  SSPADD = 0x0A appears to get 83KHz.
	SSPADD = 0x0A;

	// Init PIC I2C hardware as Master
	OpenI2C (MASTER, SLEW_OFF);
	
	configStartTempSensor();

	while(1) {

		// Flash top red LED to indicate that the program is running
		LATBbits.LATB5 = ~(LATBbits.LATB5 & 1);

		// read temp sensor, get bytes for more accurate result
		readTempSensor(&byte1, &byte2, &slope, &counter);

		// check to see if we have a read error. If not, check to 
		// see if the temperature has changed.  If so, do something
		// with the red LEDs.
		if(byte1!=0xFF) {
			temp = (int) byte1; 
			temp = temp << 1;
			byte2 = byte2 >> 7;
			temp = temp + (int) byte2;
			diff = temp - old_temp;
			if(diff<0) diff = -diff;
			if((diff+last_diff)>=3) {
				LATB = 0x3F;
			} else if ((diff+last_diff)==2) {
				LATB = 0x1F;
			} else if ((diff+last_diff)==1) {
				LATB = 0x0F;
			} else {
				LATB = 0x07;
			}

			// save temp as old_temp to compute difference
			old_temp = temp;
			last_diff = diff;
		} else {
Пример #13
0
void main(void)
{
    // Configuracao das portas com LEDs
    TRISCbits.TRISC0=0;    // LED Amarelo para simples sinalizacao
    TRISCbits.TRISC1=0;    // LED Verde para simples sinalizacao
    TRISCbits.TRISC2=0;    // LED Vermelho para simples sinalizacao

    // Configuracao do pino TX da porta serial EUSART / para RS232
    TRISCbits.TRISC6=1;    // TX da EUSART
    // O programa ira informar na porta serial o status
    // e logs de funcionamento da coleta de dados I2C

    // agora a CHAMADA para configuracao GLOBAL da PIC
    configuracao_PIC();

    // Preparacao para configuracao do modulo MSSP I2C (com Errata aplicada)
    /* 17. Module: MSSP (ERRATA for PIC18F4550 and PIC18F2525, etc)
     * ================
     *
     *  It has been observed that following a Power-on Reset, I2C mode may not
     *  initialize properly by just configuring the SCL and SDA pins as either
     *  inputs or outputs. This has only been seen in a few unique system
     *  environments. A test of a statistically significant sample of pre-
     *  production systems, across the voltage and current range of the
     *  application's power supply, should indicate if a system is
     *  susceptible to this issue.
     *
     * Work around = Before configuring the module for I2C operation:
     * 1. Configure the SCL and SDA pins as outputs by clearing
     *  their corresponding TRIS bits.
     * 2. Force SCL and SDA low by clearing the corresponding LAT bits.
     * 3. While keeping the LAT bits clear, configure SCL and SDA as
     *  inputs by setting their TRIS bits.
     *
     * Once this is done, use the SSPCON1 and SSPCON2 registers to
     *  configure the proper I2C mode as before.
     */

    TRISCbits.TRISC3=0;    // SCL do I2C colocado como saida por causa de bug*
    TRISCbits.TRISC4=0;    // SDA do I2C colocado como saida por causa de bug*
    LATC3=0;            // bug* pede que zere-se o LAT das portas SCL e SDA
    LATC4=0;            // durante inicializacao do I2C para evitar flutuacoes
    // eletricas que ficariam nas portas antes de liga-las

    Delay10KTCYx(10);   // simples pausa para troca de estado na SDA e SCL

    TRISCbits.TRISC3=1;    // SCL do I2C, agora corretamente como saida
    TRISCbits.TRISC4=1;    // SDA do I2C, agora corretamente como saida
    // here ends "errata workaround"

    // entao a CHAMADA para diversas configuracoes referentes ao I2C (MSSP)
    configuracao_I2C();

    // e a inicializacao da porta serial EUSART
    configuracao_EUSART();

    while(BusyUSART());
    putrsUSART("\n\r_INIT SERIAL.\n\r");


    /*************************
     *
     * INICIO DO PROGRAMA
     *
     *************************/

    LED_AMAR=0;
    LED_VERM=1;
    LED_VERD=0;

    // Inicializacao do MSSP I2C

    CloseI2C(); // simplesmente fechando qualquer possibilidade de I2C anterior
    // comando nao necessario no boot da PIC
    //macro = #define CloseI2C()  SSPCON1 &=0xDF

    while(BusyUSART());
    putrsUSART("SSPAD=");
    putsUSART( itoa(NULL,SSPADD,10) );
    putrsUSART(" (hex=0x");
    putrsUSART( itoa(NULL,SSPADD,16) );
    putrsUSART("); Abrindo MSSP I2C (Master,Slew_off)\n\r");

    OpenI2C(MASTER,SLEW_OFF);   // configuracao implicita da SSPCON1 e SSPSTAT

    while (1)
    {
        testaColisao();
        getDS1307();



        //testaColisao();
        getTemperaturaHumidade();

        pausa(10);
    }
}
Пример #14
0
void main (void)
{
	/* TIMER 1*/
	OpenTimer1(	TIMER_INT_ON   &
							T1_16BIT_RW    &
      				T1_SOURCE_EXT  &
      				T1_PS_1_1      &
      				T1_OSC1EN_ON   &
      				T1_SYNC_EXT_OFF );// tem que estar off para correr na placa, mas on para correr no proteus

	ADCON1 = 0x0E; // Port A: A0 - analog; A1-A7 - digital

	OpenADC (ADC_FOSC_RC & ADC_RIGHT_JUST & ADC_1ANA_0REF, ADC_CH0 & ADC_INT_OFF);

	/* BUTTON S3 */
	OpenRB0INT (	PORTB_CHANGE_INT_ON & /* enable the RB0/INT0 interrupt */
                PORTB_PULLUPS_ON &    /* configure the RB0 pin for input */
                FALLING_EDGE_INT);    /* trigger interrupt upon S3 button depression */


	OpenXLCD( FOUR_BIT & LINES_5X7 ); // 4-bit data interface; 2 x 16 characters

	OpenI2C(MASTER, SLEW_ON);// Initialize I2C module
	SSPADD = 9; //400kHz Baud clock(9) @16MHz
	//100kHz Baud clock(39) @16MHz

	InitializeBuzzer();

	init_LVD();

	EnableHighInterrupts();

	alarmes[0] = 'a';
	alarmes[1] = 0;
	alarmes_prev[0] = 'a';
	alarmes_prev[1] = 0;

	checksumIsRight = verificar_checksum();

	if(checksumIsRight == 1){
		ler_EEPROM_interna_parametros();
		ler_EEPROM_interna_relogio();
		ler_EEPROM_interna_relogio_alarme(); // carregar da EEPROM interna o valor do alarme do relogio
		ler_EEPROM_interna_temp_alarme(); // carregar da EEPROM interna o valor do alarme da temperatura
		ler_EEPROM_interna_lum_alarme(); // carregar da EEPROM interna o valor do alarme da luminosidade
	}

	ler_EEPROM_interna_relogio_seconds();

	update_EEPROM_interna_parametros();
	update_EEPROM_interna_relogio_alarme();
	update_EEPROM_interna_temp_alarme();
	update_EEPROM_interna_lum_alarme();
	update_EEPROM_interna_relogio_hours();
	update_EEPROM_interna_relogio_minutes();

	init_EEPROM_externa();

 	WriteTimer1( 0x8000 ); // load timer: 1 second

///////////////////////////////////////////////////////////////////////////////
//*************************** Ciclo Principal *******************************//
///////////////////////////////////////////////////////////////////////////////

	while (1){

		if(modo_sleep == 1 && cursor_pos == 8){
    	WriteCmdXLCD( DOFF );      // Turn display off
		}

		else{
			while( BusyXLCD() );
  		WriteCmdXLCD( DOFF );      // Turn display off
  		while( BusyXLCD() );
  		WriteCmdXLCD( CURSOR_OFF );// Enable display with no cursor
  		while( BusyXLCD() );
		}

		sd = seconds/10;
		su = seconds%10;
		md = minutes/10;
		mu = minutes%10;
		hd = hours/10;
		hu = hours%10;

		SetDDRamAddr(0x0D);
		putsXLCD(alarmes);

		rotina_verificacao_alarmes();

		rotina_modo_modificacao();

		rotina_sai_modificacao();

		avisa_alarmes();

		rotina_sensores_PMON();

		if(CCP1CON == 0x00 && modo_modificacao == 0){
			modo_sleep = 1;
			Sleep();
		}
 	}
}
Пример #15
0
void init_OLED(){

    OpenI2C(MASTER, SLEW_ON);
    SSPADD = 29; //200kHz Baud clock(9) @20MHz
    //100kHz Baud clock(39) @16MHz

    ///////
    //OpenI2C(MASTER, SLEW_OFF);
    //StartI2C();
    sendcommand(0xae); //display off
    sendcommand(0xa6); //Set Normal Display (default)
    // Adafruit Init sequence for 128x64 OLED module
    sendcommand(0xAE); //DISPLAYOFF
    sendcommand(0xD5); //SETDISPLAYCLOCKDIV
    sendcommand(0x80); // the suggested ratio 0x80
    sendcommand(0xA8); //SSD1306_SETMULTIPLEX
    sendcommand(0x3F);
    sendcommand(0xD3); //SETDISPLAYOFFSET
    sendcommand(0x0); //no offset
    sendcommand(0x40 | 0x0); //SETSTARTLINE
    sendcommand(0x8D); //CHARGEPUMP
    sendcommand(0x14);
    sendcommand(0x20); //MEMORYMODE
    sendcommand(0x00); //0x0 act like ks0108

    sendcommand(0xA0 | 0x1); //SEGREMAP   //Rotate screen 180 deg
    //sendcommand(0xA0);

    sendcommand(0xC8); //COMSCANDEC  Rotate screen 180 Deg
    //sendcommand(0xC0);

    sendcommand(0xDA); //0xDA
    sendcommand(0x12); //COMSCANDEC
    sendcommand(0x81); //SETCONTRAS
    sendcommand(0xCF); //
    sendcommand(0xd9); //SETPRECHARGE
    sendcommand(0xF1);
    sendcommand(0xDB); //SETVCOMDETECT
    sendcommand(0x40);
    sendcommand(0xA4); //DISPLAYALLON_RESUME
    sendcommand(0xA6);

    /////////////////////////////////////////////////
    clear_display();
    sendcommand(0x2e); // stop scroll
    //----------------------------REVERSE comments----------------------------//
    //  sendcommand(0xa0);		//seg re-map 0->127(default)
    //  sendcommand(0xa1);		//seg re-map 127->0
    //  sendcommand(0xc8);
    //  delay(1000);
    //----------------------------REVERSE comments----------------------------//
    // sendcommand(0xa7);  //Set Inverse Display
    // sendcommand(0xae);		//display off
    sendcommand(0x20); //Set Memory Addressing Mode
    sendcommand(0x00); //Set Memory Addressing Mode ab Horizontal addressing mode
    //  sendcommand(0x02);         // Set Memory Addressing Mode ab Page addressing mode(RESET)
    setXY(0, 0);
    /*
     for(int i=0;i<128*8;i++)     // show 128* 64 Logo
     {
       SendChar(pgm_read_byte(logo+i));
     }
     */
    sendcommand(0xaf); //display on
}