void loadNewData(void)
{
    if(dataAvailable==0)
    {
        dataAvailable = getsUSBUSART(USB_In_Buffer,BUFFER_SIZE);
        nextEmptyByte = dataAvailable;
        currentByte = 0;

        return;
    }
    if(dataAvailable<BUFFER_SIZE)
    {
        UINT8 oldDataAvailable = dataAvailable;
        if(currentByte<=nextEmptyByte)
        {
            dataAvailable += getsUSBUSART(USB_In_Buffer+nextEmptyByte,BUFFER_SIZE-nextEmptyByte);
            dataAvailable += getsUSBUSART(USB_In_Buffer,currentByte);
        }
        else
        {
            dataAvailable += getsUSBUSART(USB_In_Buffer+nextEmptyByte,currentByte-nextEmptyByte);
        }
        nextEmptyByte = (nextEmptyByte+(dataAvailable-oldDataAvailable))%BUFFER_SIZE;
    }
}
Esempio n. 2
0
void ProcessIO(void)
{	
	//Blink	the	LEDs according to the USB device status
	BlinkUSBStatus();
	// User	Application	USB	tasks
	if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1))	return;

	// only check	for	new	USB	buffer if the old RS232	buffer is
	// empty.	 This will cause additional	USB	packets	to be NAK'd

	// RS232_送信バッファに HostPC から届いたデータをFillする.
	if (LastRS232Out == 0) {						  
		LastRS232Out = getsUSBUSART(RS232_Out_Data,64);	//until	the	buffer is free.
		if(LastRS232Out	> 0) {
//			RS232_Out_Data_Rdy = 1;	 //	signal buffer full
			RS232cp	= 0;  // Reset the current position
		}
	}

	if(LastRS232Out && (NextUSBOut==0)) {
		//エコーバック専用:
		memcpy(USB_Out_Buffer,RS232_Out_Data,LastRS232Out);
		NextUSBOut = LastRS232Out;
		LastRS232Out = 0;
	}

	//可能なら、RS232_受信バッファの内容をHostPCに送る.
	if((USBUSARTIsTxTrfReady())	&& (NextUSBOut > 0)){
		putUSBUSART(&USB_Out_Buffer[0],	NextUSBOut);
		NextUSBOut = 0;
	}

	CDCTxService();
}
Esempio n. 3
0
void ProcessIO(void)
{   
    BYTE numBytesRead;

    //Blink the LEDs according to the USB device status
    BlinkUSBStatus();
    // User Application USB tasks
    if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return;

    if(buttonPressed)
    {
        if(stringPrinted == FALSE)
        {
            if(mUSBUSARTIsTxTrfReady())
            {
                putrsUSBUSART("Button Pressed data-- \r\n");
                stringPrinted = TRUE;
            }
        }
    }
    else
    {
        stringPrinted = FALSE;
    }

    if(USBUSARTIsTxTrfReady())
    {
		numBytesRead = getsUSBUSART(USB_Out_Buffer,64);
		if(numBytesRead != 0)
		{
			BYTE i;
	        
			for(i=0;i<numBytesRead;i++)
			{
				switch(USB_Out_Buffer[i])
				{
					case 0x0A:
					case 0x0D:
						putUSBUSART(&USB_Out_Buffer[i],numBytesRead);
						break;
                                        case 0x53://letter S to start sampling
                                                ReadADC();
                                                putUSBUSART(ADC_sample,SAMPLE_SIZE);
                                                break;
                                        case 0x51: //letter Q to stop

                                                break;
					default:
						putUSBUSART(&USB_Out_Buffer[i],numBytesRead);
						break;
				}

			}

			//putUSBUSART(USB_In_Buffer,numBytesRead);
		}
	}

    CDCTxService();
}		//end ProcessIO
Esempio n. 4
0
unsigned int usb_tty_loop(void){
    USB_BUFFER usb_task;

    /* regiao critica */
    portENTER_CRITICAL();

    if ((USBDeviceState < CONFIGURED_STATE) || (USBSuspendControl == 1)){
        portEXIT_CRITICAL();
        return 0;
    }

    if (USBUSARTIsTxTrfReady()){
        if (buffer_entrada_cont == 0) {
            buffer_entrada_cont = getsUSBUSART((char *)buffer_entrada, sizeof(buffer_entrada));
        }

        if(xQueueReceive(usb_buffer_queue, &usb_task, ( portTickType ) 10)){
            putUSBUSART((char *)usb_task.out, usb_task.co);
        }
    }

    CDCTxService();

    portEXIT_CRITICAL();

    return 1;
}
Esempio n. 5
0
/*
 * Main program entry point.
 */
int main (void)
{
	AD1PCFG = 0xFFFF;

	//Initialize all of the LED pins
	LATE |= 0x000F;
	TRISE &= 0xFFF0;

	USBDeviceInit();	//usb_device.c.  Initializes USB module SFRs and firmware
    				//variables to known states.
	PMCON = 0;

	for (;;) {
		// 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
        			  // frequently (such as once about every 100 microseconds) at any
        			  // time that a SETUP packet might reasonably be expected to
        			  // be sent by the host to your device.  In most cases, the
        			  // USBDeviceTasks() function does not take very long to
        			  // execute (~50 instruction cycles) before it returns.

		// Application-specific tasks.
		// Blink the LEDs according to the USB device status
		BlinkUSBStatus();

		// User Application USB tasks
		if (USBDeviceState >= CONFIGURED_STATE && ! (U1PWRC & PIC32_U1PWRC_USUSPEND)) {
			unsigned nbytes_read;
			static unsigned char inbuf[64], outbuf[64];
			static unsigned led3_count = 0;

			// Pull in some new data if there is new data to pull in
			nbytes_read = getsUSBUSART ((char*) inbuf, 64);
			if (nbytes_read != 0) {
				snprintf (outbuf, sizeof(outbuf),
					"Received %d bytes: %02x...\r\n",
					nbytes_read, inbuf[0]);
				putUSBUSART ((char*) outbuf, strlen (outbuf));
				mLED_2_Toggle();
				mLED_3_On();
				led3_count = 10000;
			}
			if (led3_count) {
				// Turn off LED3 when timeout expired.
				led3_count--;
				if (led3_count == 0)
					mLED_3_Off();
			}

			CDCTxService();
		}
	}
}
Esempio n. 6
0
void usbbufservice(void){
	
	if(usbbuf.cnt==0){//if the buffer is empty, get more data
		usbbuf.cnt = getsUSBUSART(usbbuf.inBuf,30);
		usbbuf.rdptr=0;
	}

}
Esempio n. 7
0
static uint8_t USB_CDC_get(void) {
    uint8_t numBytesRead;
    if (USBUSARTIsTxTrfReady() == true) {
        numBytesRead = getsUSBUSART(readBuffer, sizeof (readBuffer));
    }
    CDCTxService();
    return numBytesRead;
}
Esempio n. 8
0
void usbbufservice(void) {

    if (usbbuf.cnt == 0) {//if the buffer is empty, get more data
        usbbuf.cnt = getsUSBUSART(usbbuf.inBuf, CDC_BUFFER_SIZE); //JTR2
        usb_handler();
        usbbuf.rdptr = 0;
    }
}
Esempio n. 9
0
File: main.c Progetto: 21rcc/ioio
int main() {
  log_init();

  // If bootloader mode not requested, go immediately to app.
  if (!ShouldEnterBootloader()) {
    OscCalibrateCached();
    log_printf("Running app...");
    __asm__("goto __APP_RESET");
  }

  // We need to enter bootloader mode, wait for the boot pin to be released.
  while (!led_read());

  // Now we can start!
  led_init();
#ifdef SIGNAL_AFTER_BAD_RESET
  if (RCON & 0b1100001001000000) {
    SignalRcon();
  }
#endif

  log_printf("Hello from Bootloader!!!");
  if (IsPin1Grounded()) {
    log_printf("Erasing config.");
    EraseConfig();
  }
  OscCalibrateCached();
  Blink(5);
  USBInitialize();

  while (1) {
    // Wait for connection
    while (!(USBGetDeviceState() == CONFIGURED_STATE
      && CDCIsDtePresent())) USBTasks();

    log_printf("Connected!");
    BootProtocolInit();

    while (USBGetDeviceState() == CONFIGURED_STATE && CDCIsDtePresent()) {
      static char in_buf[64];
      USBTasks();

      BYTE size = getsUSBUSART(in_buf, sizeof(in_buf));
      if (!BootProtocolProcess(in_buf, size)) {
        log_printf("Protocol error. Will detach / re-attach.");
        USBSoftDetach();
        __delay_ms(2000);
        USBDeviceAttach();
        break;
      }
      BootProtocolTasks();
    }
    log_printf("Disconnected!");
  }
  return 0;
}
Esempio n. 10
0
/********************************************************************
 * Function:        void ProcessIO(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        This function is a place holder for other user
 *                  routines. It is a mixture of both USB and
 *                  non-USB tasks.
 *
 * Note:            None
 *******************************************************************/
