Exemplo n.º 1
0
void SendUSBMessage(char *message, unsigned int len)
{
    BYTE tosend;

    // give up if the other end isn't listening!
    if(!USBUSARTIsTxTrfReady())
        return;

    while (len)
    {
        if(len <= (int) 255)
            tosend= (BYTE) len;
        else
            tosend= (BYTE) 255;

        putUSBUSART(message, tosend);
        message += tosend;
        len -= tosend;

        // don't return until message is sent otherwise we get problems
        // with buffer being overwitten - e.g. LIST
        while (!USBUSARTIsTxTrfReady())
            CDCTxService();
    }
}
Exemplo n.º 2
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
/********************************************************************
 * Function:        void ProcessUSBData(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 ProcessUSBData(void)
{
    // User Application USB tasks
    if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return;

    if(USBUSARTIsTxTrfReady())
    {
        if(currentMode != PR_NOREQUEST)
        {
            continueWithCurrentMode();
        }
        else
        {
            if(dataAvailable==0)
            {
                loadNewData();
            }
            if(dataAvailable > 0)
            {
                UINT8 oldCurrentByte = currentByte;
            	currentByte = (currentByte+1)%BUFFER_SIZE;
                dataAvailable--;

                handleProcessRequest(USB_In_Buffer[oldCurrentByte]);
            }
        }
        
    }

    CDCTxService();
}		//end ProcessIO
Exemplo 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;
}
Exemplo n.º 5
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();
}
Exemplo n.º 6
0
/*===================================================
|					Funtions						|
===================================================*/
void USBGetInput(void)
{
	if((USBUSARTIsTxTrfReady()) && (NextOut > 0))
	{
		putUSBUSART(&Out_Buffer[0], NextOut);
		NextOut = 0;
	}
}	
Exemplo n.º 7
0
static uint8_t USB_CDC_get(void) {
    uint8_t numBytesRead;
    if (USBUSARTIsTxTrfReady() == true) {
        numBytesRead = getsUSBUSART(readBuffer, sizeof (readBuffer));
    }
    CDCTxService();
    return numBytesRead;
}
Exemplo n.º 8
0
void usb_char_send(char c) {
    if (!is_usb_available()) {
        //USBCBSendResume();
        return;
    }
    while (!USBUSARTIsTxTrfReady()) CDCTxService();
    putUSBUSART(&c, 1);
    CDCTxService();
}
Exemplo n.º 9
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;
}
Exemplo n.º 10
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();
}
Exemplo n.º 11
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();
}
Exemplo n.º 12
0
//IR signals are first captured in the interrupt loop below
//when the capture is complete, the bits are decoded into bytes and sent to USB from this function
void ProcessIR(void){   
	static unsigned char i;

	if((decoderState==SEND) && (USBUSARTIsTxTrfReady())){
	
		//process IR data (decode RC5) in irToy.s[]
		//byte# | description
		//0 second start bit, use as bit 6 in command byte for RC5x protocol support
		//1 toggle bit, discard
		//2-6 5bit address
		//7-12 6bit command

		//final USB packet is:
		//byte 1 bits 7-5 (don't care)
		//byte 1 bits 4-0 (5 address bits)
		//byte 2 bit 7 (don't care)
		//byte 2 bit 6 (RC5x/start bit 2, not inversed)
		//byte 2 bits 5-0 (RC5 6 bit command)
		//byte 3-6 (unused)

		//first byte of USB data is the RC5 address (lower 5 bits of first byte)
		//loop through irToy.s[] and shift the 5bit address into the USB output buffer
		//5 address bits, 5-0, MSB first
		irToy.usbOut[0]=0; 					//clear USB buffer byte to 0
		for(i=2;i<7;i++){ 					//loop through and assemble 5 address bits into a byte, bit 4 to bit 0, MSB first
			irToy.usbOut[0]<<=1; 			//shift last bit up
			irToy.usbOut[0]|=irToy.s[i]; 	//set bit 0 to value of irToy.s[i]					
		}

		//second byte of USB data is the RC5 command (lower 6 or 7 bits of second byte)
		//for RC5x, the second start bit is used as the MSB of the command (bit 6)
		irToy.usbOut[1]=irToy.s[0]; 		//start with the value of the RC5x bit (bit 6), 
		//irToy.usbOut[1]=(~irToy.s[0]);		//technically this should be inversed, but that would ruin compatibility for exisitng remote profiles
		//loop through irToy.s[] and shift the 'normal' 6 command bits, bit 5 to bit 0, into the USB output buffer
		//6 command bits, 5-0, MSB first
		for(i=7;i<13;i++){ 					//loop through and assemble 6 command bits into a byte, bit 5 to bit 0, MSB first
			irToy.usbOut[1]<<=1; 			//shift last bit up
			irToy.usbOut[1]|=irToy.s[i]; 	//set bit 0 to value of irToy.s[i]	
		}

		irToy.usbOut[2]=0x00;//four extra bytes for 6 byte IRMAN format
		irToy.usbOut[3]=0x00;
		irToy.usbOut[4]=0x00;
		irToy.usbOut[5]=0x00;	

		putUnsignedCharArrayUsbUsart(irToy.usbOut,6);

		decoderState=IDLE;//wait for more RC commands....
		IRRX_IE=1;//interrupts back on	

	}

}	
Exemplo n.º 13
0
void BootProtocolTasks() {
  if (USBUSARTIsTxTrfReady()) {
    const BYTE* data;
    if (bytes_out) {
      ByteQueuePull(&tx_queue, bytes_out);
      bytes_out = 0;
    }
    ByteQueuePeek(&tx_queue, &data, &bytes_out);
    if (bytes_out > 0) {
      if (bytes_out > max_packet) bytes_out = max_packet;
      putUSBUSART((char *) data, bytes_out);
    }
  }
}
Exemplo n.º 14
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();
}
Exemplo n.º 15
0
unsigned char SUMPlogicService(void){
	static unsigned char i, USBWriteCount;

	switch(LAstate){//dump data
		//case IDLE:
		//case ARMED:
		//case LA_START_DUMP: 
		case LA_DUMP:
		    if(USBUSARTIsTxTrfReady()){
				USBWriteCount=0;
				for(i=0; i<8; i++){

					loga.btrack<<=1; //shift bit at begin to reset from last loop
					if((loga.btrack==0) && (loga.ptr>0) ){//no bits left
						loga.btrack=0b00000001;//start at bit 0
						loga.ptr--;
					}
		
					if( (irToy.s[loga.ptr] & loga.btrack)!=0)
						irToy.usbOut[USBWriteCount]=0; 
					else
						irToy.usbOut[USBWriteCount]=1;

					USBWriteCount++;

					loga.sample--;
					if(loga.sample==0){//send 64/128/512/1024 samples exactly!
						LAstate=LA_RESET;
						break;
					}

				}
				putUnsignedCharArrayUsbUsart(irToy.usbOut,USBWriteCount);

			}
			break;
		case LA_RESET:
			LAstate = LA_IDLE;
			return 0xff;	
			break;
	}
	return 0;
}
Exemplo n.º 16
0
void DebugService(void)
{
    if(USBUSARTIsTxTrfReady() && current_buffer_len) {
        putUSBUSART((uint8_t *)current_buffer, current_buffer_len);
        
        if (current_buffer == buffer_1) {
            current_buffer = buffer_2;
        }
        else {
            current_buffer = buffer_1;
        }
        current_buffer_len = 0;
        
        if (dropped_lines) { // The USB layer couln't send the data fast enough. If this is a problem, calling CDCService() more often could help.
            current_buffer[0] = '\n'; // Send an empty line to show that the overflow happened.
            current_buffer_len++;
            dropped_lines = 0;
        }
    }
}
Exemplo n.º 17
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();
}
Exemplo n.º 18
0
Arquivo: main.c Projeto: z9u2k/remote
/**
 * blink LED, send data on queue
 */
