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 imprimir() { while(BusyUSART()); WriteUSART(35); while(BusyUSART()); WriteUSART(88); while(BusyUSART()); itoa(buf, acc_x, 10); putsUSART(&buf); //putintUSART(&acc_x); while(BusyUSART()); WriteUSART(43); while(BusyUSART()); WriteUSART(89); while(BusyUSART()); //putintUSART(&acc_y); itoa(buf, acc_y, 10); putsUSART(&buf); while(BusyUSART()); WriteUSART(43); while(BusyUSART()); WriteUSART(90); while(BusyUSART()); //putintUSART(&acc_z); itoa(buf, acc_z, 10); putsUSART(&buf); while(BusyUSART()); WriteUSART(43); while(BusyUSART()); WriteUSART(33); //itoa(buf, temperature, 10); // putsUSART(&buf); // putsUSART(&mid); //putsUSART(&start); //itoa(buf, acc_x, 10); //putintUSART(&acc_x); //putsUSART(&mid); //itoa(buf, acc_y, 10); //putsUSART(&buf); //putsUSART(&mid); //itoa(buf, acc_z, 10); //putsUSART(&buf); //putsUSART(&mid); //putsUSART(&end); //putsUSART(&enter); }
void main() { clock_int_4MHz(); habilita_interrupcao(recep_serial); taxa_serial(9600); while (1) { if(!entrada_pin_e3){Reset();}//pressionar o botão para gravação nivel_alto(pin_b7); tempo_ms(1000); nivel_baixo(pin_b7); tempo_ms(1000); //tempo_ms(2000); ultoa(d,str); // convert to string and print d - importante para sensores putsUSART(str); tempo_ms(200);// o tempo para envio de mais de um caractere // escreve_serial('A'); //while (envia_byte());// escreve só um byte //------------Transmissão Serial ---------------------------------------------------------------- putsUSART((char *) Txdata); // transmite the string if (avisa_interrompeu == 1) //foi inserido um caracter? { if(inputstr[str_pos - 1] == 'K') //0x0D o último caracter foi o ENTER? {avisa_interrompeu = 0; // printf("Comando digitado %s\r", inputstr); str_pos = 0; //reset da posição na string de buffer } } } }
void main (void) { // Interrupt configs RCONbits.IPEN = 0; // Deshabilitar prioridades INTCONbits.PEIE = 1; // Habilitar interrupciones de perifericos INTCONbits.GIE = 1; // Habilitar interrupciones globales // Inicializa el USART y lo configura a 8N1, 9600 badios OpenUSART( USART_TX_INT_OFF & // TX sin interrupciones USART_RX_INT_ON & // RX con interrupciones USART_ASYNCH_MODE & // Modo asincronico USART_EIGHT_BIT & // 8 bits de datos USART_CONT_RX & // Recepci?n continua USART_BRGH_HIGH, 129 // 9600 baudios a 20 mhz (calcular con PicBaudRate) ); // Init LCD lcd_init(); lcd_gotoxy(0,2); lcd_putrs(" Temp: "); // Safety? __delay_ms(39); while (1) { if (dataFlag != 0) { dataFlag = 0; // Convierte el float a string sprintf(strGrados, "%2.1f,", grados); if (data == 0xFD) putcUSART(0xFD); // Control else if (data == 0xFF) putsUSART(strGrados); // Env�a info } Medir_Temperatura(); __delay_ms(39); grados = Leer_DS18B20(); lcd_gotoxy(10,2); printf("%2.1f", grados); } }
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++; } }
// 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 InitializeGPS(void) { // configure USART OpenUSART( USART_TX_INT_OFF & USART_RX_INT_OFF & USART_ASYNCH_MODE & USART_EIGHT_BIT & USART_CONT_RX & USART_BRGH_LOW, 64 ); while (BusyUSART()); putsUSART(gga_off); while (BusyUSART()); putsUSART(gsa_off); while (BusyUSART()); putsUSART(gsv_off); while (BusyUSART()); putsUSART(rmc_off); while (BusyUSART()); putsUSART(gll_off); while (BusyUSART()); putsUSART(vtg_on); }
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 getDS1307(void) { int hora=0, minuto=0, segundo=0, diasemana=0, dia=0, mes=0, ano=0, dummy=0; char msg[40]; //#define StartI2C() SSPCON2bits.SEN=1;while(SSPCON2bits.SEN) LED_AMAR=1; IdleI2C(); StartI2C(); //IdleI2C(); __delay_us(16); WriteI2C( 0xD0 ); //IdleI2C(); __delay_us(60); WriteI2C( 0x00 ); IdleI2C(); __delay_us(16); //AckI2C();AckI2C();AckI2C();AckI2C();AckI2C();AckI2C();AckI2C();AckI2C(); StopI2C(); //#define StopI2C() SSPCON2bits.PEN=1;while(SSPCON2bits.PEN) //IdleI2C(); __delay_us(26); RestartI2C(); __delay_us(16); WriteI2C( 0xD1 ); __delay_us(1); IdleI2C(); segundo =ReadI2C(); AckI2C(); IdleI2C(); minuto =ReadI2C(); AckI2C(); IdleI2C(); hora =ReadI2C(); AckI2C(); IdleI2C(); diasemana=ReadI2C(); AckI2C(); IdleI2C(); dia =ReadI2C(); AckI2C(); IdleI2C(); mes =ReadI2C(); AckI2C(); IdleI2C(); ano =ReadI2C(); AckI2C(); IdleI2C(); dummy =ReadI2C(); //AckI2C(); //__delay_us(16); //IdleI2C(); //NotAckI2C(); //IdleI2C(); StopI2C(); //#define StopI2C() SSPCON2bits.PEN=1;while(SSPCON2bits.PEN) LED_VERM = 0; LED_AMAR=0; LED_VERD=1; sprintf(msg,"%xh:%xm:%xs _ dia %x/%x/%x _ ", hora,minuto,segundo,dia,mes,ano); while(BusyUSART()); putsUSART( msg ); LED_VERD=0; }
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 main(void) { /* Configure the oscillator for the device */ ConfigureOscillator(); /* Initialize I/O and Peripherals for application */ InitApp(); char i = 0; int loops = 0; int direction = 1; unsigned int servoIn[MAX_SERVOS]; unsigned int servoSorted1[MAX_SERVOS]; unsigned int servoSorted2[MAX_SERVOS]; unsigned char servoSortedId1[MAX_SERVOS]; unsigned char servoSortedId2[MAX_SERVOS]; unsigned int servoBuffer[MAX_SERVOS]; unsigned int servoBufferId[MAX_SERVOS]; //unsigned int servoBuffer[MAX_SERVOS]; unsigned char currentServo = 0; unsigned int servoValue; unsigned char sBegin[] = "Begin\n"; unsigned char sCommand[25]; for(i = 0; i < MAX_SERVOS; i++) { servoIn[i] = 0; } //Test values servoIn[0] = 0x01AA; servoIn[1] = 0x00AF; servoIn[2] = 0x0100; servoIn[3] = 0x0060; servoIn[4] = 0x0020; putsUSART((char *) sBegin); while(1) { int num = 32424; char hex[5]; //Process values SortServos(servoIn, servoBuffer, servoBufferId); PrintStatus(servoIn, servoBuffer, servoBufferId, currentServo, servoValue); ScaleServos(servoBuffer); OffsetServos(servoBuffer); //Cleanly switch out new values //ToDo: Functionize if(Servo_Set == 1) { for(i = 0; i < MAX_SERVOS; i++) { servoSorted2[i] = servoBuffer[i]; servoSortedId2[i] = servoBufferId[i]; Servo_Set = 2; } if(Servo_Switch_Flag == 1) { Servo_Times = servoSorted2; } } if(Servo_Set == 1) { for(i = 0; i < MAX_SERVOS; i++) { servoSorted2[i] = servoBuffer[i]; servoSortedId2[i] = servoBufferId[i]; Servo_Set = 2; } if(Servo_Switch_Flag == 1) { Servo_Times = servoSorted2; } } // for(int i = 0; i < MAX_SERVOS; i++) { // servoSorted2[i] = servoSortedNext[i]; // //Servo_Times = servoSorted2; // servoSet = 2; // } // // } //Read dashboard controls if(CTRLBUTTON1) { CTRLLED1 = 1; currentServo = (currentServo + 1) % MAX_SERVOS; for(int e = 0; e < 10; e++) { //__delay_ms(40); __delay_ms(10); } } else { CTRLLED1 = 0; } if(CTRLSWITCH1) { CTRLLED2 = 1; servoIn[currentServo] = servoValue; } else { CTRLLED2 = 0; } //TODO: I got bridge problems, son /* //if(DataRdyUSART()) //while (!DataRdyUSART()); //sHeader[3] = getcUSART(); while( !DataRdyUSART( ) ); //Wait for serial data //sHeader[1] = ReadUSART(); // Read buffer if (RCSTAbits.OERR) { RCSTAbits.CREN=0; RCSTAbits.CREN=1; sHeader[1] = getcUSART(); } //getsUSART((char *) sHeader, 4); // Receive data up to 24 bytes. //while (BusyUSART()); */ ConvertADC(); for(int e = 0; e < 20; e++) { //__delay_ms(40); __delay_ms(40); } while( BusyADC() ); servoValue = ReadADC(); } }
void main(void) { char c; char str[7]="ECHO:x\0"; RCONbits.IPEN = 1; // Enable priority interrupt INTCON = 0b10100000; TRISD = 0b00000000; // Configure PORTD for output PORTD = 0b00000000; // turn off all LEDs initially TRISB = 0b00000010; // Configure PORTB for output except RB1 PORTB = 0b00000000; // turn off all LEDs initially //TMR0H=0x67; //TMR0L=0x69; //T0CON=0b10000110; // configure USART OpenUSART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_ASYNCH_MODE & USART_EIGHT_BIT & USART_CONT_RX, 129); OpenADC(ADC_FOSC_64 & ADC_RIGHT_JUST & ADC_1ANA, ADC_CH0 & ADC_INT_OFF, 0); OpenTimer0(TIMER_INT_ON & T0_16BIT & T0_SOURCE_INT & T0_PS_1_64); WriteTimer0(57722); //CONFIGURAR AQUI AS INTERRUPÇÕES while (1); // stay in an infinite loop { // ADC handler ConvertADC(); while (BusyADC()); resultado = ReadADC(); // Usart handler c = getc_usart(); if (c == 'l') { PORTB = 0b00000001; } else if (c == 'd') { PORTB = 0b00000000; } else if (c == 'q') { resultado = resultado + 50; } else if (c == 'f') { resultado = resultado - 50; } // get char from USART by polling method str[5] = c; putsUSART(str); // send string to USART } }
void terminalSendString(char *str) { while(BusyUSART()); putsUSART(str); }
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); } }
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; }
/** * シリアルバッファへ書き込み * @param str 出力バッファ */ void WriteSerial(char *str) { putsUSART(str); }
void PrintStatus(unsigned int *iServos, unsigned int *iOutput, unsigned char *cIds, unsigned char cId, unsigned int iInput) { static int c = 4; unsigned char sMod[] = "Mod: "; unsigned char sId[] = " Id: "; unsigned char sInput[] = ", Input: "; unsigned char sCurrent[] = " Current: "; unsigned char sNew[] = " New: "; unsigned char sSorted[] = " Sorted: "; unsigned char sSeparator[] = ", "; unsigned char sNewline[] = "\r\n"; //Overall Values putsUSART((char *) sMod); WriteUSART((c % 10) + '0'); //This just shows activity putsUSART((char *) sId); PrintInt(cId); putsUSART((char *) sInput); PrintInt(iInput); putsUSART((char *) sNewline); //Current values putsUSART((char *) sCurrent); for(int i = 0; i < MAX_SERVOS; i++) { if(i) { putsUSART((char *) sSeparator); } PrintInt(iServos[i]); } putsUSART((char *) sNewline); //New values putsUSART((char *) sNew); for(int i = 0; i < MAX_SERVOS; i++) { if(i) { putsUSART((char *) sSeparator); } PrintInt(iOutput[i]); } putsUSART((char *) sNewline); //Sort order putsUSART((char *) sSorted); for(int i = 0; i < MAX_SERVOS; i++) { if(i) { putsUSART((char *) sSeparator); } PrintInt(cIds[i]); } putsUSART((char *) sNewline); putsUSART((char *) sNewline); c++; }
void main (void) { TRISC0=0; // Led Amar TRISC1=0; // Led Verd TRISC2=0; // LED Verm TRISC6=0; // saida TX EUSART ADCON1=0x0F; // coloca pinos I/O em modo digital (nao analogico) acordar(); unsigned int D0, D1, D2, D3, minAnterior, contador, segInicial; char msg[30]; LED_VERM=1; // inicia porta serial com 9600 bps @ 8mhz initExt7SegLCD(); // inicia barramento I2C e escreve ".12:34." pausa(1); piscaSeg(0); // Inicio do Relogio e Display contador=0; // o contador esta acima do limite (59) minAnterior=10; // o minuto nunca chegaria a 10 (forca display) while (1) { getDS1307(); sprintf(msg," _[%x:%x:%x]_", hora, minuto, segundo ); while(BusyUSART()); putsUSART( msg ); D0 = (hora & 0b00110000) >> 4; // utiliza somente 2 bits da nibble esq D1 = hora & 0b00001111; // utiliza somente 4 bits da nibble dir D2 = (minuto & 0b11110000) >> 4;// utiliza somente 4 bits da nibble esq D3 = minuto & 0b00001111; // utiliza somente 4 bits da nibble dir /* sprintf(msg,"___ %d%d:%d%d ...%xseg_ \r\n", D0, D1, D2, D3 ,segundo); while(BusyUSART()); putsUSART( msg ); */ if (D3 != minAnterior) // se mudou o minuto, entao mostre novo horario { StartI2C(); __delay_us(16); // delay experimental WriteI2C(HT16K33_ADDR << 1); WriteI2C(0x00); WriteI2C(numbertable[D0] & 0xff ); // preenche todos os bits WriteI2C(numbertable[D0] >> 8); // qualquer byte // obs: acima como foram usados somente 2 bits, alguma "sujeira" // poderia ter ficado escrita no registrador, por isso a necessidade // de "preencher" os outros bits com & 0xff WriteI2C(numbertable[ D1 ] & 0xFF ); // preenche todos os bits WriteI2C(numbertable[ D1 ] >> 8); // qualquer byte WriteI2C(0xFF); // escreve ":" sempre no segundo 0 de mostrar WriteI2C(0xFF >> 8); // qualquer byte WriteI2C(numbertable[ D2 ] & 0xFF );// preenche todos os bits WriteI2C(numbertable[ D2 ] >> 8); // qualquer byte WriteI2C(numbertable[ D3 ] & 0xFF );// preenche todos os bits WriteI2C(numbertable[ D3 ] >> 8); // qualquer byte NotAckI2C(); // encerra envio __delay_us(16); // delay experimental StopI2C(); minAnterior=D3; // variavel para proxima checagem e mudanca } pausa(1); // utiliza TIMER0 para realizar contagem precisa de 1 seg if ( (contador % 2) == 0) piscaSeg(1); // gera a piscada ":" par else piscaSeg(0); // ou impar " ", a cada mudanca de contador (seg) sprintf(msg,"\r\nSeg=%d, Cont=%d", segundo, contador ); while(BusyUSART()); putsUSART( msg ); // rotina abaixo de calculo de desvio de segundos // ainda deve ser corrigida para o algoritmo correto if (contador >= 2 ) // cont >= 40+10 { dormir(); sprintf(msg,"\r\nSeg=%d, Cont=%d (volta do sleep)", segundo, contador ); while(BusyUSART()); putsUSART( msg ); contador=0; } contador++; // incrementa controle de contagem de segundos }
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); } }
//=============================================================================================== // Main loop //=============================================================================================== void main(void) { // Creates the variable to readin the commands from the python script char reading; // Creates the controller structure and initizle the corresponding values CONTROLLER PY_GAMES_CONTROLLER; CONTROLLER_INIT(&PY_GAMES_CONTROLLER); // Set all of PORTC as outputs TRISC=0x00; // Configure UART OpenUSART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_ASYNCH_MODE &USART_EIGHT_BIT & USART_CONT_RX & USART_BRGH_HIGH, 10); Delay1KTCYx(4); while(1) { // Wait for the next branch of data to come in and store it to the reading variable while(!DataRdyUSART()); reading=ReadUSART(); // Checks to see if the current reading is equal to c, which means check to see if the controller is connected if(reading=='c') { // Sends 1 to the python script sprintf(message,"1"); putsUSART(message); Delay1KTCYx(4); } // Checks to see if reading is equal to j for joystick else if(reading=='j') { // Waits for the next data to be sent and stores it to reading while(!DataRdyUSART()); reading=ReadUSART(); // Checks to see if the next reading is equal to l, or left if(reading=='l') { // Waits for the next data to come in and stores it to reading while(!DataRdyUSART()); reading=ReadUSART(); // Checks to see if x axis data is requested if(reading=='x') { // Reads in the left joystick's x axis and sends it to the python script int result=READJOYSTICKX(&PY_GAMES_CONTROLLER.LEFT_JOYSTICK); sprintf(message,"%d",result); putsUSART(message); Delay1KTCYx(4); } // Check to see if y axis data is requested else if(reading=='y') { // Reads the left joystick's y axis and sends the results to the python script int result=READJOYSTICKY(&PY_GAMES_CONTROLLER.LEFT_JOYSTICK); sprintf(message,"%d",result); putsUSART(message); Delay1KTCYx(4); } } // Checks to see if reading is equal to r for right else if(reading=='r') { // Waits for the next data to come in and stores the results to reading while(!DataRdyUSART()); reading=ReadUSART(); // Checks to see if x axis data is requested if(reading=='x') { // Reads in the right joystick's x axis and sends the results to the python script int result=READJOYSTICKX(&PY_GAMES_CONTROLLER.RIGHT_JOYSTICK); sprintf(message,"%d",result); putsUSART(message); Delay1KTCYx(4); } // Check to see if y axis data is requested else if(reading=='y') { // Checks the right joystick's y axis and sends the results to the python script int result=READJOYSTICKY(&PY_GAMES_CONTROLLER.RIGHT_JOYSTICK); sprintf(message,"%d",result); putsUSART(message); Delay1KTCYx(4); } } } // Checks to see if reading is equal to b for button else if(reading=='b') { // Waits for the next data to come in and stores the results to reading while(!DataRdyUSART()); reading=ReadUSART(); // Checks to see if reading is equal to y for yellow button if(reading=='y') { // Checks the status of the yellow button and sends it to the python script int result=ISBUTTONPRESSED(&PY_GAMES_CONTROLLER.YELLOW_BUTTON); sprintf(message,"%d",result); putsUSART(message); Delay1KTCYx(4); } // Checks to see if reading is equal to r for red button else if(reading=='r') { // Checks the status of the red button and sends the results to the python script int result=ISBUTTONPRESSED(&PY_GAMES_CONTROLLER.RED_BUTTON); sprintf(message,"%d",result); putsUSART(message); Delay1KTCYx(4); } } } }
void Write_str(unsigned char* str) { putsUSART((char *)str); /*Passing the address of the String to the USART write function */ while(BusyUSART()); /*Wait until USART goes to idle state */ }
void SEND_TX_DATA(void) { putsUSART(TRANSMITT_DATA); while (BusyUSART()); Clear_TX_Buffer(); }