void ProcessIO(void)
{   
    BYTE numBytesRead;

    //Blink the LEDs according to the USB device status

    //
    // User Application USB tasks
    //

    // If suspended, do nothing.
    if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return;

    // If character received, echo it
    if(mUSBUSARTIsTxTrfReady())
    {
        numBytesRead = getsUSBUSART(USB_Out_Buffer,64);
        if(numBytesRead != 0)
        {
            BYTE i;
            
            #ifdef NETV
            
            #else            
            for(i=0;i<numBytesRead;i++)
            {
            	USB_In_Buffer[i] = USB_Out_Buffer[i];    
            }
    
    		//Test: Send SPI word to control motor
    		if(USB_In_Buffer[0] == 'u')
    		{
		    	motor_speed += 250;
		    	if(motor_speed > 3000)
		    	motor_speed = 3000;
		    	SpiChnPutC(4, motor_speed);   
	    	}
	    	else if(USB_In_Buffer[0] == 'i')
	    	{
		    	motor_speed -= 250;
		    	if(motor_speed < -3000)
		    	motor_speed = -3000;
		    	SpiChnPutC(4, motor_speed);  
	    	}
	    	
            putUSBUSART(USB_In_Buffer,numBytesRead);	//Echo
            HBLED1 ^= 1; //Toggle LEDs
            HBLED2 ^= 1;
            #endif
        }
    }

    // Service the USB CDC driver
    CDCTxService();

} // End ProcessIO
Esempio n. 11
0
/** Procesamiento de información USB  */
void USB_process(void) {
    static char RTCC_CONF[] = "rtccconfig";
    static char RTCC_TEST[] = "rtcctest";
    static char XBEE_JOIN[] = "xbeejoin";
    static char ADC_TEST[] = "adctest";
    // Sht-11 test commands
    static char SHT[] = "shttest";

    BYTE numBytesRead;

    // Init payloads
    Payload_init(&usbInputBuffer);
    Payload_init(&usbOutputBuffer);

    // User Application USB tasks
    if ((USBDeviceState < CONFIGURED_STATE) || (USBSuspendControl == 1)) {
        return;
    }
    // Recibe un buffer de tamaño determinado
    numBytesRead = getsUSBUSART((char*)usbOutputBuffer.data, 64);

    // Si ha leído datos
    if (numBytesRead != 0) {
        if (strncmp((char*)usbOutputBuffer.data, RTCC_CONF, strlen(RTCC_CONF)) == 0) {
            Rtc_readInputStream(&usbOutputBuffer);
            Rtc_writeFormattedTimestamp(&usbInputBuffer);
        } else if (strncmp((char*)usbOutputBuffer.data, RTCC_TEST, strlen(RTCC_TEST)) == 0) {
            Rtc_readTimestamp();
            Rtc_writeFormattedTimestamp(&usbInputBuffer);
        } else if (strncmp((char*)usbOutputBuffer.data, XBEE_JOIN, strlen(XBEE_JOIN)) == 0) {
            XBee_join();
            Payload_putString(&usbInputBuffer, (UINT8*) "Join request sent");
        } else if (strncmp((char*)usbOutputBuffer.data, ADC_TEST, strlen(ADC_TEST)) == 0) {
           // TODO
            Payload_putString(&usbInputBuffer, (UINT8*) "Adc test received");
        } else if (strncmp((char*)usbOutputBuffer.data, SHT, strlen(SHT)) == 0) {
#if SHT_ENABLED
            Sht11_measure(&sht);
            Sht11_addMeasuresCalculatedToPayload(&sht, &usbInputBuffer);
#else
            Payload_putString(&usbInputBuffer, (UINT8*) "SHT11 not installed");
#endif
        } else {
            // Si el comando es erróneo, muestra un mensaje de error
            Payload_putString(&usbInputBuffer, (UINT8*) "Comando desconocido");
        }
        // Si está preparado para enviar datos
        if (USBUSARTIsTxTrfReady() && usbInputBuffer.size != 0) {
            putUSBUSART((char*)usbInputBuffer.data, (BYTE) usbInputBuffer.size);
        }
    }

    CDCTxService();
}
Esempio n. 12
0
// FIXME: implement for serial comms
BYTE GetUserMessage(char *buffer, BYTE len)
{
    if(CommsChannel == COMMS_USB)
    {
        if (mUSBUSARTIsTxTrfReady())
            return getsUSBUSART(buffer, len);
        else
            return 0;
    }
    return 0;
}
Esempio n. 13
0
uint8_t usb_char_get(char *c) {
    if (!is_usb_available()) {
        //USBCBSendResume();
        return 0;
    }
    while (!USBUSARTIsTxTrfReady()) CDCTxService();
    uint8_t ans;
    ans = getsUSBUSART(c, 1);
    CDCTxService();
    return ans;
}
Esempio n. 14
0
void ProcessIO(void)
{	
	uchar i;
	BlinkUSBStatus();		//Blink	the	LEDs according to the USB device status
	// User	Application	USB	tasks
	if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1))	return;

	// only check	for	new	USB	buffer if the old RS232	buffer is
	// empty.	 This will cause additional	USB	packets	to be NAK'd

	// RS232_送信バッファに HostPC から届いたデータをFillする.
	if( mDataRdyUSART() < 32 ) 

	if (LastRS232Out == 0) {						  
		LastRS232Out = getsUSBUSART(RS232_Out_Data,64);	//until	the	buffer is free.
		if(LastRS232Out	> 0) {
//			RS232_Out_Data_Rdy = 1;	 //	signal buffer full
			RS232cp	= 0;  // Reset the current position
		}
	}

