//Slave Mode void slave(void){ while(1){ WriteUSART(27); putrsUSART (ClrScr); putrsUSART (Menu1_4); manmode(); } return; }
void main(void) { uartInit(); putrsUSART("UART initialized\r\n"); plaInit(); putrsUSART("PLA initialized\r\n"); fifosInit(); putrsUSART("FIFOs initialized\r\n"); usbInit(); putrsUSART("USB initialized\r\n"); for (;;) { processCy7c4xxFifo(); processUsbCommands(); } }
void main(void) { char msg[6]; int counter=0; initSquareWear(); // open USART, default baud rate 57600 (defined in SquareWear.h) openUSART(); putrsUSART("Begin.\r\n"); // write a constant string while(1) { itoa(counter, msg); putsUSART(msg); // write a string putrsUSART("\r\n"); latC7 = !latC7; delaySeconds(1); counter++; } }
//Encapsulates the whole testing process u8 testPart() { PartSS = 0; diff = 0; part_unit = 'm'; //mV by default pins[0] = 'X'; pins[1] = 'X'; pins[2] = 'X'; //returns the number of conducting directions between all 3 pins //On return tList, nC, diff, and other variables hold the results testConduct(); //gets the ID of the part that is most probable PartSS = getPartSS(); //switches depending on the PartSS value, here is where all the part specific functions all called part_val = switchPart(PartSS); #ifdef HAS_SERIAL_PORT putrsUSART("\n\n"); tListPrint_serial(); putrsUSART("\nPartSS: "); putINT_serial(PartSS); putcUSART('\n'); printPart_serial(); #endif #ifdef HAS_USB_CDC if (terminalF) { puts_cdc("\n\n"); tListPrint_cdc(); puts_cdc("\nPartSS: "); putINT_cdc(PartSS); putc_cdc('\n'); printPart_cdc(); } #endif #ifdef HAS_LCD printPart_lcd(); #endif if (PartSS) return 1; return 0; }
void printPart_serial() { putrsUSART(type_descs[PartSS]); if(PartSS == ERROR || PartSS >= NOID) return; putINT_serial(part_val); putcUSART(part_unit); putcUSART(' '); putrsUSART("1:"); putcUSART(pins[0]); putcUSART(' '); putrsUSART("2:"); putcUSART(pins[1]); putcUSART(' '); putrsUSART("3:"); putcUSART(pins[2]); putcUSART(' '); }
static void processCy7c4xxFifo(void) { unsigned char c; static unsigned char *cy7c4xx_buf_ptr = InDataPacket; static unsigned char len = 0; if (cy7c4xxPull(&c) != 0) return; if (len) { *cy7c4xx_buf_ptr = c; ++cy7c4xx_buf_ptr; --len; if (len == 0) { #if DEBUG if (usbfifo_debug_operation.dump_fifo_out == 1) { unsigned char l = cy7c4xx_buf_ptr-InDataPacket, i; unsigned char b[12]; putrsUSART("FIFO IN: '"); for (i=0;i<l;++i) { if (i != 0) { while (BusyUSART()); putcUSART(' '); } sprintf(b, "%02x", InDataPacket[i]); putsUSART(b); } sprintf(b, "' len=%3d\r\n", l); putsUSART(b); } if (usbfifo_debug_operation.fifo_loopback == 1) { unsigned char l = cy7c4xx_buf_ptr-InDataPacket, i; /* length of incoming packet _must_ not exceed the length of outgoing */ fifo9403aPush(l, 1); for (i=0;i<l;++i) fifo9403aPush(InDataPacket[i], 1); } #endif /* FIXME: use real ping-pong */ while (USBHandleBusy(UsbInDataHandle)); // should not loop, anyway ... UsbInDataHandle = USBGenWrite(USBGEN_DATA_EP_NUM, (BYTE*)&InDataPacket, cy7c4xx_buf_ptr-InDataPacket); while (USBHandleBusy(UsbInDataHandle)); // have to wait here as full ping-pong is not implemented // and thus we don't want data from FIFO override the data being sent here cy7c4xx_buf_ptr = InDataPacket; } } else { len = c; } }
void main(void) { char msg[1]; int value; initSquareWear(); latC7 = 0; openUSART(); putrsUSART("Type a single digit number:\r\n"); while(1) { getsUSART(msg, 1); if(msg[0]>='0' && msg[0]<='9') { value = msg[0]-'0'; if (value<10) { putrsUSART("On for "); WriteUSART(msg[0]); putrsUSART(" seconds.\r\n"); latC7 = 1; delaySeconds(value); latC7 = 0; } } } }
void interrupcao() { if (serial_interrompeu) { serial_interrompeu=0; avisa_interrompeu=1; inputstr[str_pos] = getcUSART(); //ou le_serial - vai buscar a inputstr à porta série caracter a caracter (em cada iterada) str_pos++;//incrementa a posição de escrita na string de destino if(str_pos == 30){str_pos = 0;} //verifica se a string de 80 caracteres //está cheia e caso o esteja faz reset da posição de escrita na string a 0 //comando = le_serial();//apenas um byte switch (inputstr[0]) //teste da comunicacao serial no Terminal { case 'L' : {pisca=0; nivel_alto(pin_b7);putrsUSART ( (const far rom char *) " Ligado\r\n");while (envia_byte());} //Recebe A e Transmite byte B para teste break; case 'D' : {pisca=0; nivel_baixo(pin_b7);putrsUSART ( (const far rom char *) " Desligado");while (envia_byte());} break; case 'P' : {pisca=1; printf_text(Txdata); printf_data(10); } break; } } }
// Master Mode void master(void){ while(1){ WriteUSART(27); putrsUSART (ClrScr); putrsUSART (Menu1); while(!DataRdyUSART()); //wait for data key = ReadUSART(); //read data putcUSART(key); switch (key) { case '1': { WriteUSART(27); putrsUSART (ClrScr); putrsUSART (Menu1_1); while(!DataRdyUSART()); //wait for data key = ReadUSART(); //read data break; } case '2': { trackmode(); break; } case '3': { WriteUSART(27); putrsUSART (ClrScr); putrsUSART (Menu1_3); manmode(); break; } case '4': { blink(); } default: { putrsUSART (BadKey); break; } } } }
// main application code void main() { u8 counter=0; char str[20]; // TRISBbits.TRISB7=0; init_picstar(); init_buzzer(); init_bPous; // Configure Hardware USART OpenUSART( USART_TX_INT_OFF & USART_RX_INT_OFF & USART_ASYNCH_MODE & USART_EIGHT_BIT & USART_CONT_RX & USART_BRGH_LOW, BAUD19200); //check the uard_baud.h file for available baud rates. bip(); // let's wait until we powered the PICKIT2 delay_ms(2000); // print from ROM putrsUSART( "\r\nHello World!\r\n" ); // main loop while(1) { if(bPous==0) { // bip(); // print from variable string sprintf(str,"counter= %u \r\n", counter++); putsUSART(str); delay_ms(1000); } } // end of main loop }
void main() { unsigned char c; unsigned char column; TRISA=0; TRISC=0; LATCbits.LATC4=1; // PORTA=1; // PORTB=0xFF; // PORTC=0xFF; OSCCON=0b01100000; //Internal 4MHZ Oscillator ADCON1=0x7F;//Make all ports Digital OpenUSART(USART_TX_INT_OFF &// Initialize USART, Transmit interrupt off USART_RX_INT_ON &// Receive interrupt ON USART_ASYNCH_MODE & // Use USART in asynchronous mode USART_EIGHT_BIT &// Eight bit data USART_CONT_RX &// Enable continous receiving USART_BRGH_LOW,// Do not use baud rate multiplication 12);// For a baud rate of 9600 value of SPBRGH:SPBRG register pair INTCONbits.PEIE=1;// Enable peripheral interrupts INTCONbits.GIEH=1;// Enable all interrupts // putrsUSART ("\nPlease type a S to Start"); OpenSPI(SPI_FOSC_4,MODE_01,SMPMID); // SSPCON |= SPI_FOSC_64; while(1) { putrsUSART(0x1); // WriteSPI(0x01); //UARTIntPutChar(0xa); // __delay_ms(500); // __delay_ms(50); } }
void testaColisao(void) { unsigned char data; signed char status; do { status = WriteI2C( 0xB8 | 0x00 ); //write the address of slave if(status == -1) //check if bus collision happened { while(BusyUSART()); putrsUSART("\n\rColisao.\n\r"); LED_VERM=1; data = SSPBUF; //upon bus collision detection clear the buffer, SSPCON1bits.WCOL=0; // clear the bus collision status bit } } while (status!=0); //write untill successful communication LED_VERM=0; }
//Manual Mode void manmode(void){ while(1){ while(!DataRdyUSART()); //wait for data key = ReadUSART(); //read data switch (key) { case 'A': { while(!DataRdyUSART()); //wait for data percent[0] = ReadUSART(); //read data while(!DataRdyUSART()); //wait for data percent[1] = ReadUSART(); //read data PWMA2=atoi(percent); //convert the string to an integer PWMA2=PWM_Conv*PWMA2; //convert to appropriate Duty Cycle value break; } case 'B': { while(!DataRdyUSART()); //wait for data percent[0] = ReadUSART(); //read data while(!DataRdyUSART()); //wait for data percent[1] = ReadUSART(); //read data PWMB1= atoi(percent); //convert the string to an integer PWMB1=PWM_Conv*PWMB1; //convert to appropriate Duty Cycle value break; } case 'C': { while(!DataRdyUSART()); //wait for data percent[0] = ReadUSART(); //read data while(!DataRdyUSART()); //wait for data percent[1] = ReadUSART(); //read data PWMC0= atoi(percent); //convert the string to an integer PWMC0=PWM_Conv*PWMC0; //convert to appropriate Duty Cycle value break; } case 'D': { while(!DataRdyUSART()); //wait for data percent[0] = ReadUSART(); //read data while(!DataRdyUSART()); //wait for data percent[1] = ReadUSART(); //read data PWMD3= atoi(percent); //convert the string to an integer PWMD3=PWM_Conv*PWMD3; //convert to appropriate Duty Cycle value break; } case ' ': { PWMA2=PWM_Stop; PWMB1=PWM_Stop; PWMC0=PWM_Stop; PWMD3=PWM_Stop; break; } case 27: { return; break; } default: { putrsUSART ("-"); break; } } //Upate the PWM signals Update_PWMs(); } return; }
static void processUsbCommands(void) { #if defined(USB_POLLING) // Check bus status and service USB interrupts. USBDeviceTasks(); // Interrupt or polling method. If using polling, must call // this function periodically. This function will take care // of processing and responding to SETUP transactions // (such as during the enumeration process when you first // plug in). USB hosts require that USB devices should accept // and process SETUP packets in a timely fashion. Therefore, // when using polling, this function should be called // regularly (such as once every 1.8ms or faster** [see // inline code comments in usb_device.c for explanation when // "or faster" applies]) In most cases, the USBDeviceTasks() // function does not take very long to execute (ex: <100 // instruction cycles) before it returns. #endif // Note: The user application should not begin attempting to read/write over the USB // until after the device has been fully enumerated. After the device is fully // enumerated, the USBDeviceState will be set to "CONFIGURED_STATE". if ((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return; // As the device completes the enumeration process, the UsbCbInitEP() function will // get called. In this function, we initialize the user application endpoints (in this // example code, the user application makes use of endpoint 1 IN and endpoint 1 OUT). // The USBGenRead() function call in the UsbCbInitEP() function initializes endpoint 1 OUT // and "arms" it so that it can receive a packet of data from the host. Once the endpoint // has been armed, the host can then send data to it (assuming some kind of application software // is running on the host, and the application software tries to send data to the USB device). // If the host sends a packet of data to the endpoint 1 OUT buffer, the hardware of the SIE will // automatically receive it and store the data at the memory location pointed to when we called // USBGenRead(). Additionally, the endpoint handle (in this case UsbOutCmdHandle) will indicate // that the endpoint is no longer busy. At this point, it is safe for this firmware to begin reading // from the endpoint buffer, and processing the data. In this example, we have implemented a few very // simple commands. For example, if the host sends a packet of data to the endpoint 1 OUT buffer, with the // first byte = 0x80, this is being used as a command to indicate that the firmware should "Toggle LED(s)". if (!USBHandleBusy(UsbOutCmdHandle)) { // Check if the endpoint has received any data from the host. #if DEBUG unsigned char l = USBHandleGetLength(UsbOutCmdHandle); if (usbfifo_debug_operation.dump_usb_out == 1) { unsigned char b[16]; unsigned char i; putrsUSART("USB OUT: '"); for (i=0;i<l;++i) { if (i != 0) { while (BusyUSART()); putcUSART(' '); } sprintf(b, "%02x", OutCmdPacket[i]); putsUSART(b); } sprintf(b, "' len=%3d\r\n", l); putsUSART(b); } if (usbfifo_debug_operation.usb_loopback == 1) { unsigned char i; // Now check to make sure no previous attempts to send data to the host are still pending. If any attemps are still // pending, we do not want to write to the endpoint 1 IN buffer again, until the previous transaction is complete. // Otherwise the unsent data waiting in the buffer will get overwritten and will result in unexpected behavior. while (USBHandleBusy(UsbInCmdHandle)); for (i=0;i<l;++i) InCmdPacket[i] = OutCmdPacket[i]; // The endpoint was not "busy", therefore it is safe to write to the buffer and arm the endpoint. // The USBGenWrite() function call "arms" the endpoint (and makes the handle indicate the endpoint is busy). // Once armed, the data will be automatically sent to the host (in hardware by the SIE) the next time the // host polls the endpoint. Once the data is successfully sent, the handle (in this case UsbInCmdHandle) // will indicate the the endpoint is no longer busy. UsbInCmdHandle = USBGenWrite(USBGEN_CMD_EP_NUM, (BYTE*)&InCmdPacket, l); } #endif switch (OutCmdPacket[0]) { #if DEBUG case USBFIFO_CMD_DUMP_USB_OUT: usbfifo_debug_operation.dump_usb_out ^= 1; break; case USBFIFO_CMD_DUMP_FIFO_OUT: usbfifo_debug_operation.dump_fifo_out ^= 1; break; case USBFIFO_CMD_FIFO_LOOPBACK: usbfifo_debug_operation.fifo_loopback ^= 1; break; case USBFIFO_CMD_USB_LOOPBACK: usbfifo_debug_operation.usb_loopback ^= 1; break; #endif default: { unsigned char b[8]; putrsUSART("Unexpected cmd="); sprintf(b, "0x%2X\r\n", OutCmdPacket[0]); putsUSART(b); } break; } // Re-arm the OUT endpoint for the next packet: // The USBGenRead() function call "arms" the endpoint (and makes it "busy"). If the endpoint is armed, the SIE will // automatically accept data from the host, if the host tries to send a packet of data to the endpoint. Once a data // packet addressed to this endpoint is received from the host, the endpoint will no longer be busy, and the application // can read the data which will be sitting in the buffer. UsbOutCmdHandle = USBGenRead(USBGEN_CMD_EP_NUM, (BYTE*)&OutCmdPacket, USBGEN_EP_SIZE); } if (!USBHandleBusy(UsbOutDataHandle)) { #if USBGEN_EP_SIZE > FIFO_9403A_MAX_MSG_LEN #error "Transfer of more than FIFO_9403A_MAX_MSG_LEN not implemented" #endif unsigned char l = USBHandleGetLength(UsbOutDataHandle); unsigned char i; #if DEBUG if (usbfifo_debug_operation.dump_usb_out == 1) { unsigned char b[16]; putrsUSART("USB OUT: '"); for (i=0;i<l;++i) { if (i != 0) { while (BusyUSART()); putcUSART(' '); } sprintf(b, "%02x", OutDataPacket[i]); } sprintf(b, "' len=%3d\r\n", l); putsUSART(b); } if (usbfifo_debug_operation.usb_loopback == 1) { while (USBHandleBusy(UsbInDataHandle)); // ensure that FIFO data left the device for (i=0;i<l;++i) InDataPacket[i] = OutDataPacket[i]; /* FIXME: use real ping-pong */ UsbInDataHandle = USBGenWrite(USBGEN_DATA_EP_NUM, (BYTE*)&InDataPacket, l); while (USBHandleBusy(UsbInDataHandle)); // have to wait here as full ping-pong is not implemented // and thus we don't want data from FIFO override the data being sent here } #endif fifo9403aPush(l, 1); for (i=0;i<l;++i) fifo9403aPush(OutDataPacket[i], 1); UsbOutDataHandle = USBGenRead(USBGEN_DATA_EP_NUM, (BYTE*)&OutDataPacket, USBGEN_EP_SIZE); } }
void TaskTxSerial(void *pdata) { #if OS_CRITICAL_METHOD == 3 OS_CPU_SR cpu_sr; #endif struct AdcMsg *Sensores; INT8U err; INT16S Sensor1; INT16S Sensor2; INT16S Sensor3; INT16U Acumulador1; INT16U Acumulador2; INT16U Acumulador3; INT8U contador; INT16U ValorTeclado; INT8S strTx1[5]; INT8S strTx2[5]; INT8S strTx3[5]; for(;;) { OSSemPend(STaskTxSerial,0,&err); Acumulador1=0; Acumulador2=0; Acumulador3=0; for(contador=0 ; contador<10 ; contador++) { Sensores = (struct AdcMsg *) OSQPend(QueueADC0, 0, &err); Acumulador1+=Sensores->adc0; Acumulador2+=Sensores->adc1; Acumulador3+=Sensores->adc2; OSMemPut(dMemory,Sensores); } OSSemPend(STeclado,0,&err); ValorTeclado=NumeroSensores; OSSemPost(STeclado); Sensor1=0; Sensor2=0; Sensor3=0; switch(ValorTeclado){ case 3: Sensor3 = (INT16S) Acumulador3/10; case 2: Sensor2 = (INT16S) Acumulador2/10; case 1: Sensor1 = (INT16S) Acumulador1/10; default: break; } /* itoa(Sensor1,strTx1); putsUSART(strTx1); putrsUSART(SPACE); itoa(Sensor2,strTx2); putsUSART(strTx2); putrsUSART(SPACE); itoa(Sensor3,strTx3); putsUSART(strTx3); putrsUSART(CRLF); */ if(NumeroSensores > 0){ itoa(Sensor1,strTx1); putsUSART(strTx1); putrsUSART(SPACE); if(NumeroSensores > 1){ itoa(Sensor2,strTx2); putsUSART(strTx2); putrsUSART(SPACE); } if(NumeroSensores > 2){ itoa(Sensor3,strTx3); putsUSART(strTx3); } putrsUSART(CRLF); } //OSSemPost(STask1); OSTimeDly(10); } }
// Track Mode // Assume motor A and B are front left and right, motor C and D are back left and right // Num pad controls A/C and B/D void trackmode(void){ WriteUSART(27); putrsUSART (ClrScr); putrsUSART (Menu1_2); while(1){ while(!DataRdyUSART()); //wait for data key = ReadUSART(); //read data switch (key) { case 'W': { if(PWMA2+PWM_Step<=PWM_DC_Max)PWMA2=PWMA2+PWM_Step; else PWMA2=PWM_DC_Max; if(PWMB1+PWM_Step<=PWM_DC_Max)PWMB1=PWMB1+PWM_Step; else PWMB1=PWM_DC_Max; // PWMA2+=PWM_Step; // PWMB1+=PWM_Step; break; } case 'S': { if(PWMA2-PWM_Step>=PWM_DC_Min) PWMA2=PWMA2-PWM_Step; else PWMA2=PWM_DC_Min; if(PWMB1-PWM_Step>=PWM_DC_Min) PWMB1=PWMB1-PWM_Step; else PWMB1=PWM_DC_Min; // PWMA2-=PWM_Step; // PWMB1-=PWM_Step; break; } case 'A': { if(PWMA2-PWM_Step>=PWM_DC_Min) PWMA2=PWMA2-PWM_Step; else PWMA2=PWM_DC_Min; if(PWMB1+PWM_Step<=PWM_DC_Max) PWMB1=PWMB1+PWM_Step; else PWMB1=PWM_DC_Max; // PWMA2-=PWM_Step; // PWMB1+=PWM_Step; break; } case 'D': { if(PWMA2+PWM_Step<=PWM_DC_Max) PWMA2=PWMA2+PWM_Step; else PWMA2=PWM_DC_Max; if(PWMB1-PWM_Step>=PWM_DC_Min) PWMB1=PWMB1-PWM_Step; else PWMB1=PWM_DC_Min; // PWMA2+=PWM_Step; // PWMB1-=PWM_Step; break; } case 'N': { RC=0; RD=0; break; } case 'K': { RC=1; RD=1; break; } case 'O': { RC=1; RD=0; break; } case 'M': { RE=0; RF=0; break; } case 'L': { RE=1; RF=1; break; } case 'P': { RE=1; RF=0; break; } case ' ': { PWMA2=PWM_Stop; PWMB1=PWM_Stop; PWMC0=PWM_Stop; PWMD3=PWM_Stop; RC=0; RD=0; break; } case 27: { return; break; } default: { putrsUSART (BadKey); break; } } //Set Channels C and D from Channels A and B, respectivley PWMC0=PWMA2; PWMD3=PWMB1; //Upate the PWM signals Update_PWMs(); } return; }
void tListPrint_serial() { u8 i, t1; u16 t2; putrsUSART("\nVcc:"); putINT_serial(VCC); putrsUSART("\nnC:"); putcUSART(nC + '0'); putrsUSART("\ndiff:"); putcUSART(diff + '0'); for (i = 0; i < 12; i++) { putrsUSART("\nCP"); putcUSART(i + '1'); putrsUSART(": "); t1 = (u8) tList[i][0]; putcUSART(t1 + '0'); putrsUSART("->"); t1 = (u8) tList[i][1]; putcUSART(t1 + '0'); putrsUSART(" Value: "); t2 = tList[i][2]; putINT_serial(t2); } for (i = 0; i < 3; i++) { putrsUSART("\ntIN"); putcUSART(i + '1'); putrsUSART(": "); putcUSART(tIN[i] + '0'); } for (i = 0; i < 3; i++) { putrsUSART("\ntOUT"); putcUSART(i + '1'); putrsUSART(": "); putcUSART(tOUT[i] + '0'); } for (i = 0; i < 3; i++) { putrsUSART("\ntC"); putcUSART(i + '1'); putrsUSART(": "); putcUSART(tC[i] + '0'); } for (i = 0; i < 8; i++) { putrsUSART("\ntN"); putcUSART(i + '1'); putrsUSART(": "); putcUSART(tN[i] + '0'); } }
void bucket(void){ WriteUSART(27); putrsUSART (ClrScr); putrsUSART (Menu1_2); while(1){ while(!DataRdyUSART()); //wait for data key = ReadUSART(); //read data switch (key) { case 'P': { if(PWMA2+PWM_Step<=PWM_DC_Max)PWMA2=PWMA2+PWM_Step; else PWMA2=PWM_DC_Max; // PWMA2+=PWM_Step; // PWMB1+=PWM_Step; break; } case 'L': { if(PWMA2-PWM_Step>=PWM_DC_Min) PWMA2=PWMA2-PWM_Step; else PWMA2=PWM_DC_Min; // PWMA2-=PWM_Step; // PWMB1-=PWM_Step; break; } case 'O': { if(PWMD3-PWM_Step>=PWM_DC_Min) PWMD3=PWMD3-PWM_Step; else PWMD3=PWM_DC_Min; // PWMA2-=PWM_Step; // PWMB1+=PWM_Step; break; } case 'K': { if(PWMD3+PWM_Step<=PWM_DC_Max) PWMD3=PWMD3+PWM_Step; else PWMD3=PWM_DC_Max; // PWMA2+=PWM_Step; // PWMB1-=PWM_Step; break; } case ' ': { PWMA2=PWM_Stop; PWMB1=PWM_Stop; PWMC0=PWM_Stop; PWMD3=PWM_Stop; break; } case 27: { return; break; } default: { putrsUSART (BadKey); break; } } //Upate the PWM signals Update_PWMs(); } return; }
void terminalSendPString(char *str) { while(BusyUSART()); putrsUSART(str); }
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); } }
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; }
void getTemperaturaHumidade (void) { unsigned char TEMPL=0, TEMPH=0, HUMIDL=0, HUMIDH=0; unsigned char DUMMY=0, OP=0, BT=0; float humidade, temperatura; char msg[55]; LED_AMAR=1; //#define StartI2C() SSPCON2bits.SEN=1;while(SSPCON2bits.SEN) StartI2C(); // ACORDAR DEVICE __delay_us(16); WriteI2C(0xB8); // endereco Slave do AM2315 __delay_us(135); StopI2C(); //#define StopI2C() SSPCON2bits.PEN=1;while(SSPCON2bits.PEN) // com clock de 4 mhz: // 10K (100) = 1000 ms // 1K (100) = 100 ms // 1K (10) = 10 ms // 1K (2) = 2 ms // Delay100TCYx(); __delay_us(25); RestartI2C(); // REQUISITAR PEDIDO DE BYTES __delay_us(16); WriteI2C(0xB8); // endereco Slave do AM2315 __delay_us(60); // manual do AM2315 recomenda minimo de 30us WriteI2C(0x03); // byte que simboliza a temperatura __delay_us(60); WriteI2C(0x00); // start byte para leitura __delay_us(60); WriteI2C(0x04); // quantidades de bytes a serem lidos; //AckI2C(); __delay_us(16); StopI2C(); //#define StopI2C() SSPCON2bits.PEN=1;while(SSPCON2bits.PEN) __delay_ms(10); // manual do AM2315 recomenda esperar no minimo 10ms RestartI2C(); WriteI2C(0xB9); // endereco Slave do AM2315 //AckI2C(); // retirado por nao necessitar (?) __delay_us(60); // manual do AM2315 recomenda minimo de 30us IdleI2C(); OP = ReadI2C(); // 1o byte AckI2C(); IdleI2C(); BT = ReadI2C(); // 2o byte AckI2C(); IdleI2C(); HUMIDL = ReadI2C(); // 3o byte AckI2C(); IdleI2C(); HUMIDH = ReadI2C(); // 4o byte AckI2C(); IdleI2C(); TEMPL = ReadI2C(); // 5o byte AckI2C(); IdleI2C(); TEMPH = ReadI2C(); // 6o byte AckI2C(); IdleI2C(); DUMMY = ReadI2C(); // 7o byte AckI2C(); IdleI2C(); DUMMY = ReadI2C(); // 8 byte //__delay_us(16); StopI2C(); //#define StopI2C() SSPCON2bits.PEN=1;while(SSPCON2bits.PEN) LED_VERM=0; LED_AMAR=0; LED_VERD=1; // Calculos obtidos do exemplo do Arduino humidade = HUMIDL; humidade *= 256; humidade += HUMIDH; humidade /= 10; temperatura = TEMPL; temperatura *= 256; temperatura += TEMPH; temperatura /= 10; /* ou ainda RH = RHH << 8; RH |= RHL; TEMP = TEMPH << 8; TEMP |= TEMPL; */ sprintf (msg, "Temp= %0.2f, Humid= %0.2f .", temperatura, humidade); while(BusyUSART()); putsUSART(msg); while(BusyUSART()); putrsUSART("\n\r"); LED_VERD=0; }
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 } }