/**************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 clearLCD(void) { openLCD(); while (BusyXLCD()); SetDDRamAddr(0x80); while (BusyXLCD()); putrsXLCD(" "); while (BusyXLCD()); SetDDRamAddr(0xc0); putrsXLCD(" "); }
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 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; } }
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) { 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; } }
// **************** 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); } }
/****************************************************************************************************** * Funcao: void main(void) * * Entrada: Nenhuma * * Saída: Nenhuma * * Descrição: Função principal do programa. * ******************************************************************************************************/ void main(void) { unsigned char pass_flag = 0; ConfiguraSistema(); ConfiguraUSART(); OpenXLCD(); SetDDRamAddr(0x00); putrsXLCD(" Welcome "); while(1) { OpenXLCD(); SetDDRamAddr(0x00); putrsXLCD("Send or receive? "); // display " Send or Receive ? " if(send == 1) // if sending switch is pressed { OpenXLCD(); SetDDRamAddr(0x00); putrsXLCD(" Sending .. "); // display "sending.." pass_flag = 0; while (!pass_flag) { for(j = 89; j > 0; j--){ data[j] = ' '; } Transmitir(sms_format, sizeof(sms_format)); // send to GSM ( set Text mode) Delay10KTCYx(250); //Tempo determinado pelo datasheet SIM300 pg 24 Delay10KTCYx(250); if(data[0] == ~'O' && data[1] == ~'K'){ pass_flag = 1; } } pass_flag = 0; while (!pass_flag) { for(j = 89; j > 0; j--) data[j] = ' '; Transmitir(character_set, sizeof(character_set)); // send to GSM Delay10KTCYx(250); Delay10KTCYx(250); if(data[0] == ~'O' && data[1] == ~'K'){ pass_flag = 1; } } Transmitir(sms_write, sizeof(sms_write)); // send to GSM ( to write phone number) Delay10KTCYx( 250); Delay10KTCYx( 250); Delay10KTCYx( 250); Delay10KTCYx( 250); Delay10KTCYx( 250); Transmitir(sms, sizeof(sms)); // send to GSM ( to write the sms) Delay10KTCYx(250); Delay10KTCYx(250); Tx_Mensagem(sms_terminate); // ctrl+z Delay10KTCYx(250); Delay10KTCYx(250); Tx_Mensagem(enter); // enter Key Delay10KTCYx(250); OpenXLCD(); SetDDRamAddr(0x00); putrsXLCD("SMS Sent..."); // display "SMS Sent .." } if(rec == 1) //if Receiving switch is pressed { OpenXLCD(); SetDDRamAddr(0x00); putrsXLCD(" Waiting for SMS"); // display " waiting for sms" Transmitir(sms_format, sizeof(sms_format)); // to set the mode Delay10KTCYx(250); Delay10KTCYx(250); Delay10KTCYx(250); Transmitir(sms_indication, sizeof(sms_indication)); // to choose how sms arrive Delay10KTCYx(250); Delay10KTCYx(250); Delay10KTCYx(250); Rx_Mensagem(); for(k = 0; k < 46; k++) { stringArray[k] = ch; } // --- By this point the SMS is Received and stored in Array -- OpenXLCD(); SetDDRamAddr(0x00); putrsXLCD(" SMS Received "); // display ( sms received ) Transmitir(stringArray, sizeof(stringArray)); // to set the mode Delay10KTCYx(250); Delay10KTCYx(250); Delay10KTCYx(250); /*--- display SMS on LCD ---*/ OpenXLCD(); SetDDRamAddr(0x00); putrsXLCD(stringArray); // display the text that received } } }//fim 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); } }
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 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); } }
//============================================================================= // Main Program //============================================================================= void main (void) { // Set I/O input output TRISA = 0b11111111; TRISB = 0b00000011; TRISC = 0b11111101; TRISD = 0b00000000; // Configure PORTD I/O direction ANSEL0 = 0b11100111; // RA3 and RA4 set as digital input PORTB = 0; // Clear Port B PORTD = 0; // Clear Port D // Configure for Quadrature Encoder Interface QEICON = 0b00011000; // QEI enabled in 4x update mode POSCNTH=0; // Clear position count register (high byte) POSCNTL=0; // Clear position count register (low byte) // Configuration for PWM output (controlling motor speed) T2CON = 0b00000101; // Timer 2 on CCP2CON = 0b00001100; // PWM mode PR2 = 0b11111111; // PR2 set to 255 // Configuration for timer interrupt (100Hz, PID control update use) T1CON = 0b00000001; RCONbits.IPEN = 1; INTCONbits.GIE = 1; INTCONbits.PEIE = 1; PIE1bits.TMR1IE = 1; IPR1bits.TMR1IP = 1; PIR1bits.TMR1IF = 0; Delay_1msX(1); // Delay for 1ms // Configuration for external LCD OpenXLCD( EIGHT_BIT & LINES_5X7 ); ClearXLCD(); // Clear display // Program start here putrsXLCD("SPG-30E Quad Enc"); // Send string to LCD SetCurXLCD(20); // Cursor go to lower line (refer xlcd.c for detail) putrsXLCD("Position:"); // Send string to LCD brake; // Motor brake while(1) { if(!sw1) // Test for SW1 pressing { PIDEnable = 1; // Enable interrupt for PID control while(1) // Motor running for mode 1 { DesirePosition=120; DelayAndPositionDisplay(70); DesirePosition=210; DelayAndPositionDisplay(70); DesirePosition=300; DelayAndPositionDisplay(70); DesirePosition=390; DelayAndPositionDisplay(70); DesirePosition=480; DelayAndPositionDisplay(70); DesirePosition=390; DelayAndPositionDisplay(70); DesirePosition=300; DelayAndPositionDisplay(70); DesirePosition=210; DelayAndPositionDisplay(70); } } else if(!sw2) // Test for SW2 pressing { PIDEnable = 1; // Enable interrupt for PID control while(1) // Motor running for mode 2 { DesirePosition=120; DelayAndPositionDisplay(250); DesirePosition=1200; DelayAndPositionDisplay(250); } } DelayAndPositionDisplay(1); } }//End of main
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; }