#if	USART_USE_TX_INTERRUPT		// 送信割り込みを使用する.
	//USARTが送信可であれば RS232_送信バッファの内容を USARTに 1文字送る.
	if(LastRS232Out && mTxRdyUSART())	{
//		PIR1bits.TXIF = 0;			// 送信割り込みフラグ.
		PIE1bits.TXIE = 1;			// 送信割り込み許可.
	}
#else
	//USARTが送信可であれば RS232_送信バッファの内容を USARTに 1文字送る.
	if(LastRS232Out && mTxRdyUSART())	{
		putcUSART(RS232_Out_Data[RS232cp]);	//1文字送る.
		++RS232cp;
		if (RS232cp	== LastRS232Out) {
//			RS232_Out_Data_Rdy = 0;
			LastRS232Out=0;
			RS232cp=0;
		}
	}
#endif

	//可能なら、RS232_受信バッファの内容をHostPCに送る.
	if((USBUSARTIsTxTrfReady())	&& (mDataRdyUSART())){
		i=0;
		while( mDataRdyUSART() ) {
			if(i>=CDC_DATA_OUT_EP_SIZE) break;
			USB_Out_Buffer[i++]=getcUSART();
		}
		putUSBUSART(&USB_Out_Buffer[0],	i);
		NextUSBOut = 0;
	}

	CDCTxService();
}
Esempio n. 15
0
void ProcessIO(void)
{	
	uchar cnt;
	//Blink	the	LEDs according to the USB device status
	BlinkUSBStatus();
	// User	Application	USB	tasks
	if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1))	return;

	// only check	for	new	USB	buffer if the old RS232	buffer is
	// empty.	 This will cause additional	USB	packets	to be NAK'd

	// RS232_送信バッファに HostPC から届いたデータをFillする.
	if (LastRS232Out == 0) {						  
		LastRS232Out = getsUSBUSART(RS232_Out_Data,64);	//until	the	buffer is free.
		if(LastRS232Out	> 0) {
			RS232cp	= 0;  // Reset the current position
		}
	}

	for(cnt=0;cnt<32;cnt++) {

		//USARTが送信可であれば RS232_送信バッファの内容を USARTに 1文字送る.
		if(LastRS232Out && mTxRdyUSART())	{
			putcUSART(RS232_Out_Data[RS232cp]);	//1文字送る.
			++RS232cp;
			if (RS232cp	== LastRS232Out) {
				LastRS232Out=0;
				RS232cp=0;
			}
		}

		//USARTがデータを受信済みであれば RS232_受信バッファに溜める.
		if(mDataRdyUSART()) {
			USB_Out_Buffer[NextUSBOut] = getcUSART();
			++NextUSBOut;
			//USB_Out_Buffer[NextUSBOut] = 0;
		}

	}

	//可能なら、RS232_受信バッファの内容をHostPCに送る.
	if((USBUSARTIsTxTrfReady())	&& (NextUSBOut > 0)){
		putUSBUSART(&USB_Out_Buffer[0],	NextUSBOut);
		NextUSBOut = 0;
	}

	CDCTxService();
}
Esempio n. 16
0
BYTE cdc_get_conf(char *confstr, BYTE conflen)
{
    char uart_c;
    if (mUSBUSARTIsTxTrfReady()) {
        if (getsUSBUSART(&uart_c, 1) != 0) {
            if ((config_cycle>0) && (config_cycle<=conflen)) {
                confstr[conflen-config_cycle] = uart_c;
            }
            config_cycle--; // advance to next state
            if (config_cycle == 0)
                return 1; // do more after this function returns..
        } // if numBytesRead
    }
    config_cycle++; // correct for inactive cdc loops in up_cdc_cycle();
    return 0;
}
Esempio n. 17
0
/********************************************************************
 * Function:        void ProcessIO(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        This function is a place holder for other user
 *                  routines. It is a mixture of both USB and
 *                  non-USB tasks.
 *
 * Note:            None
 *******************************************************************/