void ProcessIO(void) {

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

    if (USBUSARTIsTxTrfReady()) {
        int len = 0;
        char temp[QUEUE_SIZE];
        while (QueueHas()) {
            temp[len++] = QueueGet();
        }

		if (len > 0) {
			putUSBUSART(temp, len);
		}
	}

    CDCTxService();
}
Exemplo n.º 19
0
static int CDCCanSend(int h) {
  assert(h == 0);
  if (channel_state != CHANNEL_OPEN) return 0;
  return USBUSARTIsTxTrfReady();
}
Exemplo n.º 20
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
    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(mUSBUSARTIsTxTrfReady())
//    {
//		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);
//		}
//	}

    //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;
    }

    //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
Exemplo n.º 21
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;
        }
    }
Exemplo n.º 22
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()
{
    uint8_t numBytesWrite = 0;
    uint8_t packet[MAX_PACKET_SIZE];
    uint8_t packetSize;
    packet_data_u data;

    /* Make sure that the CDC driver is ready for a transmission.
     */
    if (mUSBUSARTIsTxTrfReady() == true) {
        uint16_t value;
        uint32_t percent;
        button_state_s cur_state[3];

        memset(cur_state, 0x00, 3 * sizeof(button_state_s));

        bool button1IsPressed = BUTTON_IsPressed(BUTTON_S1);
        bool button2IsPressed = BUTTON_IsPressed(BUTTON_S2);
        bool button3IsPressed = BUTTON_IsPressed(BUTTON_S3);
    
        value = ADC_Read10bit(ADC_CHANNEL_1);
        percent = ((uint32_t)100 * value) / 0x03FF;
        cur_state[0].pos = 0;
        cur_state[0].state = button1IsPressed ? BUTTON_PRESSED : BUTTON_RELEASED;
        cur_state[0].state |= ((percent >= 95) ? BUTTON_UNMOUNTED : BUTTON_MOUNTED);
        cur_state[0].uid = percent;

        value = ADC_Read10bit(ADC_CHANNEL_2);
        percent = ((uint32_t)100 * value) / 0x03FF;
        cur_state[1].pos = 1;
        cur_state[1].state = button2IsPressed ? BUTTON_PRESSED : BUTTON_RELEASED;
        cur_state[1].state |= ((percent >= 95) ? BUTTON_UNMOUNTED : BUTTON_MOUNTED);
        cur_state[1].uid = percent;

        value = ADC_Read10bit(ADC_CHANNEL_3);
        percent = ((uint32_t)100 * value) / 0x03FF;
        cur_state[2].pos = 2;
        cur_state[2].state = button3IsPressed ? BUTTON_PRESSED : BUTTON_RELEASED;
        cur_state[2].state |= ((percent >= 95) ? BUTTON_UNMOUNTED : BUTTON_MOUNTED);
        cur_state[2].uid = percent;

        if ((buttons_state[0].state != cur_state[0].state) || (buttons_state[1].state != cur_state[1].state) || (buttons_state[2].state != cur_state[2].state)) {
            memset(&data, 0x00, sizeof(packet_data_u));
            memcpy(data.buttons_state, cur_state, 3 * sizeof(button_state_s));
            assemblyPacket(GET_BUTTONS_STATE, &data, packet, &packetSize);
            memcpy(writeBuffer, packet, packetSize);
            numBytesWrite = packetSize;

            if (numBytesWrite > 0) {
                putUSBUSART(writeBuffer, numBytesWrite);
            }
            
            memcpy(buttons_state, cur_state, 3 * sizeof(button_state_s));
        }
    }

    /* 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)
    {
        uint16_t i;
        uint16_t validDataLen;
        uint16_t numBytesRead;
        char deviceID[] = "Keys 011";
        char *e;
        packet_type_e type;
        uint8_t payload[MAX_DATA_SIZE];
        uint8_t payloadSize;

        // Collect incoming data in read buffer. Bear in mind, buffer have to had ability receive whole CDC packet.
        if ((readPos + CDC_DATA_OUT_EP_SIZE) >= sizeof(readBuffer)) {
            e = memchr(readBuffer, PREAMBLE, sizeof(readBuffer));
            // Wipe out trash before valid data
            if (e == 0) {
                memset(readBuffer, 0x00, sizeof(readBuffer));
                readPos = 0;
            } else {
                validDataLen = (uint16_t)(&readBuffer[sizeof(readBuffer)] - e);
                memmove(readBuffer, e, validDataLen);
                memset(&readBuffer[validDataLen], 0x00, sizeof(readBuffer) - validDataLen);
                readPos = 0;
            }
        }
        numBytesRead = getsUSBUSART(&readBuffer[readPos], CDC_DATA_OUT_EP_SIZE);
        if (numBytesRead > 0) {
            // Parse all collected incoming data
            do {
                e = memchr(readBuffer, PREAMBLE, sizeof(readBuffer));
                if (e == 0) {
                    break;
                }
                i = (uint16_t)(e - readBuffer);
                parsePacket(&readBuffer[i], sizeof(readBuffer) - i, &type, payload, &payloadSize);
                numBytesWrite = 0;
                if (type == GET_DEVICE_ID) {
                    memset(&data, 0x00, sizeof(packet_data_u));
                    memcpy(data.device_id, deviceID, 8);
                    assemblyPacket(GET_DEVICE_ID, &data, packet, &packetSize);
                    memcpy(writeBuffer, packet, packetSize);
                    numBytesWrite = packetSize;
                } else if (type == GET_STATUS) {
                    memset(&data, 0x00, sizeof(packet_data_u));
                    data.device_status.errors = ERROR_NONE;
                    data.device_status.rtc = 0;
                    assemblyPacket(GET_STATUS, &data, packet, &packetSize);
                    memcpy(writeBuffer, packet, packetSize);
                    numBytesWrite = packetSize;                    
                } else if (type == SET_LEDS_STATE) {
                    led_state_s *led = (led_state_s *)payload;
                    if (led->state == LED_TURN_ON) {
                        if (led->pos == 0)
                            LED_On(LED_D2);
                        if (led->pos == 1)
                            LED_On(LED_D3);
                        if (led->pos == 2)
                            LED_On(LED_D4);
                    } else {
                        if (led->pos == 0)
                            LED_Off(LED_D2);
                        if (led->pos == 1)
                            LED_Off(LED_D3);
                        if (led->pos == 2)
                            LED_Off(LED_D4);
                    }
                } else if (type == RESET_DEVICE) {
                    LED_Off(LED_D2);
                    LED_Off(LED_D3);
                    LED_Off(LED_D4);
                    memset(readBuffer, 0x00, sizeof(readBuffer));
                    readPos = 0;
                } else {
                    memcpy(writeBuffer, &readBuffer[i], 20);
                    numBytesWrite = 20;
                }
                // Clear packet's start marker - PREAMBLE
                memset(&readBuffer[i], 0x00, 1);
                // Send answer
                if (numBytesWrite > 0) {
                    putUSBUSART(writeBuffer, numBytesWrite);
                }
            } while (1);
        }
    }

    CDCTxService();
}
Exemplo n.º 23
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
Exemplo n.º 24
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();
}
Exemplo n.º 25
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
/*********************************************************************
* 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();
}
Exemplo n.º 27
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()
{
    uint8_t numBytesRead;
    uint8_t temp_level;
    static uint8_t numberChADC = 0;
    
    if (ready_scan){
        temp_level = adc_levels[numberChADC];
        numBytesRead = sprintf(writeBuffer, "ADC_NN=%u, LEVEL=%u \n\r", numberChADC, temp_level);
         if( USBUSARTIsTxTrfReady() == true)
            {
             putUSBUSART(writeBuffer,numBytesRead);
             numberChADC ++;
             if (numberChADC >= N_ADC) numberChADC = 0;
            }
      
           
    }    
    CDCTxService();
    
          //  USBTxOnePacket(USB_MAX_EP_NUMBER,(uint8_t*)&midiData,2);
          
   //     numBytesRead = sprintf(writeBuffer, "ADC_NN=%u, LEVEL=%u", midiData.IDX, midiData.ADC);
   //     putUSBUSART(writeBuffer,numBytesRead);
    
    
    
    
    /* 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 i;
   //     uint8_t numBytesRead;

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

        /* For every byte that was read... */
   //     for(i=0; i<numBytesRead; i++)
   //    {
   //         switch(readBuffer[i])
   //         {
                /* If we receive new line or line feed commands, just echo
                 * them direct.
                 */
   //             case 0x0A:
   //             case 0x0D:
   //                 writeBuffer[i] = readBuffer[i];
   //                 break;

                /* If we receive something else, then echo it plus one
                 * so that if we receive 'a', we echo 'b' so that the
                 * user knows that it isn't the echo enabled on their
                 * terminal program.
                 */
   //             default:
   //                 writeBuffer[i] = readBuffer[i] + 1;
   //                 break;
   //         }
   //     }

   //     if(numBytesRead > 0)
   //     {
            /* After processing all of the received data, we need to send out
             * the "echo" data now.
             */
          //  putUSBUSART(writeBuffer,numBytesRead);
    //    }
   // }

  //  CDCTxService();
}
Exemplo n.º 28
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();
}
Exemplo n.º 29
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