void LCD_WriteFirstLine(char OutFirstString[]){ while (BusyXLCD()); SetDDRamAddr(0x00); while (BusyXLCD()); putsXLCD(OutFirstString); while (BusyXLCD()); WriteCmdXLCD(CURSOR_OFF&BLINK_OFF); //cursor uit, knipperen uit }
void clearLCD(void) { openLCD(); while (BusyXLCD()); SetDDRamAddr(0x80); while (BusyXLCD()); putrsXLCD(" "); while (BusyXLCD()); SetDDRamAddr(0xc0); putrsXLCD(" "); }
void printLCD(char *line1, char *line2) { openLCD(); while (BusyXLCD()); SetDDRamAddr(0x80); while (BusyXLCD()); putsXLCD(line1); while (BusyXLCD()); SetDDRamAddr(0xc0); while (BusyXLCD()); putsXLCD(line2); }
void LCD_Init(void){ // LCD instellingen OpenXLCD(DON); OpenXLCD(FOUR_BIT&LINES_5X7); // 8 bits datalijn, meerdere regels while (BusyXLCD()); WriteCmdXLCD(SHIFT_DISP_LEFT); // cursor instelling while (BusyXLCD()); WriteCmdXLCD(CURSOR_ON&BLINK_OFF); //cursor uit, knipperen uit }
void openLCD(void) { if (!flagDisplayOn) { WriteCmdXLCD(DON); while (BusyXLCD()); flagDisplayOn = 1; PORTDbits.RD7 = 0; } }
void LCD_Write(void){ while (BusyXLCD()); SetDDRamAddr(0x00); while (BusyXLCD()); putsXLCD(LCDREGEL4); Delay10KTCYx(250); // 500 mSec Delay10KTCYx(250); // 500 mSec while (BusyXLCD()); SetDDRamAddr(0x40); while (BusyXLCD()); putsXLCD(LCDREGEL5); while (BusyXLCD()); WriteCmdXLCD(CURSOR_OFF&BLINK_OFF); //cursor uit, knipperen uit }
void putrsXLCD(const rom char *buffer) { while(*buffer) // Write data to LCD up to null { while(BusyXLCD()); // Wait while LCD is busy WriteDataXLCD(*buffer); // Write character to LCD buffer++; // Increment buffer } return; }
/******************************************************************** * Function Name: lcd_puts issue de putsXLCD * * Return Value: void * * Parameters: pointer to string * * Description: Ecrit une chaine de caractère à partir d'un * pointeur vers char, à la suite du dernier * caractère écrit. Prend en compte \n \f \b * ********************************************************************/ void lcd_puts(char *buffer) { while(*buffer) // Write data to LCD up to null { while(BusyXLCD()); // Wait while LCD is busy lcd_putc(*buffer); // Write character to LCD buffer++; // Increment buffer } return; }
void OpenXLCD(unsigned char lcdtype) { // 4-bit mode #ifdef UPPER // Upper 4-bits of the port DATA_PORT &= 0x0f; TRIS_DATA_PORT &= 0x0F; #else // Lower 4-bits of the port DATA_PORT &= 0xf0; TRIS_DATA_PORT &= 0xF0; #endif TRIS_RW = 0; // All control signals made outputs TRIS_RS = 0; TRIS_E = 0; RW_PIN = 0; // R/W pin made low RS_PIN = 0; // Register select pin made low E_PIN = 0; // Clock pin made low // Delay for 15ms to allow for LCD Power on reset DelayPORXLCD(); //-------------------reset procedure through software---------------------- WriteCmdXLCD(0x30); Delay1KTCYx(33); WriteCmdXLCD(0x30); Delay1KTCYx(0x01); WriteCmdXLCD(0x32); while( BusyXLCD() ); //------------------------------------------------------------------------------------------ // Set data interface width, # lines, font while(BusyXLCD()); // Wait if LCD busy WriteCmdXLCD(lcdtype); // Function set cmd // Turn the display on then off while(BusyXLCD()); // Wait if LCD busy WriteCmdXLCD(DOFF&CURSOR_OFF&BLINK_OFF); // Display OFF/Blink OFF while(BusyXLCD()); // Wait if LCD busy WriteCmdXLCD(DON&CURSOR_ON&BLINK_ON); // Display ON/Blink ON // Clear display while(BusyXLCD()); // Wait if LCD busy WriteCmdXLCD(0x01); // Clear display // Set entry mode inc, no shift while(BusyXLCD()); // Wait if LCD busy WriteCmdXLCD(SHIFT_CUR_LEFT); // Entry Mode // Set DD Ram address to 0 while(BusyXLCD()); // Wait if LCD busy SetDDRamAddr(0x80); // Set Display data ram address to 0 return; }
/**************Initialise LCD****************/ void mInitLCD(void) { // Initialise LCD for 4 bit operation and multiple line operation OpenXLCD( FOUR_BIT & LINES_5X7 ); // configure external LCD // Initialise display so that neither cursor nor blink is ON while(BusyXLCD()); WriteCmdXLCD(0b00000001); // Reset Display // Initialise display so that neither cursor nor blink is ON while(BusyXLCD()); WriteCmdXLCD(0b00001100); // Last three digits are display ON, Cursor OFF, Blink OFF // Initialise display as what to show: // Money:XXXXXXXp // Energy:XXXXXWh while(BusyXLCD()); SetDDRamAddr( 0x00 ); // Put the cursor in the correct position //Blank the bottom line, just in case while(BusyXLCD()); putrsXLCD(dataArrayInit); while(BusyXLCD()); SetDDRamAddr( 0x40 ); // Put the cursor in the correct position //Blank the bottom line, just in case while(BusyXLCD()); putrsXLCD(dataArrayInit); }//end Initialise LCD routine
void rotina_sai_modificacao(void) { if(sai_modificacao == 1){ mudei_horas = 0; mudei_ahoras = 0; mudei_alum = 0; mudei_atemp = 0; d_a_alarmes = 0; alarme_temp_prev = alarme_temp; alarme_lum_prev = alarme_lum; alarme_hours_prev = alarme_hours; alarme_minutes_prev = alarme_minutes; alarme_seconds_prev = alarme_seconds; alarmes_prev[0] = alarmes[0]; change_AH = 1; SetDDRamAddr(0x46); while( BusyXLCD() ); putrsXLCD((const rom far char*)" "); SetDDRamAddr(0x09); while( BusyXLCD() ); sprintf((char*)spaces, (const rom far char*)" "); putsXLCD(spaces); SetDDRamAddr(0x4D); while( BusyXLCD() ); sprintf((char*)luminosidade, (const rom far char*)"L %d", n_lum); putsXLCD(luminosidade); SetDDRamAddr(0x40); while( BusyXLCD() ); sprintf((char*)temperatura_s, (const rom far char*)"%d C", (int)temperatura); putsXLCD(temperatura_s); sai_modificacao = 0; } }
/******************************************************************** * Function Name: lcd_putc(char lettre) * * Return Value: void * * Parameters: lettre: caractère à afficher sur le LCD * * Description: Cette fonction reprend WriteDataXLCD mais en* * plus gère les caractère spéciaux \n \f \b * ********************************************************************/ void lcd_putc(char lettre) { while(BusyXLCD()); switch(lettre){ case '\f' : WriteCmdXLCD(0x01); DelayXLCD(); break; // effacement de l'écran case '\n' : lcd_gotoyx(2,1); break; // passage à la ligne case '\b' : WriteCmdXLCD(0x10); break; // recule d'une position default : WriteDataXLCD(lettre); break; // écrit la lettre } }
void interrupt global_isr(void) { // TIMER 0 if(TMR0IE && TMR0IF) { //TMR0IE=0; LED2=1; //vw_isr_tmr0(); //return; // volta antes de testar o Timer1 //TMR0IE=1; } // TIMER 1 if (TMR1IF) { //TMR1IE=0; LEDI=1; LEDI=0; if (relogio >= 60) { aferir(); // Afere, Mostra no LCD, e Trasmite relogio=0; } else relogio++; // Mostra o contador de segundos no LCD while(BusyXLCD()) ; SetDDRamAddr(0x66); //linha 4 nas duas ultimas posicoes putrsXLCD ( ltoa ( NULL , relogio , 10) ); TMR1IF=0; WriteTimer1( 0xFC00 ); //TMR1IE=1; } }
void main(void) { ADCON1 = 0b11111111; // Configure all pins digital // For me it not want work without it //******** Configure LCD for four line communication and 5X7 line display ********************************* OpenXLCD(FOUR_BIT & LINES_5X7); while( BusyXLCD() ); //wait untill LCD controller is busy WriteCmdXLCD(CURSOR_OFF); while( BusyXLCD() ); WriteCmdXLCD(BLINK_OFF); while( BusyXLCD() ); //************************************************************************************************************* while(1){ //*********** Set the starting address in the LCD RAM for display. This determines the location of display ******** SetDDRamAddr(0x80); while( BusyXLCD() ); //wait untill LCD controller is busy putsXLCD(LCD_text1); //Display string of text while( BusyXLCD() ); //wait untill LCD controller is busy //********** Set the address in second line for display **************************************************** SetDDRamAddr(0xC0); while( BusyXLCD() ); //wait untill LCD controller is busy putsXLCD(LCD_text2); //Display string of text while( BusyXLCD() ); //wait untill LCD controller is busy WriteCmdXLCD(SHIFT_DISP_LEFT); while( BusyXLCD() ); } }
void main (void) { unsigned int i; bool MUDA=false; //char null_0 [sizeof(unsigned long)*8+1]; //char null_1 [sizeof(unsigned long)*8+1]; //float *input = (float*)malloc(DATA_SIZE*sizeof(float)); //float *output = (float*)malloc(DATA_SIZE*sizeof(float)); //FOSC = INTOSC_EC, the actual value for FOSC<3:0> = b'1001', which accesses the internal clock and sets RA6 as a Fosc/4 pin. // OSCCON=0b110; // 4 mhz // OSCCON=0b111; // 8 mhz // OSCCON=0b11110010; // 8 mhz , SCS<1:0> = b'10', which activates the internal oscillator. //IRCF0=0; //IRCF1=1; //IRCF2=1; // SCS1=1; // SCS0=0; /* REGISTER 2-2: OSCCON: OSCILLATOR CONTROL REGISTER IDLEN IRCF2 IRCF1 IRCF0 OSTS IOFS SCS1 SCS0 bit 7 ................................ bit 0 bit 7 IDLEN:Idle Enable bit 1= Device enters Idle mode on SLEEPinstruction 0= Device enters Sleep mode on SLEEPinstruction bit 6-4 IRCF2:IRCF0:Internal Oscillator Frequency Select bits 111= 8 MHz (INTOSC drives clock directly) 110= 4 MHz 101= 2 MHz 100= 1 MHz 011= 500 kHz 010= 250 kHz 001= 125 kHz 000= 31 kHz (from either INTOSC/256 or INTRC directly) bit 3 OSTS:Oscillator Start-up Time-out Status bit 1= Oscillator Start-up Timer time-out has expired; primary oscillator is running 0= Oscillator Start-up Timer time-out is running; primary oscillator is not ready bit 2 IOFS:INTOSC Frequency Stable bit 1= INTOSC frequency is stable 0= INTOSC frequency is not stable bit 1-0 SCS1:SCS0:System Clock Select bits 1x= Internal oscillator 01= Timer1 oscillator 00= Primary oscillator Note 1: Depends on the state of the IESO Configuration bit. 2: Source selected by the INTSRC bit (OSCTUNE<7>), see text. 3: Default output frequency of INTOSC on Reset */ TRISB=0x00; // configura PORTB para saida do LCD TRISD6=0; // configura LED TRISD7=0; // configura LED TRISD2=0; // configura LED de while TRISD3=0; // configura LED de Interrupcao TRISA0=1; // configura ENTRADA do TERMISTOR LM35 TRISA1=1; // configura ENTRADA do LDR TRISA2=1; // configura ENTRADA para botao de estado do GIE //CCP1CON=0x00; //CCP2CON=0x00; /* * If either of the CCP modules is configured in Compare * mode to generate a Special Event Trigger * (CCP1M3:CCP1M0 or CCP2M3:CCP2M0 = 1011), * this signal will reset Timer1. The trigger from CCP2 will * also start an A/D conversion if the A/D module is * enabled (see Section 15.3.4 ?Special Event Trigger? * for more information). */ ADCON1bits.PCFG=0b1101; // Configura somente as portas AN0 e AN1 como AD ADFM=1; // utiliza o total de 10 bits no ADRES /* * Página 33 de 74O bit de ADFM tem a função de organizar o resultado da * conversão A/D, de forma que o osvalores convertidos sejam justificados * a direita ou a esquerda nos registradores ADRESH e ADRESL. Caso venhamos * configurar ADFM = 1, organizamos o valor da conversão a direita,ou seja, * os oitos bits menos significativo será armazendo em ADRESL, e os 2 bits * maissignificativo serão armazenados em ADRESH.Caso ADFM = 0, * justificaremos a esquerda os valores de conversão, desta forma os * oitosbits mais significativos ficarão em ADRESH e os 2 menos * significativo ficará em ADRESL. */ for(i=0;i<10;i++) { LED2=1; LED1=0; Delay1KTCYx(50); // 50 ms LED2=0; LED1=1; Delay1KTCYx(50); } LED1=0; initLCD(); //####################################################################### //####################################################################### //####################################################################### //####################################################################### while(BusyXLCD()); WriteCmdXLCD(0x01); SetDDRamAddr(0x00); putrsXLCD ("PIC18F4550 LuzTempRF"); vw_setup(600); // inicializa o modulo RF com 600 bps // apenas um teste para imprimir o tamanho do float //sprintf(msg, "%s%d%c", "I", sizeof(float), NULL); //Delay1KTCYx(100); vw_send("INIT", 5); Delay10KTCYx(250); aferir(); // Primeira Afericao, ainda fora do contador do TIMER1 //Delay10KTCYx(250); configTimers(); // ativa os parametros de contador do TIMER1 com 500ms while (1) { if (PORTAbits.RA2) { if (!MUDA) { aferir(); GIE=1;} MUDA=true; } else { if (MUDA) { aferir();GIE=0;} MUDA=false; } LATDbits.LD2=~PORTDbits.RD2; } }
/******************************************************************** * Function Name: lcd_init() * * Return Value: void * * Parameters: void * * Description: Basée sur le coontroleur d'afficheur Hitachi* * HD44780 LCD, cette fonction initialise * * l'écran LCD * ********************************************************************/ void lcd_init() { PORTD = 0; // tous les signaux à 0 TRISD = 0xF0; // signaux de contrôle en sortie et signaux de données en entrées DelayPORXLCD(); // Delay for 15ms to allow for LCD Power on reset // Setup interface to LCD TRIS_DATA_PORT &= 0x0f; // Port données en écriture DATA_PORT &= 0x0f; // Masque pour effacer le port de données DATA_PORT |= 0b00110000; // Masque pour écrire 0011 (cmd) sur le port de données E_PIN = 1; // Clock the cmd in - Validation de l'écriture de cmd DelayxxTCY(); E_PIN = 0; // Delay for at least 4.1ms DelayXLCD(); // Setup interface to LCD DATA_PORT &= 0x0f; // On recommence à écrire cmd DATA_PORT |= 0b00110000; // E_PIN = 1; // Clock the cmd in DelayxxTCY(); E_PIN = 0; // Delay for at least 100us DelayXLCD(); // Setup interface to LCD DATA_PORT &= 0x0f; // Function set cmd DATA_PORT |= 0b00110000; E_PIN = 1; // Clock cmd in DelayxxTCY(); E_PIN = 0; DelayXLCD(); // Setup interface to LCD DATA_PORT &= 0x0f; // Function set cmd(4-bit interface) DATA_PORT |= 0b00100000; E_PIN = 1; // Clock cmd in DelayxxTCY(); E_PIN = 0; TRIS_DATA_PORT |= 0xf0; // Port de données en entrée // Set data interface width, # lines, font while(BusyXLCD()); // Wait if LCD busy WriteCmdXLCD(LCD_TYPE); // Function set cmd // Turn the display on then off while(BusyXLCD()); // Wait if LCD busy WriteCmdXLCD(DOFF&CURSOR_OFF&BLINK_OFF); // Display OFF/Blink OFF while(BusyXLCD()); // Wait if LCD busy WriteCmdXLCD(DON&CURSOR_ON&BLINK_ON); // Display ON/Blink ON // Clear display while(BusyXLCD()); // Wait if LCD busy WriteCmdXLCD(0x01); // Clear display // Set entry mode inc, no shift while(BusyXLCD()); // Wait if LCD busy WriteCmdXLCD(SHIFT_CUR_LEFT); // Entry Mode // Set DD Ram address to 0 while(BusyXLCD()); // Wait if LCD busy lcd_gotoyx(1,1); // Set Display data ram address to 0 return; }
int main( void ) { int adcvalue; char buf[20]; Setup(); //LCD display OpenXLCD(FOUR_BIT&LINES_5X7); Delay(50000); while(BusyXLCD()); SetDDRamAddr(0); putsXLCD("EE4207 Lab"); while(BusyXLCD()); SetDDRamAddr(0x40); putsXLCD("Demo 1"); while(1) { adcvalue = ReadADC(7); if (adcvalue <200 && adcvalue >=0) { LED1 = 0; LED2 = 0; LED3 = 0; LED4 = 0; } if (adcvalue <400 && adcvalue >=200) { LED1 = 1; LED2 = 0; LED3 = 0; LED4 = 0; } if (adcvalue <600 && adcvalue >=400) { LED1 = 1; LED2 = 1; LED3 = 0; LED4 = 0; } if (adcvalue <800 && adcvalue >=600) { LED1 = 1; LED2 = 1; LED3 = 1; LED4 = 0; } if (adcvalue >800) { LED1 = 1; LED2 = 1; LED3 = 1; LED4 = 1; } sprintf(buf, "%d ", adcvalue); SetDDRamAddr(0x47); putsXLCD("ADC="); SetDDRamAddr(0x4B); putsXLCD(buf); } // end while(1) } // end main
void update_EEPROM_external(char codigoev) { indwrite = endereco*8; dataEEPROMext[0] = hours; dataEEPROMext[1] = minutes; dataEEPROMext[2] = seconds; dataEEPROMext[3] = codigoev; //SetDDRamAddr(0x46); switch(codigoev){ case 1: //while( BusyXLCD() ); //putrsXLCD("I"); dataEEPROMext[4] = (int)temperatura; dataEEPROMext[5] = 0; dataEEPROMext[6] = 0; dataEEPROMext[7] = 0; writeEEPROMexterna(indwrite,dataEEPROMext); EEAckPolling(0xA0); break; case 2: //while( BusyXLCD() ); //putrsXLCD("N"); dataEEPROMext[4] = hours; dataEEPROMext[5] = minutes; dataEEPROMext[6] = seconds; dataEEPROMext[7] = 0; writeEEPROMexterna(indwrite,dataEEPROMext); //Temperatura EEAckPolling(0xA0); break; case 3: //while( BusyXLCD() ); //putrsXLCD("h"); dataEEPROMext[4] = alarme_hours; dataEEPROMext[5] = alarme_minutes; dataEEPROMext[6] = alarme_seconds; dataEEPROMext[7] = 0; writeEEPROMexterna(indwrite,dataEEPROMext); //Temperatura EEAckPolling(0xA0); break; case 4: //while( BusyXLCD() ); //putrsXLCD("t"); dataEEPROMext[4] = alarme_temp; dataEEPROMext[5] = 0; dataEEPROMext[6] = 0; dataEEPROMext[7] = 0; writeEEPROMexterna(indwrite,dataEEPROMext); //Temperatura EEAckPolling(0xA0); break; case 5: //while( BusyXLCD() ); //putrsXLCD("l"); dataEEPROMext[4]=alarme_lum; dataEEPROMext[5]=0; dataEEPROMext[6]=0; dataEEPROMext[7]=0; writeEEPROMexterna(indwrite,dataEEPROMext); //Temperatura EEAckPolling(0xA0); break; case 6: //while( BusyXLCD() ); //putrsXLCD("A"); dataEEPROMext[4] = (int)temperatura; dataEEPROMext[5] = n_lum; dataEEPROMext[6] = 0; dataEEPROMext[7] = 0; writeEEPROMexterna(indwrite,dataEEPROMext); //Temperatura EEAckPolling(0xA0); break; case 7: //while( BusyXLCD() ); //putrsXLCD("H"); dataEEPROMext[4] = (int)temperatura; dataEEPROMext[5] = n_lum; dataEEPROMext[6] = 0; dataEEPROMext[7] = 0; writeEEPROMexterna(indwrite,dataEEPROMext); //Temperatura EEAckPolling(0xA0); break; case 8: //while( BusyXLCD() ); //putrsXLCD("T"); dataEEPROMext[4] = (int)temperatura; dataEEPROMext[5] = n_lum; dataEEPROMext[6] = 0; dataEEPROMext[7] = 0; writeEEPROMexterna(indwrite,dataEEPROMext); //Temperatura EEAckPolling(0xA0); break; case 9: //while( BusyXLCD() ); //putrsXLCD("L"); dataEEPROMext[4] = (int)temperatura; dataEEPROMext[5] = n_lum; dataEEPROMext[6] = 0; dataEEPROMext[7] = 0; writeEEPROMexterna(indwrite,dataEEPROMext); //Temperatura EEAckPolling(0xA0); break; case 10: //while( BusyXLCD() ); //putrsXLCD("L"); dataEEPROMext[4] = old_PMON; dataEEPROMext[5] = PMON; dataEEPROMext[6] = 0; dataEEPROMext[7] = 0; writeEEPROMexterna(indwrite,dataEEPROMext); //Mudança PMON EEAckPolling(0xA0); break; case 11: //while( BusyXLCD() ); //putrsXLCD("L"); dataEEPROMext[4] = NREG; dataEEPROMext[5] = nr; dataEEPROMext[6] = ie; dataEEPROMext[7] = il; writeEEPROMexterna(indwrite,dataEEPROMext); //Memória Cheia EEAckPolling(0xA0); break; default: break; } endereco++; if(nr<NREG){ //nr não pode ser maior que o nº máx de registos nr++; } if(endereco == NREG + 1){ //buffer está cheio endereco = 1; } ie=endereco-1; //índice de escrita é o seguinte ao que foi escrito agora init_EEPROM_externa(); if(nr >= NREG/2 && full == 0){ //memória está meio cheia full = 1; SetDDRamAddr(0x48); while( BusyXLCD() ); putrsXLCD((const far rom char*)"M"); update_EEPROM_external(11); escrever_USART(SOM); escrever_USART(NMCH); escrever_USART((char)NREG+'0'); escrever_USART((char)nr+'0'); escrever_USART((char)ie+'0'); escrever_USART((char)il+'0'); escrever_USART(EOM); } }
// **************** Boucle principale de l'OS ****************************** // Boucle infinie qui attend des ?v?nement li?s aux interruptions pour // appeler les fonctions enregistr?es // ************************************************************************* void TIOSStart() { unsigned char idx; char j; for(j=0; j<14; j++) { TabRecuRFID[j] = 0; iRec = 0; } FlagLecture = 0; //VARAIBLES LOCALES //CONFIG PIC OSCCONbits.IRCF = 0b111; // on defini la frequence de l'oscillateur ? 16 mHz //CONFIG PIN //SELECTION AN/DI (ANSEL) ANSELA = NUM; //on place toutes les pins en num?rique, XC8 se fout des pins qu'on ne peut pas d?finir ANSELB = NUM; ANSELC = NUM; ANSELD = NUM; ANSELE = NUM; ANSELDbits.ANSD4 = ANA; //photodiode //SELECTION IN/OUT (TRIS) TRISCbits.TRISC2 = OUT; //LED en output TRISBbits.TRISB4 = OUT; //RELAIS en output TRISDbits.TRISD4 = IN; //photo diode en input //ETAT REPOS DES PINS (PORT) IO_LED = OFF; IO_REL = OFF; //Initialisation des périphériques //LCD initLCD(); //Boutons initBout(); //RFID initRFID(); //ETHERNET ethernetInit(); //Lumiere ADC InitADC(); //USART //initUsart(); INTCONbits.GIE = 1; INTCONbits.PEIE = 1; RCONbits.IPEN = 1; //Cr?ation, configuration et démarrage de Timer1 pour g?n?rer une interruption toutes les mS en priorité haute TIMER1_Init_1ms(); //A partir d'ici, interruption toutes les ms par Timer1 //Boucle principale de l'OS d'o? on ne sort jamais while(1) { ethernetEnvoi(); Delay10KTCYx(50); if(flagusart == 1){ CBUSARTRECEPT(caractere); flagusart = 0; compteurUsart=0; } // Check les conditions pour rappeler les fonctions li?es au temps for (idx = 0; idx < MAXCALLBACKCHRONO; idx++) { if (MaCB[idx]) //Si on a l'adresse d'une fonction CB ? cet index //Si on est arriv? au nombre de mS demand?, on appelle la fonction if (TickCB[idx] >= TempsCB[idx]) { TickCB[idx] = 0; MaCB[idx](); //Rappel de la fonction enregistrée! } } if(flagBout) { CBBT(bout); flagBout = 0; } if(FlagLecture) { if(iRec >= 9) //si on a tout recu { if(TabRecuRFID[7] == 0xFF) //si la lecture c'est bien passer { CBRFID(TabRecuRFID[3], TabRecuRFID[4], TabRecuRFID[5], TabRecuRFID[6]); for(j=0; j<14; j++) { TabRecuRFID[j] = 0; iRec = 0; } FlagLecture = 0; } else { CBRFID(0,0,0,0); FlagLecture = 0; for(j=0; j<14; j++) { TabRecuRFID[j] = 0; iRec = 0; } } } } if(FlagEcriture) { if(iRec >= 5) { if(TabRecuRFID[3] == 0xFF) { SetDDRamAddr(0x40); while(BusyXLCD()); putrsXLCD(" "); while(BusyXLCD()); SetDDRamAddr(0x40); while(BusyXLCD()); putrsXLCD("Ecriture OK"); for(j=0; j<14; j++) { TabRecuRFID[j] = 0; iRec = 0; } } } FlagEcriture = 0; } //Delay10KTCYx(200); } }
void rotina_modo_modificacao(void) { if(modo_modificacao == 1){ // estamos em modo modificacao if(cursor_pos >= 4){ SetDDRamAddr(0x00); // First line, first column while( BusyXLCD() ); sprintf((char*)time_s, (const rom far char*)"%d%d:%d%d:%d%d", alarme_hd, alarme_hu, alarme_md, alarme_mu, alarme_sd, alarme_su); putsXLCD(time_s); } SetDDRamAddr(0x4D); while( BusyXLCD() ); sprintf((char*)luminosidade, (const rom far char*)"L %d", alarme_lum); putsXLCD(luminosidade); SetDDRamAddr(0x40); while( BusyXLCD() ); sprintf((char*)temperatura_s, (const rom far char*)"%d%d C", alarme_temp/10, alarme_temp%10); putsXLCD(temperatura_s); SetDDRamAddr(0x0F); while( BusyXLCD() ); putrsXLCD((const rom far char*)"P"); // letra P que so aparece quando em modo modificacaoo SetDDRamAddr(0x09); while( BusyXLCD() ); putrsXLCD((const rom far char*)"ATL"); // letras ATL que aparecem quando em modo modificaoo para se definir os alarmes SetDDRamAddr(0x0D); while( BusyXLCD() ); putsXLCD(alarmes); // letra a ou A para desactivar/activar alarmes if(cursor_pos == 1){ // acertar horas SetDDRamAddr(0x00); while(PORTAbits.RA4 && cursor_pos == 1); if(cursor_pos == 1){ hours++; mudei_horas=1; Delay1KTCYx(200); if (hours == 24){ hours = 0; } hd = hours/10; hu = hours%10; while( BusyXLCD() ); sprintf((char*)change_hours, (const rom far char*)"%d%d", hd, hu); putsXLCD(change_hours); update_EEPROM_interna_relogio_hours(); } } else if(cursor_pos == 2){ // acertar minutos SetDDRamAddr(0x03); while(PORTAbits.RA4 && cursor_pos == 2); if(cursor_pos == 2){ minutes++; mudei_horas=1; Delay1KTCYx(200); if (minutes == 60){ minutes = 0; } md = minutes/10; mu = minutes%10; while( BusyXLCD() ); sprintf((char*)change_minutes, (const rom far char*)"%d%d", md, mu); putsXLCD(change_minutes); update_EEPROM_interna_relogio_minutes(); } } else if(cursor_pos == 3){ // acertar segundos SetDDRamAddr(0x06); while(PORTAbits.RA4 && cursor_pos == 3); if(cursor_pos == 4 && mudei_horas == 1){ mudei_horas == 0; update_EEPROM_external(2); } if(cursor_pos == 3){ seconds++; mudei_horas = 1; Delay1KTCYx(200); // usado para resolver debounce - delay de 50ms if (seconds == 60){ seconds = 0; } sd = seconds/10; su = seconds%10; while( BusyXLCD() ); sprintf((char*)change_seconds, (const rom far char*)"%d%d", sd, su); putsXLCD(change_seconds); } } else if(cursor_pos == 4){ // acertar alarme do relogio if(change_A == 0){ SetDDRamAddr(0x09); } else{ if(change_AH == 1){ SetDDRamAddr(0x00); // colocar o cursor no sitio das dezenas das horas } else if(change_AM == 1){ SetDDRamAddr(0x03); // colocar o cursor no sitio das dezenas dos minutos } else if(change_AS == 1){ SetDDRamAddr(0x06); // colocar o cursor no sitio das dezenas dos segundos } } if(change_A == 0){ while(PORTAbits.RA4 && cursor_pos == 4); // carregar em S2 para indicar que se quer definir alarme } if(cursor_pos == 4){ if(change_AH == 1){ SetDDRamAddr(0x00); // colocar o cursor no sitio das dezenas das horas } Delay1KTCYx(200); change_A = 1; while(PORTAbits.RA4 && change_A == 1); // carregar em S2 uma vez para incrementar as horas if(mudei_ahoras == 1 && (alarme_hours_prev != alarme_hours || alarme_minutes_prev != alarme_minutes || alarme_seconds_prev != alarme_seconds )){ mudei_ahoras = 0; update_EEPROM_interna_relogio_alarme(); update_EEPROM_external(3); } if(change_A == 1){ if(change_AH == 1){ SetDDRamAddr(0x00); alarme_hours++; Delay1KTCYx(200); if (alarme_hours == 24){ alarme_hours = 0; } alarme_hd = alarme_hours/10; alarme_hu = alarme_hours%10; while( BusyXLCD() ); sprintf((char*)change_hours_alarme, (const rom far char*)"%d%d", alarme_hd, alarme_hu); putsXLCD(change_hours_alarme); } else if(change_AM == 1){ SetDDRamAddr(0x03); alarme_minutes++; Delay1KTCYx(200); if (alarme_minutes == 60){ alarme_minutes = 0; } alarme_md = alarme_minutes/10; alarme_mu = alarme_minutes%10; while( BusyXLCD() ); sprintf((char*)change_minutes_alarme, (const rom far char*)"%d%d", alarme_md, alarme_mu); putsXLCD(change_minutes_alarme); } else if(change_AS == 1){ SetDDRamAddr(0x06); alarme_seconds++; Delay1KTCYx(200); if (alarme_seconds == 60){ alarme_seconds = 0; } alarme_sd = alarme_seconds/10; alarme_su = alarme_seconds%10; while( BusyXLCD() ); sprintf((char*)change_seconds_alarme, (const rom far char*)"%d%d", alarme_sd, alarme_su); putsXLCD(change_seconds_alarme); } } } } else if(cursor_pos == 5){ // acertar alarme da temperatura if(change_T == 0){ SetDDRamAddr(0x0A); } else{ SetDDRamAddr(0x40); } if(change_T == 0){ while(PORTAbits.RA4 && cursor_pos == 5); // carregar em S2 para indicar que se quer definir alarme } if(cursor_pos == 5){ SetDDRamAddr(0x40); // levar o cursor ate ao sitio onde aparece o nivel da temperatura Delay1KTCYx(200); change_T = 1; while(PORTAbits.RA4 && change_T == 1); if(mudei_atemp == 1 && alarme_temp_prev != alarme_temp){ mudei_atemp = 0; update_EEPROM_interna_temp_alarme(); update_EEPROM_external(4); } if(change_T == 1){ alarme_temp++; if (alarme_temp == 40){ alarme_temp = 10; } Delay1KTCYx(200); Td = alarme_temp/10; Tu = alarme_temp%10; while( BusyXLCD() ); sprintf((char*)nova_T, (const rom far char*)"%d%d", Td, Tu); putsXLCD(nova_T); } } } else if(cursor_pos == 6){ // acertar alarme da luminosidade if(change_L == 0){ SetDDRamAddr(0x0B); } else{ SetDDRamAddr(0x4F); } if(change_L == 0){ while(PORTAbits.RA4 && cursor_pos == 6); // carregar em S2 para indicar que se quer definir alarme } if(cursor_pos == 6){ SetDDRamAddr(0x4F); // levar o cursor ate ao sitio onde aparece o nivel da luminosidade Delay1KTCYx(200); change_L = 1; while(PORTAbits.RA4 && change_L == 1); // carregar novamente em S2 para incrementar "n" e definir o valor de luminosidade pretendido if(mudei_alum == 1 && alarme_lum_prev != alarme_lum){ mudei_alum = 0; update_EEPROM_interna_lum_alarme(); update_EEPROM_external(5); } if(change_L == 1){ if(alarme_lum < 5){ alarme_lum++; } else{ alarme_lum = 0; } Delay1KTCYx(200); while( BusyXLCD() ); sprintf((char*)nova_L, (const rom far char*)"%d", alarme_lum); putsXLCD(nova_L); } } } else if(cursor_pos == 7){ // activar/desactivar alarmes SetDDRamAddr(0x0D); while(PORTAbits.RA4 && cursor_pos == 7 && alarme_OFF == 1); if(d_a_alarmes == 1 && alarmes_prev[0] != alarmes[0]){ d_a_alarmes = 0; update_EEPROM_external(6); } if(cursor_pos == 7 && alarme_OFF == 1){ Delay1KTCYx(200); if(alarmes[0] == 'a'){ alarmes[0] = 'A'; } else{ alarmes[0] = 'a'; } while( BusyXLCD() ); putsXLCD(alarmes); } } else{ //activar modo poupanca de energia SetDDRamAddr(0x0F); if (modo_sleep == 0) while(PORTAbits.RA4 && cursor_pos == 8); if(cursor_pos == 8){ modo_sleep = 1; Delay1KTCYx(200); while( BusyXLCD() ); WriteCmdXLCD(DOFF); Sleep(); } } } else{ // nao esta no modo modificao SetDDRamAddr(0x00); // First line, first column while( BusyXLCD() ); sprintf((char*)time_s, (const rom far char*)"%d%d:%d%d:%d%d", hd, hu, md, mu, sd, su); putsXLCD(time_s); } }
void closeLCD(void) { WriteCmdXLCD(DOFF); while (BusyXLCD()); flagDisplayOn = 0; PORTDbits.RD7 = 1; }
void aferir (void) { unsigned short int i; unsigned short int T, L; unsigned short int temperatura, luminosidade; bool change; char msg [12]; // = "256,30,100 " (12) ou "65535,1024,1024;" (16char) piscaVermelho(); /////////////////////////////////////////////////// ADCON0bits.CHS=0b0000; //usa o AN0 para CONversao DS39626E-page 223 // AN0 = Termistor LM35 ADCON0bits.ADON=1; // liga o AD para CONversao Delay1KTCYx(1); // delay aproximado de 1 ms ADCON0bits.GO=1; // inicia a CONversao while (ADCON0bits.GO) ; // aguarda o termino da CONversao while(BusyXLCD()) ; SetDDRamAddr(0x14); //linha 2 //0123456789_123456789 putrsXLCD ("Temp: "); temperatura = ( ADRES * 500 ) / 1023 ; T = temperatura ; //temperature = (ADCResult*5.0)/10.24; //convert data into temperature (LM35 produces 10mV per degree celcius) //putrsXLCD("Temp is "); //Display "Temp is" on the screen //sprintf(buf, "%.3g", temperature ); //Convert temperature float value to string //putsXLCD(buf); //putrsXLCD ( ltoa (null_0,((ADRES*5)/1023)+9,10) ); // era usado com o ADRESL e ADRESH invertido errado //putrsXLCD ( ltoa (null_0,( ADRES * 500) / 1023 ,10) ); while(BusyXLCD()) ; putrsXLCD ( ltoa (NULL, T , 10 ) ); /* * Equacao realizada para ajustar a temperatura, com * ajuste fino de +9 graus centigrados para temperatura local * */ while(BusyXLCD()) ; putcXLCD(0xDF); // imprime o caractere de "grau" (degree) putrsXLCD ("c "); /////////////////////////////////////////////////// piscaVermelho(); //Delay10KTCYx(50); // delay aproximado de 100 ms /////////////////////////////////////////////////// ADCON0bits.CHS=0b0001; //usa o AN0 para CONversao DS39626E-page 223 // AN1 = Termistor LDR ADCON0bits.ADON=1; // liga o AD para CONversao Delay1KTCYx(1); // delay aproximado de 1 ms ADCON0bits.GO=1; // inicia a CONversao while (ADCON0bits.GO) ; // aguarda o termino da CONversao //corrente = ADRES; while(BusyXLCD()) ; //SetDDRamAddr(0x54); //linha 2 SetDDRamAddr(0x20); //0123456789_123456789 putrsXLCD ("Luz: "); luminosidade = ( ADRES / 8 ) ; L = luminosidade; while(BusyXLCD()) ; putrsXLCD ( ltoa ( NULL,L,10) ); //putrsXLCD ( ltoa (null_1,ADRES,10) ); putrsXLCD ("% "); /////////////////////////////////////////////////// if (T != temp0) { temp0=T; change=true; } else if (L != lumi0) { lumi0=L; change=true;} if (change) { contador++; if (T < min) min=T; else if (T > max) max=T; if (L < lmin) lmin=L; else if (L > lmax) lmax=L; while(BusyXLCD()) ; SetDDRamAddr(0x40); putrsXLCD ("Tmin"); putrsXLCD (ltoa (NULL,min,10)); putrsXLCD ("/"); putrsXLCD (ltoa (NULL,max,10)); putrsXLCD (" Luz"); putrsXLCD (ltoa (NULL,lmin,10)); putrsXLCD ("/"); putrsXLCD (ltoa (NULL,lmax,10)); putrsXLCD (" "); //i=sizeof(msg)-1; // apenas um teste para mostrar o tamanho da msg sprintf(msg, "%u,%u,%u%s", contador, T, L, ";"); while(BusyXLCD()) ; SetDDRamAddr(0x54); putrsXLCD (msg); putrsXLCD (" "); LED1=1; // LED Verde Ligado while(BusyXLCD()) ; SetDDRamAddr(0x66); //linha 4 nas duas ultimas posicoes //456789abcdef0123456_ putrsXLCD ("TX"); Delay1KTCYx(100); vw_send(msg, sizeof(msg)-1); LED1=0; // LED Verde Desligado while(BusyXLCD()) ; SetDDRamAddr(0x66); //linha 2 //456789abcdef0123456_ //putrsXLCD ("__"); putcXLCD ('_');putcXLCD ('_'); change=false; } }
void main(void) { //IRCF0_bit=0b0; //IRCF1_bit=0b0; //IRCF2_bit=0b1; //OSCCON=0b100; // 1mhz //OSCCON=0b001; // 125 khz //OSCCONbits.SCS1=1; // internal oscillator block OSCCONbits.IRCF0 = 0b1; OSCCONbits.IRCF1 = 0b1; OSCCONbits.IRCF2 = 0b1; //para 100 (osconbits 210), osciloscopio acusou 250 khz short int cont; TRISB = 0; TRISC = 0; /* TRISCbits.RC3=0; TRISCbits.RC2=0; TRISCbits.RC1=0; */ PORTC = 0x00; for (cont=0; cont<2; cont++) { //LATC3=1; //LATC2=1; //LATC1=1; PORTC=0b1111; Delay10KTCYx(1000); //LATC3=0; //LATC2=0; //LATC1=0; PORTC=0b0000; Delay10KTCYx(1000); } OSCCONbits.IRCF0 = 0b0; OSCCONbits.IRCF1 = 0b1; OSCCONbits.IRCF2 = 0b1; // 4mhz LATC3=0; LATC2=0; LATC1=0; Delay10KTCYx(2000); OpenXLCD(FOUR_BIT & LINES_5X7); WriteDataXLCD('H'); WriteCmdXLCD(DON&CURSOR_ON&BLINK_ON); char data[]="Finalmente Rodou"; while (1) { PORTC=0; for (cont= 0b0001 ; cont <= 0b1111 ; cont=cont*2) { PORTC = cont; Delay10KTCYx(10); } PORTC=0; OSCCONbits.IRCF0 = 0b1; OSCCONbits.IRCF1 = 0b1; OSCCONbits.IRCF2 = 0b0; // 500 khz while(BusyXLCD()); WriteCmdXLCD(0x01); Delay10KTCYx(250); OSCCONbits.IRCF0 = 0b0; OSCCONbits.IRCF1 = 0b0; OSCCONbits.IRCF2 = 0b0; // 31 khz while(BusyXLCD()); putrsXLCD("Lcd Testando.."); Delay10KTCYx(2); /* Set DDRam address to 0x40 to display data in the second line */ SetDDRamAddr(0x40); putrsXLCD(data); Delay10KTCYx(2); OSCCONbits.IRCF0 = 0b0; OSCCONbits.IRCF1 = 0b0; OSCCONbits.IRCF2 = 0b1; // 1 mhz Delay10KTCYx(1000); } }
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(); } } }
void main(void) { int onda [] = { 31, 125, 250, 500, 1000, 2000, 4000, 8000 }; char sNumero [5]; unsigned short int freq; short int i,t; ADCON1 = 0b00111111; // Make all ADC/IO pins digital OSCCON=0b000; // 31 Khz TRISA0=0; // definida saida do LED para Clock Real TRISA1=1; // definida entrada do PushBotton TRISB=0; // definida saidas para LCD na PORTB TRISC=0; // definida saidas para os LEDs na PORTC PORTAbits.RA0=1; // liga o led vermelho initLCD(); while (1) { for (freq=0b000; freq <= 0b111 ; freq++) { //OSCCON=freq; OSCCONbits.IRCF=freq; for (t=0;t<255;t++) for (i=0b0001;i<0b10000;i=i*2) { PORTC=i;} PORTC=0; while(BusyXLCD()); WriteCmdXLCD(0x01); while(BusyXLCD()); //putrsXLCD("Frequencia Clock"); //Delay10KTCYx(1); putrsXLCD( ltoa ( sNumero, ((onda[freq]*1000)/16), 10) ); putrsXLCD(" / "); putrsXLCD( ltoa (sNumero, ((onda[freq]*1000)/4), 10) ); SetDDRamAddr(0x40); // segunda linha display putrsXLCD(itoa (sNumero,onda[freq],10) ); if (freq<0b100) { putrsXLCD(" khz "); } else { putrsXLCD(" mhz "); } putrsXLCD( itoa (sNumero,freq,2)); putrsXLCD(" / "); putrsXLCD( itoa (sNumero,PORTAbits.RA1,2) ); while (PORTAbits.RA1==1) PORTAbits.RA0=~PORTAbits.RA0; PORTAbits.RA0=0; while (PORTAbits.RA1==0); PORTAbits.RA0=1; Delay10KTCYx(1); } } // fim while 1 return; }
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; }
/******************************************************************* Function Name: OpenXLCD Description: This function configure the IO pins and initializes the LCD controller the lcdtype should contain data on the type of interface and number of lines of display. Input parameters: char lcdtype Return value: none ********************************************************************/ void OpenXLCD(char lcdType) { /* Allow a delay for POR.(minimum of 15ms) */ DelayPORXLCD(); /*Initialize the data port/control pins to zero */ DATA_PIN_7 = 0; DATA_PIN_6 = 0; DATA_PIN_5 = 0; DATA_PIN_4 = 0; # ifdef EIGHT_BIT_INTERFACE DATA_PIN_3 = 0; DATA_PIN_2 = 0; DATA_PIN_1 = 0; DATA_PIN_0 = 0; #endif RW_PIN = 0; RS_PIN = 0; E_PIN = 0; /* Configure the data pins as outputs */ TRIS_DATA_PIN_7 = 0; TRIS_DATA_PIN_6 = 0; TRIS_DATA_PIN_5 = 0; TRIS_DATA_PIN_4 = 0; #ifdef EIGHT_BIT_INTERFACE TRIS_DATA_PIN_3 = 0; TRIS_DATA_PIN_2 = 0; TRIS_DATA_PIN_1 = 0; TRIS_DATA_PIN_0 = 0; #endif /* Make all control pins as outputs */ TRIS_RW = 0; TRIS_RS = 0; TRIS_E = 0; /* First Step - Function Set as specified by lcdType*/ WriteCmdXLCD(lcdType); /* wait for command completion */ while(BusyXLCD()); /* Second Step - Display ON/OFF CONTROL*/ WriteCmdXLCD(DON & BLINK_OFF & CURSOR_ON); /* wait for command completion */ while(BusyXLCD()); /* Third Step - LCD Clear */ WriteCmdXLCD(CLEAR_XLCD); /* wait for command completion */ while(BusyXLCD()); /*Fourth Step - Entry Mode Set */ WriteCmdXLCD(ENTIRE_SHIFT_OFF & INCR_MODE); /* wait for command completion */ while(BusyXLCD()); } /* end of function */
void interrupt Interrupcao(void){ char buffer[4]; /* a string buffer ira guardar um numero decimal (0 a 32) traduzido pela * funcao itoa, onde ira transformar o numero inteiro em string com apontador * o tamanho poderia ser 3, mas o inteiro vai ate 3 posicoes + null * * the buffer string variable will hold a decimal number (0 to 32) that was * converted by the itoa function, changing a integer number into a string * pointer * its size could be only 3, but the interger goes up to 3 positions + null end */ // LED_VERMELHO = ~LED_VERMELHO; // muda o status do LED_VERMELHO quando a MCU entrar em interrupcao // changes the LED_VERMELHO when the MCU interrupts // BUZZ=1; Delay100TCYx(10); BUZZ=0; // toca o buzzer para cada interrupcao // plays the buzzer for each interrupt if (RCIF) // se existe interrupcao aguardando... // teoricamente este RCIF nao precisaria de verificacao // pois se a rotina de Interrupcao ja foi chamada, entao // nem seria necessario verifica-la // mas os LED1 e LED_VERMELHO servem justamente para comprovar // que o RCIF sempre ira existir, quando mudam juntos (leds) // Theoretically this RCIF "if" check should never be necessary // but just to confirm the RCIF, the two leds (LED1 and // LED_VERMELHO) will always change together. { RCIE = 0; // desabilita interrupts de RX para tratar a entrada // disables RX interrupts to treat input LED1 = ~LED1; // muda o status do primeiro LED // inverts the LED1 status chRX = ReadUSART(); // le caractere da Serial / read a character from Serial if ( chRX>31 && chRX<127 && !BOTAO) // filtra apenas os caracteres texto comuns // just filter the common readable text characters { // Se o Echo Serial esta ativo, entao imprima o caractere na Serial // If Serial Echo is on, then send the character to Serial Port if (SerialEcho) { while (BusyUSART()); // espera nao ocupado / waits non busy WriteUSART(chRX); // envia caractere na Porta Serial // sends the character in Serial Port } // Se o LcdDisplay esta ativo, entao imprima o caractere // If Lcd Display is enabled, print the character in LCD if (LcdDisplay) { while (BusyXLCD()); WriteDataXLCD(chRX); contadorDisplay++; // contador de caracteres para tabular // LCD character tabulation count if (contadorDisplay==16) // se chegar ao final da primeira linha // if reaches the end of first line { SetDDRamAddr(0x40); // comando para pular para segunda linha // command for going to second line if (SerialEcho) { while (BusyUSART()); putrsUSART("\r\n"); // imprime RETURN e NEWLINE (inicio) // prints Carriage RETURN and Newline } } if (contadorDisplay==32) // se chegar ao final da segunda linha // if reaches the end of second line { SetDDRamAddr(0x00); // pula novamente para primeira linha // go again to first line contadorDisplay=0; // ja na primeira linha, limpa contador // in first line, clear the char counter if (SerialEcho) { while (BusyUSART()); putrsUSART("\r\n"); // imprime RETURN e NEWLINE (inicio) // prints Carriage RETURN and Newline } } } } else // filtra todos demais Controls e Caracteres Especiais // this is the state of non-text characters being filtered if (BOTAO) // se o BOTAO de debug estiver pressionado, nao filtra controle //if pushBOTTON is pressed, do not filter control characters { while (BusyUSART()); WriteUSART(chRX); } else switch (chRX) { case 0x05 : // Caractere ^E SerialEcho=!SerialEcho; while(BusyUSART()); putrsUSART("\r\n[ECHO "); if (SerialEcho) putrsUSART("ON]"); else putrsUSART("OFF]"); break; /* * Control-E: * Rotina para ligar e desligar o ECHO na porta serial * Routine to turn on and off the ECHO in serial port */ case 0x10 : // Caractere ^P LcdDisplay=!LcdDisplay; while(BusyUSART()); putrsUSART("\r\n[LCD "); if (LcdDisplay) putrsUSART("ON]"); else putrsUSART("OFF]"); break; /* * Contro-P: * Rotina para ligar e desligar a amostragem de Caractere no LCD * Routine to turn on and off the display of characters in LCD */ case 0x0C : // Caractere ^L (FormFeed) putrsUSART("\r\n[LCD CLS]"); while(BusyXLCD()); WriteCmdXLCD(0x01); // Comando para limpar o LCD contadorDisplay=0; break; /* * Control-L: (LimpaTela / FormFeed) * Rotina para Limpar a Tela * Routine to CLear Screen (CLS) */ case 0x13 : // Caractere ^S putrsUSART("\r\n[Status Lcd:"); if (LcdDisplay) putrsUSART("On"); else putrsUSART("Off"); putrsUSART(" Echo:"); if (SerialEcho) putrsUSART("On"); else putrsUSART("Off"); putrsUSART(" charLCD:"); itoa ( buffer, contadorDisplay, 10); // itoa necessita da biblioteca <stdlib.h> // itoa needs the include stdlib.h putrsUSART( buffer ); putrsUSART("]\r\n"); /* * Control-S: * Mostra o Status do Echo, do LCD, e da quantidade de caracteres * no LCD * Shows the Status of Echo, LCD and characteres number in LCD */ break; default: ; } // two Peripheral Interrupt Request (Flag) registers (PIR1 and PIR2) // RCIF: EUSART Receive Interrupt Flag bit //PIR1bits.RCIF = 0; // PIR1 no registro RCIF RCIE = 1; // Re-Habilita a Interrupcao de Recepcao // Re-Enable RX Interrupts RCIF = 0; // PIR1 no registro RCIF // limpa o registrador de interrupcao, e sai da interrupcao // clear the interrupt register, and quits it } }