void ProcessIO(void)
{   
    //Blink the LEDs according to the USB device status
    BlinkUSBStatus();
    // User Application USB tasks
    if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return;

	// only check for new USB buffer if the old RS232 buffer is
	// empty.
	// Additional USB packets will be NAK'd
	// until the buffer is free.
	if (RS232_Out_Data_Rdy == 0)
		{
			LastRS232Out = getsUSBUSART(RS232_Out_Data,64);
			
			if(LastRS232Out > 0)
			{
				RS232_Out_Data_Rdy = 1; // signal
										//buffer full
				RS232cp = 0;// Reset the current position
			}
		}
		
	if(RS232_Out_Data_Rdy && mTxRdyUSART())
	{
		putcUSART(RS232_Out_Data[RS232cp]);
		++RS232cp;
		if (RS232cp == LastRS232Out)
			RS232_Out_Data_Rdy = 0;
	}

	if(mDataRdyUSART())
	{
		USB_Out_Buffer[NextUSBOut] = getcUSART();
		++NextUSBOut;
		USB_Out_Buffer[NextUSBOut] = 0;
	}

	if((mUSBUSARTIsTxTrfReady()) && (NextUSBOut > 0))
	{
		putUSBUSART(&USB_Out_Buffer[0], NextUSBOut);
		NextUSBOut = 0;
	}

    CDCTxService();
}		//end ProcessIO
Esempio n. 18
0
static void CDCTasks() {
  DWORD size;

  if (channel_state > CHANNEL_DETACHED
      && USBGetDeviceState() == DETACHED_STATE) {
    // handle detach
    if (channel_state >= CHANNEL_OPEN) {
      callback(NULL, 1, callback_arg);
    }
    channel_state = CHANNEL_DETACHED;
  } else if (channel_state > CHANNEL_WAIT_DTE
      && !CDCIsDtePresent()) {
    // handle close
    if (channel_state >= CHANNEL_OPEN) {
      callback(NULL, 0, callback_arg);
    }
    channel_state = CHANNEL_WAIT_DTE;
  }

  switch (channel_state) {
    case CHANNEL_DETACHED:
      if (USBGetDeviceState() == CONFIGURED_STATE) {
        channel_state = CHANNEL_WAIT_DTE;
      }
      break;

    case CHANNEL_WAIT_DTE:
      if (CDCIsDtePresent()) {
        channel_state = CHANNEL_WAIT_OPEN;
      }
      break;

    case CHANNEL_WAIT_OPEN:
      break;

    case CHANNEL_OPEN:
      size = getsUSBUSART(rx_buf, rx_buf_size);
      if (size) {
        callback(rx_buf, size, callback_arg);
      }
      break;
  }
}
Esempio n. 19
0
// *--------------------------------------------------------------------------------*
void ProcessIO(void){   
    BYTE numBytesRead;

    //Blink the LEDs according to the USB device status
    BlinkUSBStatus();
    // User Application USB tasks
    if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return;

    if(buttonPressed){
        if(stringPrinted == FALSE){
            if(mUSBUSARTIsTxTrfReady()){
                putrsUSBUSART("Button Pressed -- \r\n");
                stringPrinted = TRUE;
            }
        }
    }else{
        stringPrinted = FALSE;
    }

    if(USBUSARTIsTxTrfReady()){
		numBytesRead = getsUSBUSART(USB_Out_Buffer,64);
		if(numBytesRead != 0){
			BYTE i;
	        
			for(i=0;i<numBytesRead;i++){
				switch(USB_Out_Buffer[i]){
					case 0x0A:
					case 0x0D:
						USB_In_Buffer[i] = USB_Out_Buffer[i];
						break;
					default:
						USB_In_Buffer[i] = USB_Out_Buffer[i] + 1;
						break;
				}
			}
			putUSBUSART(USB_In_Buffer,numBytesRead);
		}
	}

    CDCTxService();
}
Esempio n. 20
0
void processUSBData(void) {
    BYTE numBytesRead;
    // User Application USB tasks
    if ((USBDeviceState < CONFIGURED_STATE) || (USBSuspendControl == 1)) {
        return;
    }
    // Si está preparado para recibir datos
    if (mUSBUSARTIsTxTrfReady()) {
        // Recibe un buffer de tamaño determinado
        numBytesRead = getsUSBUSART(USB_Out_Buffer, 64);
        // Si ha leído datos
        if (numBytesRead != 0) {
            // FIXME Usar constantes
            if (strncmppgm2ram(USB_Out_Buffer, RTCC, strlen(RTCC)) == 0) {
                //parseRTCCData(USB_Out_Buffer);
            }
        }
    }

    CDCTxService();
}
Esempio n. 21
0
void cdc_main_menu( rom char* name_str, rom char* ver_str)
{
    char uart_c;
    if (mUSBUSARTIsTxTrfReady()) {
        if (getsUSBUSART(&uart_c, 1) != 0) {
            switch (uart_c) {
                case 't': cdc_start_set_time(); break;
                case 'T': cdc_start_stop_time(); break;
                case 'r': cdc_start_read(); break;
                case 's': cdc_start_log(); break;
                case 'v': cdc_print_ver(name_str,  ver_str); break;
                case '?': cdc_print_help(); break;
                case 'f': cdc_start_format(); break;
                case '0': cdc_start_erase(); break;
                case 'i': cdc_start_init(); break;
                case 'u': cdc_start_conf_read(); break;
                case 'w': cdc_start_conf_write(); break;
                case 'x': cdc_start_reset(); break;
            } // switch
        } // if numBytesRead!=0
    } // if (mUSBUSARTIsTxTrfReady)
}
Esempio n. 22
0
u8 CDCgets(u8 *buffer)
{
    u8 numBytesRead;
        
    #if defined(__32MX220F032D__)||defined(__32MX250F128B__)||defined(__32MX220F032B__)
        USB_Service();
        numBytesRead = USB_Service_CDC_GetString( buffer );
    #else
        CDCTxService();
        numBytesRead = getsUSBUSART(buffer, 64);
    #endif
        return numBytesRead;
/*
    if (mUSBUSARTIsTxTrfReady())
    {
        CDCTxService();
        numBytesRead = getsUSBUSART(buffer, 64);
        CDCTxService();
        return numBytesRead;
    }
*/
}
Esempio n. 23
0
void user(void)
{
	BYTE numBytesRead;
	char message[64];
	char movementCommandCode[3], movementCommandType;
	double stepDegrees, distancePerRevolution;
	
	//Blink the LEDs according to the USB device status
	//BlinkUSBStatus();
	
	// User Application USB tasks
	if( (USBDeviceState < CONFIGURED_STATE) || (USBSuspendControl == 1) ) return;

	if(USBUSARTIsTxTrfReady())
	{
		numBytesRead = getsUSBUSART(USB_Out_Buffer,64);
		if(numBytesRead != 0)
		{
			BYTE i;
			for(i = 0; i < numBytesRead; i++)
			{
				USB_In_Buffer[i] = USB_Out_Buffer[i];
			}
			USB_In_Buffer[i] = '\0';
			
			// RETURN CURRENTSTEPS POSITION
			if(!strcmppgm2ram(USB_In_Buffer, (const rom char far *)"position"))
			{
				sprintf(message, (const rom char far *)"X%ld Y%ld Z%ld|", currentStepsPosition.x, currentStepsPosition.y, currentStepsPosition.z);
				putUSBUSART(message, strlen(message));
				goto endUser;
			}
			
			// RESET CNC - stat: SERIALPORTCONNECTED
			if(!strcmppgm2ram(USB_In_Buffer, (const rom char far *)"reset"))
			{
				limitSensorX = limitSensorY = limitSensorZ = programPaused = false; //configured = programPaused = false;
				strcpypgm2ram(message, (const rom char far *)"CNCR|");
				putUSBUSART(message, strlen(message));
				machineState = SERIALPORTCONNECTED;
				goto endUser;
			}
			
			// RETURN CNC STATE
			if(!strcmppgm2ram(USB_In_Buffer, (const rom char far *)"status"))
			{
				sprintf(message, (const rom char far *)"CNCS:%d|", machineState);
				putUSBUSART(message, strlen(message));
				goto endUser;
			}
			
			// MOVE TO ORIGIN: absolute 0,0,0
			if(!strcmppgm2ram(USB_In_Buffer, (const rom char far *)"origin"))
			{
				if(programPaused)
				{
					strcpypgm2ram(message, (const rom char far *)"ERR:PP|");
					putUSBUSART(message, strlen(message));
					goto endUser;
				}
				else
				{
					MoveToOrigin();
					
					if(machineState == EMERGENCYSTOP)
					{
						sprintf(message, (const rom char far *)"ERR:PE|");
						machineState = SERIALPORTCONNECTED;
					}
					else
					{
						strcpypgm2ram(message, (const rom char far *)"PO|");
						machineState = WAITINGCOMMAND;
					}
					
					putUSBUSART(message, strlen(message));
					goto endUser;
				}
			}
			
			// START FREEMOVES
			if(strstrrampgm(USB_In_Buffer, (const rom char far *)"FM:"))
			{
				if(programPaused)
				{
					strcpypgm2ram(message, (const rom char far *)"ERR:PP|");
					putUSBUSART(message, strlen(message));
					goto endUser;
				}
				else
				{
					freeCode = GetFreeCode(USB_In_Buffer);
					if(freeCode != -2)
					{
						strcpypgm2ram(message, (const rom char far *)"CNCFM|");
						machineState = FREEMOVES;
					}
					else
					{
						strcpypgm2ram(message, (const rom char far *)"ERR:CNCFM|");
					}
					putUSBUSART(message, strlen(message));
					goto endUser;
				}
			}
			
			// STOP FREEMOVES
			if( (machineState == FREEMOVES) && (!strcmppgm2ram(USB_In_Buffer, (const rom char far *)"stop")) )
			{
				freeCode = -2;
				sprintf(message, (const rom char far *)"CNCSFM_X%ld Y%ld Z%ld|", currentStepsPosition.x, currentStepsPosition.y, currentStepsPosition.z);
				putUSBUSART(message, strlen(message));
				machineState = WAITINGCOMMAND;
				goto endUser;
			}
			
			switch(machineState)
			{
				case SERIALPORTCONNECTED:
					// Count characters received and send this number to PC
					sprintf(message, (const rom char far *)"%d|", numBytesRead);
					putUSBUSART(message, strlen(message));
					machineState = HANDSHAKEACKRECEIVED;
					break;
					
				case HANDSHAKEACKRECEIVED:
					// Compare confirmation message.
					if(!strcmppgm2ram(USB_In_Buffer, (const rom char far *)"ok"))
					{
						strcpypgm2ram(message, (const rom char far *)"MC|");
						machineState = CNCMATICCONNECTED;
					}
					else
					{
						strcpypgm2ram(message, (const rom char far *)"ERR:MNC|");
						machineState = SERIALPORTCONNECTED;
					}
						
					putUSBUSART(message, strlen(message));
					break;
					
				case WAITINGCOMMAND:
					// Tipo de codigo [ G | M ]
					movementCommandType = USB_In_Buffer[0];
					// Numero de codigo
					movementCommandCode[0] = USB_In_Buffer[1];
					movementCommandCode[1] = USB_In_Buffer[2];
					movementCommandCode[2] = '\0';
					
					// Validamos el comando
					if( ValidateCommandReceived(movementCommandType, movementCommandCode, message, &gCode, &mCode) )
					{
						strcpy(commandReceived, USB_In_Buffer);
						machineState = PROCESSINGCOMMAND;
						programPaused = false;
					}
					// mandamos el mensaje correspondiente a la PC
					putUSBUSART(message, strlen(message));
					break;
					
				default:
					break;
			}
		}
		else
		{
			switch(machineState)
			{
				case FREEMOVES:
					if(freeCode != -2)
					{
						// seteo a 1 el enable de los motores
						LATEbits.LATE2 = 1;
						
							 if( freeCode == 1)	{	StepOnX(0);	}
						else if( freeCode == 2) {	StepOnX(1);	}
						else if( freeCode == 3) {	StepOnY(1);	}
						else if( freeCode == 4) {	StepOnY(0);	}
						else if( freeCode == 5) {	StepOnZ(0);	}
						else if( freeCode == 6) {	StepOnZ(1);	}
						
						if(machineState == LIMITSENSOR)
						{
							freeCode = -2;
							limitSensorX = limitSensorY = limitSensorZ = false;
							sprintf(message, (const rom char far *)"ERR:SFC_X%ld Y%ld Z%ld|", currentStepsPosition.x, currentStepsPosition.y, currentStepsPosition.z);
							putUSBUSART(message, strlen(message));
							machineState = FREEMOVES;
						}						
					
						// seteo a 0 el enable de los motores
						LATEbits.LATE2 = 0;
					}
					break;

				case CNCMATICCONNECTED:
					MoveToOrigin();
					if(machineState == EMERGENCYSTOP)
					{
						sprintf(message, (const rom char far *)"ERR:PE|");
						machineState = SERIALPORTCONNECTED;
					}
					else
					{
						strcpypgm2ram(message, (const rom char far *)"PO|");
						machineState = WAITINGCOMMAND;
					}
					putUSBUSART(message, strlen(message));
					break;
					
				case PROCESSINGCOMMAND:
					// Processing command received
					if(gCode != -2)
					{
						if(gCode == -1)
						{
							CustomG(commandReceived);
						}
						else
						{
							gCodes[gCode](commandReceived);
						}
					}
					if(mCode != -2) { mCodes[mCode](commandReceived); }
					
					// Chequeamos machineState -> si se activo algun fin de carrera
					if(machineState == LIMITSENSOR)
					{
						limitSensorX = limitSensorY = limitSensorZ = false;
						sprintf(message, (const rom char far *)"ERR:SFC_X%ld Y%ld Z%ld|", currentStepsPosition.x, currentStepsPosition.y, currentStepsPosition.z);
						machineState = SERIALPORTCONNECTED;
					}
					else if(machineState == EMERGENCYSTOP)
					{
						sprintf(message, (const rom char far *)"ERR:PE_X%ld Y%ld Z%ld|", currentStepsPosition.x, currentStepsPosition.y, currentStepsPosition.z);
						machineState = SERIALPORTCONNECTED;
					}
					else
					{
						sprintf(message, (const rom char far *)"CMDDONE_X%ld Y%ld Z%ld|", currentStepsPosition.x, currentStepsPosition.y, currentStepsPosition.z);
						if(mCode != 2) machineState = WAITINGCOMMAND;
					}
					putUSBUSART(message, strlen(message));
					// reseteamos variables de comando
					gCode = mCode = -2;
					break;
						
				default:
					break;	
			}
		}
	}
	endUser:
		CDCTxService();
}
Esempio n. 24
0
void ProcessIO(void)
{   
    //Blink the LEDs according to the USB device status
    //BlinkUSBStatus();

    //C short circuit makes this work
    if(PORTBbits.RB13 && button_pressed < 250)
    {
        button_pressed += 1;
    }
    else if (!PORTBbits.RB13)
    {
        button_cnt = 0;
        button_pressed = 0;
    }
    
    getTouchUL();
    getTouchUR();

    getTouchRU();
    getTouchRL();

    frontBack = PORTAbits.RA8 ;
    shake = PORTBbits.RB8 ;

    // User Application USB tasks
    if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return;

    {
        unsigned char nread=0, i;

        nread = getsUSBUSART(USB_In_Buffer,64); //until the buffer is free.
        if(nread > 0) {
            /* speaker */
            //LATAbits.LATA9 = !LATAbits.LATA9;
            if (USB_In_Buffer[0] == 92)
                play_count ^= 0x8000;

            play_count |= 0x0001;
            /* serial byte led */
            //LATBbits.LATB15 = !LATBbits.LATB15;
            //LATBbits.LATB1 = 1;//!LATBbits.LATB1;

            /* contrast byte */
            if (USB_In_Buffer[0] == '-') {
               char printme[8];

               gContrast--;

               printme[0] = 48 +  (unsigned char)gContrast / 100;
               printme[1] = 48 + ((unsigned char)gContrast % 100) / 10;
               printme[2] = 48 + ((unsigned char)gContrast % 100) % 10;
               printme[3] = 0;
               LCDString(printme);

               LCDInit(); //Init the LCD

               USB_In_Buffer[0] = 0;
               nread == 0;
            }

            if ((USB_In_Buffer[0] == '=') || (USB_In_Buffer[0] == '+')) {
               char printme[8];

               gContrast++;

               printme[0] = 48 +  (unsigned char)gContrast / 100;
               printme[1] = 48 + ((unsigned char)gContrast % 100) / 10;
               printme[2] = 48 + ((unsigned char)gContrast % 100) % 10;
               printme[3] = 0;
               LCDString(printme);

               LCDInit(); //Init the LCD

               USB_In_Buffer[0] = 0;
               nread == 0;
            }

            // special character that are not echoed to LCD
            if ((USB_In_Buffer[0] == 127) 
             |  (USB_In_Buffer[0] == 27)
             |  (USB_In_Buffer[0] == '[')) {
                void LCDLogo();

                /* backspace == clear screen */
                if (USB_In_Buffer[0] == 127) LCDClear();

                /* backlight byte */
                if (USB_In_Buffer[0] == 27) LATBbits.LATB7 = !LATBbits.LATB7;

                /* hackrva logo */
                if (USB_In_Buffer[0] == '[') LCDLogo();

               USB_In_Buffer[0] = 0;
               nread == 0;
            }

            if (USB_In_Buffer[0] == ',') {
                unsigned char printme[8];
                void gotoXY(int x, int y);

                char left = G_side_slider_left;
                char right = G_side_slider_right;

                gotoXY(0, 40);
                printme[0] = 'L';
                printme[1] = 48 +  (unsigned char)left / 100;
                printme[2] = 48 + ((unsigned char)left % 100) / 10;
                printme[3] = 48 + ((unsigned char)left % 100) % 10;
                printme[4] = 32;
                printme[5] = 0;
                LCDString(printme);

                for (i=0; printme[i] !=0 ; i++)
                    USB_Out_Buffer[NextUSBOut++] = printme[i];

                USB_Out_Buffer[NextUSBOut++] = ' ';

                gotoXY(42, 40);
                printme[0] = 'R';
                printme[1] = 48 +  (unsigned char)right / 100;
                printme[2] = 48 + ((unsigned char)right % 100) / 10;
                printme[3] = 48 + ((unsigned char)right % 100) % 10;
                printme[4] = 32;
                printme[5] = 0;
                LCDString(printme);

                for (i=0; printme[i] !=0 ; i++)
                    USB_Out_Buffer[NextUSBOut++] = printme[i];

                USB_Out_Buffer[NextUSBOut++] = '\r';
                USB_Out_Buffer[NextUSBOut++] = '\n';

                USB_In_Buffer[0] = 0;
                nread == 0;
            }

            if (USB_In_Buffer[0] == '.') {
               USB_In_Buffer[0] = 0;
               nread == 0;
            }

            if (USB_In_Buffer[0] == '/') {
                unsigned char printme[16];
                void gotoXY(int x, int y);
		int setupRTCC(void);


		// shake sensor
                gotoXY(0, 41);
                printme[0] = 'S';
                printme[1] = 48 +  (unsigned char)shake / 100;
                printme[2] = 48 + ((unsigned char)shake % 100) / 10;
                printme[3] = 48 + ((unsigned char)shake % 100) % 10;
                printme[4] = 32;
                printme[5] = 0;
                LCDString(printme);

                for (i=0; printme[i] !=0 ; i++)
                    USB_Out_Buffer[NextUSBOut++] = printme[i];

                USB_Out_Buffer[NextUSBOut++] = ' ';

		// front sensor
                gotoXY(42, 41);
                printme[0] = 'F';
                printme[1] = 48 +  (unsigned char)frontBack / 100;
                printme[2] = 48 + ((unsigned char)frontBack % 100) / 10;
                printme[3] = 48 + ((unsigned char)frontBack % 100) % 10;
                printme[4] = 32;
                printme[5] = 0;
                LCDString(printme);

                for (i=0; printme[i] !=0 ; i++)
                    USB_Out_Buffer[NextUSBOut++] = printme[i];

		// secondary clock running status
               	printme[0] = hextab[(OSCCON >> 28) & 0xF];
               	printme[1] = hextab[(OSCCON >> 24) & 0xF];
               	printme[2] = hextab[(OSCCON >> 20) & 0xF];
               	printme[3] = hextab[(OSCCON >> 16) & 0xF];
               	printme[4] = hextab[(OSCCON >> 12) & 0xF];
               	printme[5] = hextab[(OSCCON >>  8) & 0xF];
               	printme[6] = hextab[(OSCCON >>  4) & 0xF];
               	printme[7] = hextab[(OSCCON      ) & 0xF];
               	printme[7] = 0;
               	LCDString(printme);

                for (i=0; printme[i] !=0 ; i++)
                    USB_Out_Buffer[NextUSBOut++] = printme[i];


               	printme[0] = 'R';
               	printme[1] = 'T';
               	printme[2] = 'C';
               	printme[3] = 'C';
               	printme[4] = ':';
               	printme[5] = setupRTCC();
               	printme[6] = 0;
               	LCDString(printme);
                for (i=0; printme[i] !=0 ; i++)
                    USB_Out_Buffer[NextUSBOut++] = printme[i];


                USB_Out_Buffer[NextUSBOut++] = '\r';
                USB_Out_Buffer[NextUSBOut++] = '\n';

                USB_In_Buffer[0] = 0;
                nread == 0;
            }

            // IR xmit
            if (USB_In_Buffer[0] == '>') {
                LATCbits.LATC1 = !LATCbits.LATC1;

                USB_In_Buffer[0] = 0;
                nread == 0;
            }

//  IR recv
#define IR_RECV PORTCbits.RC1

	    // print anything not handled above
            if (USB_In_Buffer[0] != 0)  {
               char printme[32];

               for (i=0; i<nread; i++)
                    printme[i] = USB_In_Buffer[i];

               printme[i] = 0;

               LCDString(printme);

               LCDInit(); //Init the LCD
            }

            for (i=0; i<nread; i++,NextUSBOut++) {
                USB_Out_Buffer[NextUSBOut] = USB_In_Buffer[i];
            }

        }

        // echo back to USB
        if ((USBUSARTIsTxTrfReady()) && (NextUSBOut > 0)) {
            putUSBUSART(&USB_Out_Buffer[0], NextUSBOut);
		    NextUSBOut = 0;
        }
    }
Esempio n. 25
0
/********************************************************************
 * Function:        void ProcessIO(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        This function is a place holder for other user
 *                  routines. It is a mixture of both USB and
 *                  non-USB tasks.
 *
 * Note:            None
 *******************************************************************/
void ProcessIO(void)
{   
    //Blink the LEDs according to the USB device status
    BlinkUSBStatus();
    // User Application USB tasks
    if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return;

	if (RS232_Out_Data_Rdy == 0)  // only check for new USB buffer if the old RS232 buffer is
	{						  // empty.  This will cause additional USB packets to be NAK'd
		LastRS232Out = getsUSBUSART(RS232_Out_Data,64); //until the buffer is free.
		if(LastRS232Out > 0)
		{	
			RS232_Out_Data_Rdy = 1;  // signal buffer full
			RS232cp = 0;  // Reset the current position
		}
	}

    //Check if one or more bytes are waiting in the physical UART transmit
    //queue.  If so, send it out the UART TX pin.
	if(RS232_Out_Data_Rdy && mTxRdyUSART())
	{
    	#if defined(USB_CDC_SUPPORT_HARDWARE_FLOW_CONTROL)
        	//Make sure the receiving UART device is ready to receive data before 
        	//actually sending it.
        	if(UART_CTS == USB_CDC_CTS_ACTIVE_LEVEL)
        	{
        		putcUSART(RS232_Out_Data[RS232cp]);
        		++RS232cp;
        		if (RS232cp == LastRS232Out)
        			RS232_Out_Data_Rdy = 0;
    	    }
	    #else
	        //Hardware flow control not being used.  Just send the data.
    		putcUSART(RS232_Out_Data[RS232cp]);
    		++RS232cp;
    		if (RS232cp == LastRS232Out)
    			RS232_Out_Data_Rdy = 0;	    
	    #endif
	}

    //Check if we received a character over the physical UART, and we need
    //to buffer it up for eventual transmission to the USB host.
	if(mDataRdyUSART() && (NextUSBOut < (CDC_DATA_OUT_EP_SIZE - 1)))
	{
		USB_Out_Buffer[NextUSBOut] = getcUSART();
		++NextUSBOut;
		USB_Out_Buffer[NextUSBOut] = 0;
	}
	
	#if defined(USB_CDC_SUPPORT_HARDWARE_FLOW_CONTROL)
    	//Drive RTS pin, to let UART device attached know if it is allowed to 
    	//send more data or not.  If the receive buffer is almost full, we 
    	//deassert RTS.
    	if(NextUSBOut <= (CDC_DATA_OUT_EP_SIZE - 5u))
    	{
            UART_RTS = USB_CDC_RTS_ACTIVE_LEVEL;
        }   	
        else
        {
        	UART_RTS = (USB_CDC_RTS_ACTIVE_LEVEL ^ 1);
        }    
    #endif	

    //Check if any bytes are waiting in the queue to send to the USB host.
    //If any bytes are waiting, and the endpoint is available, prepare to
    //send the USB packet to the host.
	if((USBUSARTIsTxTrfReady()) && (NextUSBOut > 0))
	{
		putUSBUSART(&USB_Out_Buffer[0], NextUSBOut);
		NextUSBOut = 0;
	}

    CDCTxService();

}//end ProcessIO
Esempio n. 26
0
void main(void)
{
	BYTE bDataUSBReady1 = 0;
	BYTE bDataRS232Ready1 = 0;
	BYTE bDataUSBReady2 = 0;
	BYTE bDataRS232Ready2 = 0;

	BYTE bCountByte1 = 0;
	BYTE bCountByte2 = 0;

	BYTE bPosIn1 = 0;
	BYTE bPosIn2 = 0;
	BYTE bPosOut1 = 0;
	BYTE bPosOut2 = 0;

    while(1)
    {
        USBDeviceTasks();
		
		if(USBDeviceState < CONFIGURED_STATE || USBSuspendControl==1)
			continue;

		/************* Seriale 1 *****************/

		// Se ci sono dati da trasmettere su USART rileggo da USB
		if(!bDataUSBReady1)
		{
			bCountByte1 = getsUSBUSART(0, InBuff1, sizeof(InBuff1));
			if(bCountByte1>0)
			{
				bDataUSBReady1 = 1;
				bPosIn1 = 0;
			}
		}
		// Ho preso dati da USB li scrivo su USART se la trasmissione è pronta
		if(bDataUSBReady1 && TXRdyUSART1())
		{
			WriteUSART1(InBuff1[bPosIn1++]);
			// Una volta che sono stati scritti tutti i byte rileggo da USB
			if(bPosIn1==bCountByte1)
				bDataUSBReady1 = 0;
		}
   	    // Se ci sono dati nella USART li leggo e li metto nel buffer
		if(DataRdyUSART1() && bPosOut1<sizeof(OutBuff1))
		{
			OutBuff1[bPosOut1] = ReadUSART1();
			bPosOut1++;
		}
		// Se la USB è pronta per trasmettere e ci sono dati li scrivo su USB
		// Se arrivano dati ed il buffer è pieno c'è il rischio di perdere i dati
		if(USBUSARTIsTxTrfReady(0) && bPosOut1>0)
		{
			putUSBUSART(0, OutBuff1, bPosOut1);
			bPosOut1 = 0;
		}
		CDCTxService(0);

		/************* Seriale 2 *****************/

		// Se ci sono dati da trasmettere su USART rileggo da USB
		if(!bDataUSBReady2)
		{
			bCountByte2 = getsUSBUSART(1, InBuff2, sizeof(InBuff2));
			if(bCountByte2>0)
			{
				bDataUSBReady2 = 1;
				bPosIn2 = 0;
			}
		}
		// Ho preso dati da USB li scrivo su USART se la trasmissione è pronta
		if(bDataUSBReady2 && TXRdyUSART2())
		{
			WriteUSART2(InBuff2[bPosIn2++]);
			// Una volta che sono stati scritti tutti i byte rileggo da USB
			if(bPosIn2==bCountByte2)
				bDataUSBReady2 = 0;
		}
   	    // Se ci sono dati nella USART li leggo e li metto nel buffer
		// Se arrivano dati ed il buffer è pieno c'è il rischio di perdere i dati
		if(DataRdyUSART2() && bPosOut2<sizeof(OutBuff2))
		{
			OutBuff2[bPosOut2] = ReadUSART2();
			bPosOut2++;
		}
		// Se la USB è pronta per trasmettere e ci sono dati li scrivo su USB
		if(USBUSARTIsTxTrfReady(1) && bPosOut2>0)
		{
			putUSBUSART(1, OutBuff2, bPosOut2);
			bPosOut2 = 0;
		}
		CDCTxService(1);
    }
}//end main
Esempio n. 27
0
void CDCTasks(void)
{
	BYTE numBytesRead;

	// Blink the LEDs according to the USB device status
	if (blinkStatusValid)
	{
		BlinkUSBStatus();
	}

	// User Application USB tasks
	if ((USBDeviceState < CONFIGURED_STATE) || (USBSuspendControl == 1))
	{
		return;
	}

#if (HILSIM_USB == 1)
	numBytesRead = getsUSBUSART(USB_In_Buffer, sizeof(USB_In_Buffer));
	if (numBytesRead != 0)
	{
		int i = 0;
		while (i < numBytesRead)
		{
			udb_gps_callback_received_byte(USB_In_Buffer[i++]);
		}
	}

	if (mUSBUSARTIsTxTrfReady())
	{
		int i = 0;
		int txchar;
		while ((i < sizeof(USB_Out_Buffer)) && ((txchar = udb_gps_callback_get_byte_to_send()) != -1))
		{
			USB_Out_Buffer[i++] = txchar;
		}
		if (i > 0)
		{
			putUSBUSART(USB_Out_Buffer, i);
		}
	}

#else
	if (mUSBUSARTIsTxTrfReady())
	{
		numBytesRead = getsUSBUSART(USB_Out_Buffer, sizeof(USB_Out_Buffer));
		if (numBytesRead != 0)
		{
			BYTE i;

			for (i = 0; i < numBytesRead; i++)
			{
				switch (USB_Out_Buffer[i])
				{
					case 0x0A:
					case 0x0D:
						USB_In_Buffer[i] = USB_Out_Buffer[i];
						break;
					default:
						USB_In_Buffer[i] = USB_Out_Buffer[i] + 1;
						break;
				}
			}
			putUSBUSART(USB_In_Buffer, numBytesRead);
		}
	}
#endif
	CDCTxService();
}
Esempio n. 28
0
/********************************************************************
 * Function:        void ProcessIO(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        This function is a place holder for other user
 *                  routines. It is a mixture of both USB and
 *                  non-USB tasks.
 *
 * Note:            None
 *******************************************************************/
void ProcessIO(void)
{   
    char backSpace[3] = {0x8,' ',0x8};
	
    // User Application USB tasks
    if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return;

	// If DTR is low no client is connected, back to default.
	if (UART_DTR == 0) { nextProcessState = P_VERSION; RS232cp = 0; }

	// Print welcome message
	if(USBUSARTIsTxTrfReady() && (UART_DTR == 1))
	{
        setLEDs(0);
	    // Print Version
	    if(nextProcessState == P_VERSION)
    	{
    		putrsUSBUSART("\r\n POV serial configuration. Version 0.9\r\n\r\n\ttype 'help' for the list of available commands.\r\n");
    		nextProcessState = P_PROMPT;
    	}
    	// Print Prompt
    	else if(nextProcessState == P_PROMPT)
    	{
    		putrsUSBUSART("\r\n>> ");
    		nextProcessState = P_INPUT;
    	}
    	else if (nextProcessState == P_INPUT)
    	{
    	    // In case the buffer is full, reset the input buffer and display error message.
    	    if (RS232cp == CDC_DATA_IN_EP_SIZE)
    	    {
                RS232cp = 0;
                nextProcessState = P_PROMPT;
    	    }
    	    // Process IO
    	    else
    	    {
    	        LastRS232Out = getsUSBUSART(&(RS232_Out_Data[RS232cp]), 1);
    	        if(LastRS232Out > 0)
    	            switch(RS232_Out_Data[RS232cp])
    				{
    				    // Enter/Return, process message
    					case 0x0A:	
    					case 0x0D:	ProcessMenu(); RS232cp = 0; nextProcessState = P_PROMPT; break;
    					// Backspace
    					case 0x7F:  
    					case 0x08:	if(RS232cp > 0) {putUSBUSART(backSpace,3); RS232cp--;} break;
    					// Replay character to user
    					default: 	putUSBUSART(&(RS232_Out_Data[RS232cp]), 1); RS232cp++;
    				}
    	    }
    	}
	}
		
    CDCTxService();
	// Limpa o buffer caso necess‡rio :)
	if(clearRS232Buffer == 1)
	{
		memset(RS232_Out_Data, '\0', sizeof(RS232_Out_Data));
		clearRS232Buffer = 0;
	}
}		//end ProcessIO
/*********************************************************************
* Function: void APP_DeviceCDCBasicDemoTasks(void);
*
* Overview: Keeps the demo running.
*
* PreCondition: The demo should have been initialized and started via
*   the APP_DeviceCDCBasicDemoInitialize() and APP_DeviceCDCBasicDemoStart() demos
*   respectively.
*
* Input: None
*
* Output: None
*
********************************************************************/
void APP_DeviceCDCBasicDemoTasks()
{
    /* If the user has pressed the button associated with this demo, then we
     * are going to send a "Button Pressed" message to the terminal.
     */
    if(BUTTON_IsPressed(BUTTON_DEVICE_CDC_BASIC_DEMO) == true)
    {
        /* Make sure that we only send the message once per button press and
         * not continuously as the button is held.
         */
        if(buttonPressed == false)
        {
            /* Make sure that the CDC driver is ready for a transmission.
             */
            if(mUSBUSARTIsTxTrfReady() == true)
            {
                putrsUSBUSART(buttonMessage);
                buttonPressed = true;
            }
        }
    }
    else
    {
        /* If the button is released, we can then allow a new message to be
         * sent the next time the button is pressed.
         */
        buttonPressed = false;
    }

    /* Check to see if there is a transmission in progress, if there isn't, then
     * we can see about performing an echo response to data received.
     */
    if( USBUSARTIsTxTrfReady() == true)
    {
      uint8_t numBytesRead;
      numBytesRead = getsUSBUSART(readBuffer, sizeof(readBuffer));

      if (numBytesRead > 0) {
        switch(readBuffer[0]) {
        case 0x10:
          {
            unsigned char size = readBuffer[1];
            debug_flag2 = !debug_flag2;
            PORTCbits.RC1 = debug_flag2;
            writeBuffer[0] = 0x90;
            writeBuffer[1] = 4;
            writeBuffer[2] = numBytesRead;
            writeBuffer[3] = readBuffer[1];
            writeBuffer[4] = readBuffer[2];
            writeBuffer[5] = readBuffer[3];
            writeBuffer[1] = 4+size;
            for (unsigned char i = 0; i<size; i++) {
              writeBuffer[i+6] = readBuffer[4 + i];
            }
            if (WaitToReadySerial())
              putUSBUSART(writeBuffer, writeBuffer[1]+2);
            WaitToReadySerial();
          }
          {
            unsigned char size = readBuffer[1];
            i2c_start(0x50, 0);
            // address in big-endian format
            i2c_send(readBuffer[3]); // address MSB
            i2c_send(readBuffer[2]); // address LSB
            for (unsigned char i = 0; i<size; i++) {
              i2c_send(readBuffer[4 + i]);
            }
            i2c_stop();
            __delay_ms(10);
          }
          break;
        case 0x11:
          {
            unsigned char size = readBuffer[1];
            unsigned char data;
            unsigned char i;
            i2c_start(0x50, 0);
            // address in big-endian format
            i2c_send(readBuffer[3]); // address MSB
            i2c_send(readBuffer[2]); // address LSB
            i2c_start(0x50, 1);
            for (i=0; i<size-1; i++) {
              writeBuffer[i+2] = i2c_receive(ACK);
            }
            writeBuffer[i+2] = i2c_receive(NOACK);
            i2c_stop();
            __delay_ms(10);
            writeBuffer[0] = 0x12;
            writeBuffer[1] = size;
            putUSBUSART(writeBuffer, writeBuffer[1]+2);
          }
          break;
        }
      }

      //if (debug_flag) {
      //  debug_flag = 0;
      //  writeBuffer[0] = 9;
      //  writeBuffer[1] = 1;
      //  writeBuffer[2] = debug_data;
      //  putUSBUSART(writeBuffer, writeBuffer[1]+2);
      //}
    }
    CDCTxService();
}
Esempio n. 30
0
/*********************************************************************
* Function: void APP_DeviceCDCBasicDemoTasks(void);
*
* Overview: Keeps the demo running.
*
* PreCondition: The demo should have been initialized and started via
*   the APP_DeviceCDCBasicDemoInitialize() and APP_DeviceCDCBasicDemoStart() demos
*   respectively.
*
* Input: None
*
* Output: None
*
********************************************************************/
void APP_DeviceCDCBasicDemoTasks()
{
    static uint8_t msg_buf_idx = 0;
    static bool msg_done = false;
    
    static char msg_type;
    
    
    /* Check to see if there is a transmission in progress, if there isn't, then
     * we can see about performing an echo response to data received.
     */
    if( USBUSARTIsTxTrfReady() == true)
    {
        uint8_t i;
        uint8_t numBytesRead;

        numBytesRead = getsUSBUSART(readBuffer, sizeof(readBuffer));

        /* For every byte that was read... */
        for(i=0; i<numBytesRead; i++)
        {
            if(msg_buf_idx == MSG_BUF_SIZE)
            {
                putrsUSBUSART(buttonMessage);
                msg_buf_idx = 0;
                msg_buffer[0] = 0;
                break;
            }
            else
            {
                if(readBuffer[i] == '\r' || readBuffer[i] == '\n')
                {
                    msg_buffer[msg_buf_idx] = 0;
                    msg_done = true;
                    break;
                }
                
                
                if(readBuffer[i] >= '0' && readBuffer[i] <= '9')
                {
                    msg_buffer[msg_buf_idx] = readBuffer[i];
                    msg_buf_idx++;
                }
                else
                {
                    msg_type = readBuffer[i];
                    msg_buf_idx = 0;
                    msg_buffer[msg_buf_idx] = 0;
                    
                }
                
                msg_done = false;
                

            }
        }

        if(numBytesRead > 0 && msg_done == true && msg_buf_idx > 0)
        {
            /* After processing all of the received data, we need to send out
             * the "echo" data now.
             */
            
            int number;
            
            number = atoi(msg_buffer);
            
            //sprintf(writeBuffer, "Type: %c, number: %d\r\n", msg_type, number);
            
            if(msg_type == 'c' && number > 0 && number < 128)
            {
                PWM1DCH = (uint8_t)number;
            }
            
            if(msg_type == 'm' && number > 0 && number < 128)
            {
                PWM2DCH = (uint8_t)number;
            }
            
            //putrsUSBUSART(writeBuffer);
            msg_buf_idx = 0;
            
        }
    }

    CDCTxService();
}