void putINT_cdc(u16 vcdc) { unsigned int temp, dvd = 10000; char i = 0, k = 0; temp = vcdc; CDC_Flush_In_Now(); for (i = 0; i < 5; i++) { temp = vcdc / dvd; if (temp) k++; if (k) putc_cdc((char) temp + '0'); vcdc = vcdc - (temp * dvd); dvd /= 10; } CDC_Flush_In_Now(); }
//setup for USB2UART void Usb2UartSetup(void) { BYTE temp; DisableEachInterrupt(); // PIE1 = {SPPI EADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE}, IRFREQ_CAPIE, T0_IE, IRRXIE, IRRAWINTIE RcIf = 0; temp = 0x8; // baud16 #ifdef USE_HNDSHK_POL_INV INTCON2bits.RBPU = 0; HNDSHK_INV_TRISpin = 1; TXRX_INV_TRISpin = 1; RTSTRISpin = 0; DTRTRISpin = 0; if (HNDSHK_INV_PORTpin) { Hold_pol = 0; } else { Hold_pol = 1; } if (!TXRX_INV_PORTpin) temp |= 0x30; #endif /* Signon not used in stand alone USB-UART mode*/ #ifndef UARTONLY putc_cdc('U'); putc_cdc('0'); putc_cdc('1'); CDC_Flush_In_Now(); #endif TRISC |= 0xC0; TXSTA = 0x24; //baudrate high RCSTA = 0x90; BAUDCON = temp; PIE1 = 0x20; IPR1bits.RCIP = 1; usb_register_sof_handler(CDCFlushOnTimeout); // For timeout value see: cdc_config.h -> IRTOY -> CDC_FLUSH_MS }
int main(void) #endif { BYTE RecvdByte; initCDC(); // setup the CDC state machine SetupBoard(); //setup the hardware, customize for your hardware usb_init(cdc_device_descriptor, cdc_config_descriptor, cdc_str_descs, USB_NUM_STRINGS); // initialize USB. TODO: Remove magic with macro usb_start(); //start the USB peripheral // PIC18 INTERRUPTS // It is the users resposibility to set up high, low or legacy mode // interrupt operation. The following macros for high and low interrupt // setup have been removed: //#define EnableUsbHighPriInterrupt() do { RCONbits.IPEN = 1; IPR2bits.USBIP = 1; INTCONbits.GIEH = 1;} while(0) // JTR new //#define EnableUsbLowPriInterrupt() do { RCONbits.IPEN = 1; IPR2bits.USBIP = 0; INTCONbits.GIEL = 1;} while(0) // JTR new // By default, the interrupt mode will be LEGACY (ISR Vector 0x08) // (Same as high priority vector wise but the operation (latency) is // not the same. Consult the data sheet for details.) // If a priority mode is enabled then this affects ALL other interrupt // sources therefore it does not belong to the usb stack to be // doing this. It is a global, user application choice. #if defined USB_INTERRUPTS // See the prj_usb_config.h file. EnableUsbPerifInterrupts(USB_TRN + USB_SOF + USB_UERR + USB_URST); #if defined __18CXX //turn on interrupts for PIC18 INTCONbits.PEIE = 1; INTCONbits.GIE = 1; #endif EnableUsbGlobalInterrupt(); // Only enables global USB interrupt. Chip interrupts must be enabled by the user (PIC18) #endif // Wait for USB to connect do { #ifndef USB_INTERRUPTS usb_handler(); #endif } while (usb_device_state < CONFIGURED_STATE); usb_register_sof_handler(CDCFlushOnTimeout); // Register our CDC timeout handler after device configured // Main echo loop do { // If USB_INTERRUPT is not defined each loop should have at least one additional call to the usb handler to allow for control transfers. #ifndef USB_INTERRUPTS usb_handler(); #endif // Receive and send method 1 // The CDC module will call usb_handler each time a BULK CDC packet is sent or received. // If there is a byte ready will return with the number of bytes available and received byte in RecvdByte if (poll_getc_cdc(&RecvdByte)) putc_cdc(RecvdByte+1); // // Receive and send method 2 // Same as poll_getc_cdc except that byte is NOT removed from queue. // This function will wait for a byte and return and remove it from the queue when it arrives. if (peek_getc_cdc(&RecvdByte)) { RecvdByte = getc_cdc(); putc_cdc(RecvdByte+1); } // Receive and send method 3 // If there is a byte ready will return with the number of bytes available and received byte in RecvdByte // use CDC_Flush_In_Now(); when it has to be sent immediately and not wait for a timeout condition. if (poll_getc_cdc(&RecvdByte)) { putc_cdc(RecvdByte+1); // CDC_Flush_In_Now(); } } while (1); } //end main
void main(void) { static BYTE ledtrig; BYTE OutByte; SetupBoard(); //setup the hardware, USB SetupRC5(); usb_init(cdc_device_descriptor, cdc_config_descriptor, cdc_str_descs, USB_NUM_STRINGS); // TODO: Remove magic with macro initCDC(); // JTR this function has been highly modified It no longer sets up CDC endpoints. usb_start(); //usbbufflush(); //flush USB input buffer system ledtrig = 1; //only shut LED off once // Never ending loop services each task in small increments while (1) { do { // if (!TestGlobalUsbInterruptEnabled()) //JTR3 added usb_handler(); ////service USB tasks Guaranteed one pass in polling mode even when usb_device_state == CONFIGURED_STATE if ((usb_device_state < DEFAULT_STATE)) { // JTR2 no suspendControl available yet || (USBSuspendControl==1) ){ LedOff(); } else if (usb_device_state < CONFIGURED_STATE) { LedOff(); } else if ((ledtrig == 1) && (usb_device_state == CONFIGURED_STATE)) { // LedOn(); ledtrig = 0; } } while(usb_device_state < CONFIGURED_STATE); //TRISB &= 0x7f; //TRISB |= 0x40; //LATB |= 0x40; //mode = IRWIDGET; //irWidgetservice(); #ifdef UARTONLY //mode = USB_UART; Usb2UartService(); // Never returns #endif // Test for commands: 0, 1, 2 (Entry to SUMP MODE.) // Do not remove from input buffer, just take a PEEK. // SUMPLogicCommand will remove from input buffer // (Standardized coding) if (peek_getc_cdc(&OutByte)) { switch (OutByte) { case 0: //SUMP clear case 1: //SUMP run case 2: //SUMP ID mode = IR_SUMP; //put IR Toy in IR_SUMP mode irSUMPservice(); // Fully self contained, does not return until exited via 0x00 command. cdc_In_len = 0; mode = IR_DECODER; SetupRC5(); break; case 'r': //IRMAN decoder mode case 'R': OutByte = getc_cdc(); // now ok to remove byte from the USB buffer SetupRC5(); mode = IR_DECODER; putc_cdc('O'); putc_cdc('K'); CDC_Flush_In_Now(); break; case 'S': //IRs Sampling Mode case 's': OutByte = getc_cdc(); // now ok to remove byte from the USB buffer mode = IR_S; irsService(); // Fully self contained, does not return until exited via 0x00 command. cdc_In_len = 0; mode = IR_DECODER; SetupRC5(); break; case 'U': case 'u': OutByte = getc_cdc(); // now ok to remove byte from the USB buffer mode = USB_UART; Usb2UartService(); break; case 'P': case 'p':// IR Widget mode OutByte = getc_cdc(); // now ok to remove byte from the USB buffer mode = IRWIDGET; GetPulseFreq(); // Never returns //GetPulseTime(); break; case 'T': case 't'://self test OutByte = getc_cdc(); // now ok to remove byte from the USB buffer SelfTest(); //run the self-test break; case 'V': case 'v':// Acquire Version OutByte = getc_cdc(); // now ok to remove byte from the USB buffer GetUsbIrToyVersion(); break; case '$'://bootloader jump OutByte = getc_cdc(); // now ok to remove byte from the USB buffer BootloaderJump(); break; default: OutByte = getc_cdc(); }//switch(OutByte } // if peek OutByte == 1 ProcessIR(); //increment IR decoder state machine }//end while(1) }//end main
void SelfTest(void) { BYTE err = 0; //error flag starts with ASCII 0 unsigned int cnt; #ifndef USBIRTOY return err; #endif #define ERROR_RXPULLUP 0b1 #define ERROR_RXACT 0b10 #define ERROR_FREQPULLUP 0b100 #define ERROR_FREQACT 0b1000 IRRXIE = 0; //disable RX interrupts T2IE = 0; //disable any Timer 2 interrupt IRRX_TRIS |= IRRX_PIN; //ir to input IRTX_LAT &= (~IRTX_PIN); //TX LED off IRTX_TRIS &= (~IRTX_PIN); CCP1CON = 0; T2CON = 0; cnt = 10000; while (cnt--); if (!(IRRX_PORT & IRRX_PIN)) err |= ERROR_RXPULLUP; //test IR RX pullup, should be high if (HardwareVersion == 2) { if (IRFREQ_CAP == 0) err |= ERROR_FREQPULLUP; //test IR Frequency detector pullup, should be high //turn IR LED solid on to test frequency detector IRTX_TRIS &= (~IRTX_PIN); //output IRTX_LAT |= IRTX_PIN; //LED on //give a little delay cnt = 1000; while (cnt--); //test IR Frequency detector, should now be off if (IRFREQ_CAP == 1) err |= ERROR_FREQACT; //LED back off IRTX_LAT &= (~IRTX_PIN); } //setup for IR TX /* * PWM registers configuration * Fosc = 48000000 Hz * Fpwm = 36144.58 Hz (Requested : 36000 Hz) * Duty Cycle = 50 % * Resolution is 10 bits * Prescaler is 4 * Ensure that your PWM pin is configured as digital output * see more details on http://www.micro-examples.com/ * this source code is provided 'as is', * use it at your own risks * http://www.micro-examples.com/public/microex-navig/doc/097-pwm-calculator */ //IRTX_TRIS &=(~IRTX_PIN); //output //IRTX_LAT&=(~IRTX_PIN); //start low T2IF = 0; //clear the interrupt flag T2IE = 0; //disable interrupts PR2 = 0b01010010; //82 T2CON = 0b00000101; CCPR1L = 0b00101001; //upper 8 bits of duty cycte CCP1CON = 0b00011100; //we leave this on for visual inspection (5-4 two LSB of duty, 3-0 set PWM) cnt = 40000; while (cnt--); if (IRRX_PORT & IRRX_PIN) err |= ERROR_RXACT; //IR LED should activate RX if (err) { LedOff(); //LED off putc_cdc('F'); //answer fail putc_cdc('A'); putc_cdc(((err & 0b1100) >> 2) + 0x30); //frequency detector error code putc_cdc((err & 0b11) + 0x30); //receiver error code CDC_Flush_In_Now(); } else {
void Task_SmartPHTApp(void) { message_t msg; adc_voltages_t *v; sensor_data_t *c; byte_t comRecvByte; if (knl_mailbox_pend(&taskMailbox, &msg) == RV_OK) { switch (msg.MsgId) { case MSG_ID_SYS_VOLTAGE_UPDATE: v = (adc_voltages_t*) msg.Param0; //tiny_printf("SYS: Vbat=%dmV, Vcc=%dmV, Vdd=%dmV, Vtft=%dmV\n", v->vbat, v->vcc, v->vdd, v->vtft); // if(v->vdd < 3000) // tty_output("SYS: system voltage is low!\n"); // if(v->vbat < 3300) // tty_output("SYS: BATTERY LOW! replace or battery can be damaged\n"); break; case MSG_ID_SYS_BATTERY_STAT: // if(msg.Param0 == BAT_CHARGE_COMPLETE) // tty_output("SYS: battery charge complete.\n"); // if(msg.Param0 == BAT_CHARGING) // tty_output("SYS: charging...\n"); // if(msg.Param0 == BAT_SHUTDOWN) // tty_output("SYS: charger shtdn.\n"); // break; break; case MSG_ID_USB_STATE_CHANGED: handle_usb_change(msg.Param0); break; case MSG_ID_SENSOR_UPDATE: c = (sensor_data_t*) msg.Param0; filter(&dashboardData.pressure, c->compensated.hp_pressure); filter(&dashboardData.humidity, c->compensated.sht_humidity); filter(&dashboardData.temperature, c->compensated.sht_temperature); update_min_max(&dashboardData.pressure); update_min_max(&dashboardData.humidity); update_min_max(&dashboardData.temperature); check_alarms(); // update waveforms wfrm_put_sample(&wfrmPressure, dashboardData.pressure.val); wfrm_put_sample(&wfrmHumidity, dashboardData.humidity.val); wfrm_put_sample(&wfrmTemperature, dashboardData.temperature.val); // Write to file write_samples_to_file(c, (rtc_time_t*) msg.Param1); gui_invalidate(&dashb); gui_invalidate(&lineplot); break; case MSG_ID_MEDIA_DETECTED: //tty_output("SDCARD: inserted."); //if(msg.Param0) tty_output(" Card is write protected!"); //tty_output("\n"); sd_register(); f_close(&samplesFile); // Mount filesystem f_mount(0, &filesystem); // Try open file; sampleFileIsOpen = try_open_file(); // Change statusbar toolbar_set_status(&statusbar, STATUS_SDCARD_PRESENT); break; case MSG_ID_MEDIA_DISAPPEARED: //tty_output("SDCARD: removed\n"); // Dismount file system f_mount(0, NULL); // Change statusbar toolbar_clear_status(&statusbar, STATUS_SDCARD_PRESENT); break; case MSG_ID_WDG_PRESSED: handle_button_press_event(msg.Param0); break; case MSG_ID_WDG_DELAYED_OP: handle_delayed_operation_event(msg.Param0); break; case MSG_ID_WDG_CHECKED: handle_button_checked_event(msg.Param0); break; case MSG_ID_WDG_INVALIDATE: // GUI needs to be redrawn gui_draw(); break; case MSG_ID_LPM_REQUEST: enter_sleep_mode(); break; case MSG_ID_TOUCH_EVENT: // // Draw cursor // if(msg.Param0 == TOUCH_EVENT_PANEL_PRESSED) // { // uint16_t i, j; // i = msg.Param1; // j = msg.Param2; // // if(i < 12) i = 12; // else if(i > 467) i = 467; // if(j < 12) j = 12; // else if(j > 260) j = 260; // // gfx_set_color(COLOR_WHITE); // gfx_draw_circle(i, j , 10); // } if(!darkenScreen) { set_brightness(lightenBrightness); } darkenScreen = bTrue; // no break, gui must get this msg too default: gui_msg(&msg); break; } } // COMMAND PARSER if(usb_device_state == CONFIGURED_STATE) if (poll_getc_cdc(&comRecvByte)) { putc_cdc(comRecvByte); // echo CDC_Flush_In_Now(); cmd_parse_char(comRecvByte); } }
void FraiseService(void) { //unsigned char c; //static char TXNtries=0; //number of tries to send the TX packet //if(FrGotLineFromUsb&&(FraiseState==fIDLE)) FrGetLineFromUsb(); //goto _fin; //FraiseState=fIDLE; /*if(fIDLE==FraiseState) { mLED_2_On(); if(FrGotLineFromUsb) { FrGetLineFromUsb(); // goto _fin; } } else { mLED_2_Off(); }*/ FrSendMessagetoUsb(); if(FraiseState==fBLIN) { if(FrRXin!=FrRXout) { while(FrRXin!=FrRXout) putchar(FrRXbuf[FrRXout++]); CDC_Flush_In_Now(); } if(FrGotLineFromUsb) FrGetLineFromUsb(); goto _fin; } INTCONbits.GIEH = 0; if(FraiseState==fIDLE) { StopTimer(); if(FrGotLineFromUsb) { FrGetLineFromUsb(); goto _fin; } //goto _fin; if(!FraiseStatus.RXFULL){ if(PollCount>=PollDelay) { PollCount=0; //while(TXSTAbits.TRMT==0); incPolledChild(); if(TST_POLLEDCHILD()) { //PIE1bits.TXIE=0; FrRXchksum=FrRXin=FrRXout=0; TXSTAbits.TX9D=1; Serial_Init_Driver(); FrSendMessagetoUsb(); INTCONbits.GIEL=0; AckChild=PolledChild(); TXREG=(PolledChild()|128); TXSTAbits.TX9D=0; TXREG=(PolledChild()|128); InitTimer(T_2SERBYTES); FraiseState=fIN; INTCONbits.GIEL=1; } } } } else if(FraiseState==fWAITACK) { if((Serial_Is_Receiver()) && TimerOut() ){ //didn't rcved ACK before Timeout StopTimer(); Serial_Init_None(); if(++FrTXtries<3) { FrTXPacketLaunch(); }// resend packet maximum 3 times else { //printf((STRING)"sT%c%c\n",HI_CHAR(AckChild),LO_CHAR(AckChild)); FraiseMessage=fmessTOUT; FraiseState=fIDLE; } } } else if(FraiseState==fIN){ if( (Serial_Is_Receiver()) && TimerOut() ){ //Timeout StopTimer(); /*if(TST_POLLEDCHILDOK()){ printf((STRING)"\nsc%c%c\n",HI_CHAR(PolledChild()),LO_CHAR(PolledChild())); CLR_POLLEDCHILDOK(); }*/ FraiseMessage=fmessLOST; //printf("fIN timeout!\n"); Serial_Init_None(); FraiseState=fIDLE; } } _fin : INTCONbits.GIEH = 1; FrSendtoUsb(); }