예제 #1
0
/** Main program entry point. This routine contains the overall program flow, including initial
 *  setup of all components and the main program loop.
 */
int main(void)
{
	SetupHardware();

	RingBuffer_InitBuffer(&USBtoUSART_Buffer, USBtoUSART_Buffer_Data, sizeof(USBtoUSART_Buffer_Data));
	RingBuffer_InitBuffer(&USARTtoUSB_Buffer, USARTtoUSB_Buffer_Data, sizeof(USARTtoUSB_Buffer_Data));

	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
	GlobalInterruptEnable();

	for (;;)
	{
		/* Only try to read in bytes from the CDC interface if the transmit buffer is not full */
		if (!(RingBuffer_IsFull(&USBtoUSART_Buffer)))
		{
			int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);

			/* Read bytes from the USB OUT endpoint into the USART transmit buffer */
			if (!(ReceivedByte < 0))
			  RingBuffer_Insert(&USBtoUSART_Buffer, ReceivedByte);
		}

		/* Check if the UART receive buffer flush timer has expired or the buffer is nearly full */
		uint16_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);
		if (BufferCount)
		{
			Endpoint_SelectEndpoint(VirtualSerial_CDC_Interface.Config.DataINEndpoint.Address);

			/* Check if a packet is already enqueued to the host - if so, we shouldn't try to send more data
			 * until it completes as there is a chance nothing is listening and a lengthy timeout could occur */
			if (Endpoint_IsINReady())
			{
				/* Never send more than one bank size less one byte to the host at a time, so that we don't block
				 * while a Zero Length Packet (ZLP) to terminate the transfer is sent if the host isn't listening */
				uint8_t BytesToSend = MIN(BufferCount, (CDC_TXRX_EPSIZE - 1));

				/* Read bytes from the USART receive buffer into the USB IN endpoint */
				while (BytesToSend--)
				{
					/* Try to send the next byte of data to the host, abort if there is an error without dequeuing */
					if (CDC_Device_SendByte(&VirtualSerial_CDC_Interface,
											RingBuffer_Peek(&USARTtoUSB_Buffer)) != ENDPOINT_READYWAIT_NoError)
					{
						break;
					}

					/* Dequeue the already sent byte from the buffer now we have confirmed that no transmission error occurred */
					RingBuffer_Remove(&USARTtoUSB_Buffer);
				}
			}
		}

		/* Load the next byte from the USART transmit buffer into the USART */
		if (!(RingBuffer_IsEmpty(&USBtoUSART_Buffer)))
		  Serial_SendByte(RingBuffer_Remove(&USBtoUSART_Buffer));

		CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
		USB_USBTask();
	}
}
예제 #2
0
/** Main program entry point. This routine contains the overall program flow, including initial
 *  setup of all components and the main program loop.
 */
int main(void)
{
	SetupHardware();

	RingBuffer_InitBuffer(&USBtoUSART_Buffer);
	RingBuffer_InitBuffer(&USARTtoUSB_Buffer);

	sei();

	for (;;)
	{
		/* Only try to read in bytes from the CDC interface if the transmit buffer is not full */
		if (!(RingBuffer_IsFull(&USBtoUSART_Buffer)))
		{
			int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);

			/* Read bytes from the USB OUT endpoint into the USART transmit buffer */
			if (!(ReceivedByte < 0))
			  RingBuffer_Insert(&USBtoUSART_Buffer, ReceivedByte);
		}

		/* Check if the UART receive buffer flush timer has expired or the buffer is nearly full */
		RingBuff_Count_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);
		if ((TIFR0 & (1 << TOV0)) || (BufferCount > BUFFER_NEARLY_FULL))
		{
			TIFR0 |= (1 << TOV0);

			if (USARTtoUSB_Buffer.Count) {
				LEDs_TurnOnLEDs(LEDMASK_TX);
				PulseMSRemaining.TxLEDPulse = TX_RX_LED_PULSE_MS;
			}

			/* Read bytes from the USART receive buffer into the USB IN endpoint */
			while (BufferCount--)
			  CDC_Device_SendByte(&VirtualSerial_CDC_Interface, RingBuffer_Remove(&USARTtoUSB_Buffer));

			/* Turn off TX LED(s) once the TX pulse period has elapsed */
			if (PulseMSRemaining.TxLEDPulse && !(--PulseMSRemaining.TxLEDPulse))
			  LEDs_TurnOffLEDs(LEDMASK_TX);

			/* Turn off RX LED(s) once the RX pulse period has elapsed */
			if (PulseMSRemaining.RxLEDPulse && !(--PulseMSRemaining.RxLEDPulse))
			  LEDs_TurnOffLEDs(LEDMASK_RX);
		}

		/* Load the next byte from the USART transmit buffer into the USART */
		if (!(RingBuffer_IsEmpty(&USBtoUSART_Buffer))) {
		  Serial_TxByte(RingBuffer_Remove(&USBtoUSART_Buffer));

		  	LEDs_TurnOnLEDs(LEDMASK_RX);
			PulseMSRemaining.RxLEDPulse = TX_RX_LED_PULSE_MS;
		}

		CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
		USB_USBTask();
	}
}
예제 #3
0
int main(void)
{
	SetupHardware();

	RingBuffer_InitBuffer(&USBtoUSART_Buffer, USBtoUSART_Buffer_Data, sizeof(USBtoUSART_Buffer_Data));
	RingBuffer_InitBuffer(&USARTtoUSB_Buffer, USARTtoUSB_Buffer_Data, sizeof(USARTtoUSB_Buffer_Data));

	LEDs_SetAllLEDs(0);

	sei();

	for (;;)
	{
		if ((PINF & 0x01) == 0x01)
			LEDs_SetAllLEDs(2);
		else
			LEDs_SetAllLEDs(0);
		/* Only try to read in bytes from the CDC interface if the (outbound) transmit buffer is not full */
		if (!(RingBuffer_IsFull(&USBtoUSART_Buffer)))
		{
			int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);

			/* Read bytes from the USB OUT endpoint into the USART transmit buffer */
			if (!(ReceivedByte < 0))
			  RingBuffer_Insert(&USBtoUSART_Buffer, ReceivedByte);
		}

		/* Check if the UART receive buffer flush timer has expired or the buffer is nearly full */
		uint16_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);
		if ((TIFR0 & (1 << TOV0)) || (BufferCount > (uint8_t)(sizeof(USARTtoUSB_Buffer_Data) * .75)))
		{
			/* Clear flush timer expiry flag */
			TIFR0 |= (1 << TOV0);

			/* Read bytes from the USART receive buffer into the USB IN endpoint */
			while (BufferCount--)
			{
				/* Try to send the next byte of data to the host, abort if there is an error without dequeuing */
				if (CDC_Device_SendByte(&VirtualSerial_CDC_Interface,
				                        RingBuffer_Peek(&USARTtoUSB_Buffer)) != ENDPOINT_READYWAIT_NoError)
				{
					break;
				}

				/* Dequeue the already sent byte from the buffer now we have confirmed that no transmission error occurred */
				RingBuffer_Remove(&USARTtoUSB_Buffer);
			}
		}

		/* Load the next byte from the USART transmit buffer into the USART */
		if (!(RingBuffer_IsEmpty(&USBtoUSART_Buffer)))
		  Serial_SendByte(RingBuffer_Remove(&USBtoUSART_Buffer));

		CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
		USB_USBTask();
	}
}
void HandleSerial(void)
{
	// Only try to read in bytes from the CDC interface if the transmit buffer is not full 
	if (!(RingBuffer_IsFull(&FromHost_Buffer)))
	{
		int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);
		// Read bytes from the USB OUT endpoint into the USART transmit buffer 
		if (!(ReceivedByte < 0)){
		  	RingBuffer_Insert(&FromHost_Buffer, ReceivedByte);
			CDC_Device_SendByte(&VirtualSerial_CDC_Interface, ReceivedByte);
		}
	}

	while (RingBuffer_GetCount(&FromHost_Buffer) > 0)
	{
		int16_t c = RingBuffer_Remove(&FromHost_Buffer);

		if(c == '\n' || c == '\r'){
			if(cmd_cnt > 0 && (cmd[cmd_cnt-1] == '\n' || cmd[cmd_cnt-1] == '\r'))
				cmd_cnt--;
			cmd[cmd_cnt] = 0;			
			execute_command();
			cmd_cnt = 0;			
		}
		else{
			cmd[cmd_cnt++] = c;			
		}
	}
}
예제 #5
0
파일: Gamepad.c 프로젝트: eskerda/arduines
/** ISR to manage the reception of data from the serial port, placing received bytes into a circular buffer
 *  for later transmission to the host.
 */
ISR(USART1_RX_vect, ISR_BLOCK)
{
    uint8_t ReceivedByte = UDR1;

    if (USB_DeviceState == DEVICE_STATE_Configured && !RingBuffer_IsFull(&USARTtoUSB_Buffer))
        RingBuffer_Insert(&USARTtoUSB_Buffer, ReceivedByte);

    RingBuff_Count_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);
    if (BufferCount >= (sizeof(joyReport) + 1)) {
          joyReport.X = (int8_t) RingBuffer_Remove(&USARTtoUSB_Buffer);
          joyReport.Y = (int8_t) RingBuffer_Remove(&USARTtoUSB_Buffer);
          joyReport.Button = (uint8_t) RingBuffer_Remove(&USARTtoUSB_Buffer);
          /* Remove spacer at the end of the struct*/
          RingBuffer_Remove(&USARTtoUSB_Buffer);
    }
}
예제 #6
0
파일: USBtoSerial.c 프로젝트: ldarlok/LCS
void sendUSBtoUSART ()
{
	if (Serial_IsSendReady() && !(RingBuffer_IsEmpty(&USBtoUSART_Buffer)))
	{
		Serial_SendByte(RingBuffer_Remove(&USBtoUSART_Buffer));
	}
}
/** HID class driver callback function for the creation of HID reports to the host.
 *
 *  \param[in]     HIDInterfaceInfo  Pointer to the HID class interface configuration structure being referenced
 *  \param[in,out] ReportID    Report ID requested by the host if non-zero, otherwise callback should set to the generated report ID
 *  \param[in]     ReportType  Type of the report to create, either REPORT_ITEM_TYPE_In or REPORT_ITEM_TYPE_Feature
 *  \param[out]    ReportData  Pointer to a buffer where the created report should be stored
 *  \param[out]    ReportSize  Number of bytes written in the report (or zero if no report is to be sent
 *
 *  \return Boolean true to force the sending of the report, false to let the library determine if it needs to be sent
 */
bool CALLBACK_HID_Device_CreateHIDReport(
    USB_ClassInfo_HID_Device_t* const HIDInterfaceInfo,
    uint8_t* const ReportID,
    const uint8_t ReportType,
    void* ReportData,
    uint16_t* const ReportSize)
{
    USB_JoystickReport_Data_t *reportp = (USB_JoystickReport_Data_t*)ReportData;

    RingBuff_Count_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);

    /* If there's a new report from the Arduino, copy it in and send that.
     * If not then the last report is sent again.
     */
    if (BufferCount >= sizeof(joyReport)) {
	uint8_t ind;
	for (ind=0; ind<sizeof(joyReport); ind++) {
	    ((uint8_t *)&joyReport)[ind] = RingBuffer_Remove(&USARTtoUSB_Buffer);
	}

	LEDs_TurnOnLEDs(LEDS_LED1);
	led1_ticks = LED_ON_TICKS;
    }

    *reportp = joyReport;

    *ReportSize = sizeof(joyReport);
    return false;
}
예제 #8
0
void cdc_send_USB_data( USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo ){
    
	// process outgoing USB data
	Endpoint_SelectEndpoint(CDCInterfaceInfo->Config.DataINEndpoint.Address); // select IN endpoint to restore its registers
	if ( UEINTX & (1<<TXINI) ){ // if we can write on the outgoing data bank
		uint8_t BufferCount = RingBuffer_GetCount(&ToUSB_Buffer);
		
		if (BufferCount) {
			uint8_t bank_size = CDCInterfaceInfo->Config.DataINEndpoint.Size;
	
			// if there are more bytes in the buffer than what can be put in the data bank OR there are a few bytes and they have been waiting for too long
			if ( BufferCount >= bank_size || (TIFR0 & (1 << TOV0)) ){
				// Clear flush timer expiry flag
			    TIFR0 |= (1 << TOV0);
				
				// load the IN data bank until full or until we loaded all the bytes we know we have
				uint8_t nb_to_write = min(BufferCount, bank_size );					
				while (nb_to_write--){
                	uint8_t Data = RingBuffer_Remove(&ToUSB_Buffer);
					Endpoint_Write_8(Data);
				}
				
				// if the bank is full (== we can't write to it anymore), we might need an empty packet after this one
				needEmptyPacket = ! Endpoint_IsReadWriteAllowed();
				
				Endpoint_ClearIN(); // allow the hardware to send the content of the bank
			}
		} else if (needEmptyPacket) {
			// send an empty packet to end the transfer
			needEmptyPacket = false;
			Endpoint_ClearIN(); // allow the hardware to send the content of the bank
		}
		
	}
}
예제 #9
0
/** Main program entry point. This routine contains the overall program flow, including initial
 *  setup of all components and the main program loop.
 */
int main(void)
{
	SetupHardware();

	RingBuffer_InitBuffer(&USBtoUSART_Buffer, USBtoUSART_Buffer_Data, sizeof(USBtoUSART_Buffer_Data));
    RingBuffer_InitBuffer(&ToUSB_Buffer, ToUSB_Buffer_Data, sizeof(ToUSB_Buffer_Data));

	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
	sei();

	for (;;)
	{
		/* Only try to read in bytes from the CDC interface if the transmit buffer is not full */
		if (!(RingBuffer_IsFull(&USBtoUSART_Buffer)))
		{
			int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);

			/* Read bytes from the USB OUT endpoint into the USART transmit buffer */
			if (!(ReceivedByte < 0))
			  RingBuffer_Insert(&USBtoUSART_Buffer, ReceivedByte);
		}
		
		/* Load the next byte from the USART transmit buffer into the USART */
		if (!(RingBuffer_IsEmpty(&USBtoUSART_Buffer)))
		  Serial_SendByte(RingBuffer_Remove(&USBtoUSART_Buffer));

		cdc_send_USB_data(&VirtualSerial_CDC_Interface);
		USB_USBTask();
	}
}
예제 #10
0
파일: wi07.c 프로젝트: kehribar/xmegaE5
/*---------------------------------------------------------------------------*/
uint16_t getMessageLength()
{
  uint8_t in = 0;
  uint8_t run = 1;  
  uint8_t lenbuf[16];

  while(run)
  {
    while(RingBuffer_GetCount(&Buffer) == 0);
    
    lenbuf[in] = RingBuffer_Remove(&Buffer);

    if(lenbuf[in] == ':')
    {
      run = 0;
      lenbuf[in] = '\0';
    }
    else
    {
      in++;
    }
  }
  
  return StrTo16Uint(lenbuf);
}
예제 #11
0
/** Main program entry point. This routine contains the overall program flow, including initial
 *  setup of all components and the main program loop.
 */
int main(void)
{
	SetupHardware();

	RingBuffer_InitBuffer(&FromHost_Buffer, FromHost_Buffer_Data, sizeof(FromHost_Buffer_Data));

	GlobalInterruptEnable();

	for (;;)
	{
		/* Only try to read in bytes from the CDC interface if the transmit buffer is not full */
		if (!(RingBuffer_IsFull(&FromHost_Buffer)))
		{
			int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);

			/* Read bytes from the USB OUT endpoint into the USART transmit buffer */
			if (!(ReceivedByte < 0))
			  RingBuffer_Insert(&FromHost_Buffer, ReceivedByte);
		}

		while (RingBuffer_GetCount(&FromHost_Buffer) > 0)
		{
			static uint8_t EscapePending = 0;
			int16_t HD44780Byte = RingBuffer_Remove(&FromHost_Buffer);

			if (HD44780Byte == COMMAND_ESCAPE)
			{
				if (EscapePending)
				{
					HD44780_WriteData(HD44780Byte);
					EscapePending = 0;
				}
				else
				{
					/* Next received character is the command byte */
					EscapePending = 1;
				}
			}
			else
			{
				if (EscapePending)
				{
					HD44780_WriteCommand(HD44780Byte);
					EscapePending = 0;
				}
				else
				{
					HD44780_WriteData(HD44780Byte);
				}
			}
		}

		CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
		USB_USBTask();
	}
}
예제 #12
0
void RFM12B_Transmit( void )
{
    if ( RingBuffer_GetCount( &Transmit_Buffer ))
    {
        RFM12B_SPI_Transfer( RFM12B_TXREG_WRITE + 
            RingBuffer_Remove( &Transmit_Buffer ));
    }
    else
    {
        RFM12B_SPI_Transfer( RFM12B_CMD_RX_ON );
        RFM12B_Transmit_Active = false;
        PORTD |= 0x20;
    } 
}
예제 #13
0
// Read the dial commands and send them to the modem. Wait for the expected response then move on to the next command.
// Returns true if the last dial command has been processed.
static bool LinkManagement_DialConnection(const char** DialCommands)
{
	static char* ResponsePtr = NULL;
	char* CommandPtr = NULL;
	static uint8_t CharsMatched = 0;
	char c;

	if (USB_HostState != HOST_STATE_Configured)	
		return false;

	while (!RingBuffer_IsEmpty(&Modem_ReceiveBuffer))						    // Read back the response
	{	
		c = RingBuffer_Remove(&Modem_ReceiveBuffer);
		Debug_PrintChar(c);
		
		if (c == *(ResponsePtr + CharsMatched))									// Match the response character by character with the expected response						
			CharsMatched++;
		else
			CharsMatched = 0;
			
		if (CharsMatched != 0 && CharsMatched == strlen(ResponsePtr))			// Look for the expected response
		{
			DialSteps += 2;														// Move on to the next dial command
			CharsMatched = 0;
		}
	}	
		
	if (SystemTicks > 100)														// Space each command by 1 second
	{
		CommandPtr = (char*)DialCommands[DialSteps];
		ResponsePtr = (char*)DialCommands[DialSteps + 1];

		if (CommandPtr == NULL || ResponsePtr == NULL)							// No more dial commands
		{
			DialSteps = 0;
			return true;														// Finished dialling
		}

		SystemTicks = 0;

		Debug_Print("Send: "); Debug_Print(CommandPtr);
		Debug_Print("(Expect: "); Debug_Print(ResponsePtr); Debug_Print(")\r\n");
				
		while (*CommandPtr)														
			RingBuffer_Insert(&Modem_SendBuffer, *(CommandPtr++));			// Send the command	to the modem
	}

	return false;																// Haven't finished dialling
}
예제 #14
0
파일: wi07.c 프로젝트: kehribar/xmegaE5
/* Fill tcpData array, return message length */
uint16_t waitTCPMessage_blocking()
{
  uint16_t len;
  wait_for_message("+IPD,",0);
  wait_for_message(",",0);
  len = getMessageLength(); 
  
  uint16_t t16;
  for(t16=0;t16 < len;t16++)
  {
    while(RingBuffer_GetCount(&Buffer) == 0);
    tcpData[t16] = RingBuffer_Remove(&Buffer);
  }

  wait_for_message("OK\r\n",10000);

  return len;
}
예제 #15
0
void RFM12B_Start_Transmit( void )
{
   uint16_t BufferCount = RingBuffer_GetCount( &USBtoRF12_Buffer );
   
   RingBuffer_InsertString( &Transmit_Buffer, "\xAA\xAA\x2D\x55" );
   RingBuffer_Insert( &Transmit_Buffer, BufferCount & 0xFF );
   
   while ( BufferCount-- )
   {
       RingBuffer_Insert( &Transmit_Buffer, 
           RingBuffer_Remove( &USBtoRF12_Buffer ));
   }

   RingBuffer_InsertString( &Transmit_Buffer, "\xAA\xAA" );
   RFM12B_Transmit_Active = true;
   PORTD &= ~0x20;
   RFM12B_SPI_Transfer( RFM12B_CMD_TX_ON );
}
예제 #16
0
파일: USBpwm.c 프로젝트: hsbp/usb_moodlight
void mood(void)
{
	static uint8_t command;
	static uint16_t i=0;
	static uint16_t r=MAXPWM,g=MAXPWM/2,b=MAXPWM/42;
	static uint16_t r_dir=R_SPEED, g_dir=G_SPEED, b_dir=B_SPEED;
	static bool loop=true;

	command=' ';	// default command: none

	/* Load the next command byte from the USB to USART transmit buffer */
	if (!(RingBuffer_IsEmpty(&USBtoUSART_Buffer)))
		  command=RingBuffer_Remove(&USBtoUSART_Buffer);
	switch (command) {
		case 'r': if (r >=1000) r-=1000; break;
		case 'R': if (r <= MAXPWM-1000) r+=1000; break;
		case 'g': if (g >=1000) g-=1000; break;
		case 'G': if (g <= MAXPWM-1000) g+=1000; break;
		case 'b': if (b >=1000) b-=1000; break;
		case 'B': if (b <= MAXPWM-1000) b+=1000; break;
		case 'h': loop=true; helloworld(); break;
		case '#': loop=setcmd(&r,&g,&b); break;
		case 'm': loop=true;
		default:
			if (++i > DELAY) {
				if(loop) {
					if (r >= (MAXPWM - R_SPEED)) r_dir = -R_SPEED;
					if (r <= R_SPEED) r_dir = R_SPEED;
					if (g >= (MAXPWM - G_SPEED)) g_dir = -G_SPEED;
					if (g <= G_SPEED) g_dir = G_SPEED;
					if (b >= (MAXPWM - B_SPEED)) b_dir = -B_SPEED;
					if (b <= B_SPEED) b_dir = B_SPEED;
					r += r_dir; g += g_dir; b += b_dir;
				}
				setcolor(r,g,b);
				//if (lowvoltage()) {	// red light and stop
				//	setcolor(MAXPWM,0,0);
				//	for(;;);
				//}
				i=0;
			}
	}
}
예제 #17
0
파일: wi07.c 프로젝트: kehribar/xmegaE5
/*---------------------------------------------------------------------------*/
int8_t wait_for_message(const char* checkmsg,uint32_t timeoutLimit)
{
  uint8_t ch;
  uint16_t in = 0;
  uint8_t run = 1;
  uint32_t timeout = 0;
  
  while(run == 1)
  {
    while(RingBuffer_GetCount(&Buffer) == 0)
    {
      if(timeoutLimit != 0)
      {
        timeout++;
        _delay_us(750);
        if(timeout > timeoutLimit) { return -1; }
      }
    } 

    ch = RingBuffer_Remove(&Buffer);

    if(ch == checkmsg[in])
    {
      in++;
    }
    else
    {
      if(timeoutLimit != 0)
      {
        timeout++;
        _delay_us(750);
        if(timeout > timeoutLimit) { return -1; }
      }
    }

    if(checkmsg[in] == '\0')
    {
      run = 0;
    }
  }

  return 0;
}
예제 #18
0
파일: USBtoSerial.c 프로젝트: ldarlok/LCS
void sendUSARTtoUSB ()
{
	uint16_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);
	if (BufferCount)
	{
		Endpoint_SelectEndpoint(VirtualSerial_CDC_Interface.Config.DataINEndpoint.Address);
		if (Endpoint_IsINReady())
		{
			uint8_t BytesToSend = MIN(BufferCount, (CDC_TXRX_EPSIZE - 1));
			while (BytesToSend--)
			{
				if (CDC_Device_SendByte(&VirtualSerial_CDC_Interface, RingBuffer_Peek(&USARTtoUSB_Buffer)) != ENDPOINT_READYWAIT_NoError)
				{
					break;
				}
				RingBuffer_Remove(&USARTtoUSB_Buffer);
			}
		}
	}
}
예제 #19
0
void UARTBridge_Task(void)
{
	/* Must be in the configured state for the USART Bridge code to process data */
	if (USB_DeviceState != DEVICE_STATE_Configured)
	  return;

	/* Only try to read in bytes from the CDC interface if the transmit buffer is not full */
	if (!(RingBuffer_IsFull(&USBtoUART_Buffer)))
	{
		int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);

		/* Read bytes from the USB OUT endpoint into the UART transmit buffer */
		if (!(ReceivedByte < 0))
		  RingBuffer_Insert(&USBtoUART_Buffer, ReceivedByte);
	}

	/* Check if the UART receive buffer flush timer has expired or buffer is nearly full */
	uint16_t BufferCount = RingBuffer_GetCount(&UARTtoUSB_Buffer);
	if ((TIFR0 & (1 << TOV0)) || (BufferCount > 200))
	{
		/* Clear flush timer expiry flag */
		TIFR0 |= (1 << TOV0);

		/* Read bytes from the USART receive buffer into the USB IN endpoint */
		while (BufferCount--)
		{
			/* Try to send the next byte of data to the host, abort if there is an error without dequeuing */
			if (CDC_Device_SendByte(&VirtualSerial_CDC_Interface,
									RingBuffer_Peek(&UARTtoUSB_Buffer)) != ENDPOINT_READYWAIT_NoError)
			{
				break;
			}

			/* Dequeue the already sent byte from the buffer now we have confirmed that no transmission error occurred */
			RingBuffer_Remove(&UARTtoUSB_Buffer);
		}
	}

	CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
}
예제 #20
0
/*---------------------------------------------------------------------------*/
int transport_getdata(uint8_t* buf, int count)
{
  int i;
  int t16;
  int8_t res;
  uint8_t sockId;

  while(count > RingBuffer_GetCount(&tcpBuffer))
  {
    res = esp8266_getTCPData(ESP8266_1SecTimeout,commonBuffer,sizeof(commonBuffer),&rv,&sockId);       

    if(res == ESP8266_TIMEOUT)
    {
      return 0;
    }

    if(sockId != 0)
    {
      esp8266_hal_rebootSystem();
    }
    
    for(i=0;i<rv;i++)
    {
      if(!RingBuffer_IsFull(&tcpBuffer))
      {
        RingBuffer_Insert(&tcpBuffer,commonBuffer[i]);        
      }
    }

  }

  for(i=0;i<count;i++)
  {
    buf[i] = RingBuffer_Remove(&tcpBuffer);
  }  

  return count;
}
예제 #21
0
파일: wi07.c 프로젝트: kehribar/xmegaE5
/*---------------------------------------------------------------------------*/
int8_t check_ok()
{
  uint8_t ch;
  uint8_t run = 1;
  uint16_t in = 0;
  uint32_t timeout = 0; 
  uint8_t ok_buf[4] = {'O','K','\r','\n'};
  
  while(run == 1)
  {
    while(RingBuffer_GetCount(&Buffer) == 0)
    {
      timeout++;
      _delay_us(750);
      if(timeout > 10000) { return -1; }      
    }     

    ch = RingBuffer_Remove(&Buffer);

    if(ch == ok_buf[in])
    {
      in++;
    }
    else
    {
      timeout++;
      _delay_us(750);
      if(timeout > 10000) { return -1; }
    }

    if(in == 4)
    {
      run = 0;
    }
  }

  return 0;
}
예제 #22
0
/** HID class driver callback function for the creation of HID reports to the host.
 *
 *  \param[in]     HIDInterfaceInfo  Pointer to the HID class interface configuration structure being referenced
 *  \param[in,out] ReportID    Report ID requested by the host if non-zero, otherwise callback should set to the generated report ID
 *  \param[in]     ReportType  Type of the report to create, either REPORT_ITEM_TYPE_In or REPORT_ITEM_TYPE_Feature
 *  \param[out]    ReportData  Pointer to a buffer where the created report should be stored
 *  \param[out]    ReportSize  Number of bytes written in the report (or zero if no report is to be sent
 *
 *  \return Boolean true to force the sending of the report, false to let the library determine if it needs to be sent
 */
bool CALLBACK_HID_Device_CreateHIDReport(
    USB_ClassInfo_HID_Device_t* const HIDInterfaceInfo,
    uint8_t* const ReportID,
    const uint8_t ReportType,
    void* ReportData,
    uint16_t* const ReportSize)
{
    USB_JoystickReport_Data_t *reportp = (USB_JoystickReport_Data_t*)ReportData;

    RingBuff_Count_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);

    if (BufferCount >= (sizeof(joyReport))) {
	uint8_t ind;
	for (ind=0; ind<sizeof(joyReport); ind++) {
	    ((uint8_t *)&joyReport)[ind] = RingBuffer_Remove(&USARTtoUSB_Buffer);
	}
    }

    *reportp = joyReport;

    *ReportSize = sizeof(USB_JoystickReport_Data_t);
    return false;
}
예제 #23
0
void UARTBridge_Task(void)
{
	/* Must be in the configured state for the USART Bridge code to process data */
	if (USB_DeviceState != DEVICE_STATE_Configured)
	  return;

	/* Read bytes from the USB OUT endpoint into the UART transmit buffer */
	int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);
	if (!(ReceivedByte < 0) && !(RingBuffer_IsFull(&USBtoUART_Buffer)))
	  RingBuffer_Insert(&USBtoUART_Buffer, ReceivedByte);
	
	/* Check if the UART receive buffer flush timer has expired or buffer is nearly full */
	RingBuff_Count_t BufferCount = RingBuffer_GetCount(&UARTtoUSB_Buffer);
	if ((TIFR0 & (1 << TOV0)) || (BufferCount > 200))
	{
		TIFR0 |= (1 << TOV0);

		/* Read bytes from the UART receive buffer into the USB IN endpoint */
		while (BufferCount--)
		  CDC_Device_SendByte(&VirtualSerial_CDC_Interface, RingBuffer_Remove(&UARTtoUSB_Buffer));
	}

	CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
}
/** Main program entry point. This routine contains the overall program flow, including initial
 *  setup of all components and the main program loop.
 */
int main(void)
{
	SetupHardware();

	RingBuffer_InitBuffer(&USARTtoUSB_Buffer, USARTtoUSB_Buffer_Data, sizeof(USARTtoUSB_Buffer_Data));

	sei();

	for (;;)
	{
		/* Echo bytes from the host to the target via the hardware USART */
		if ((UCSR1A & (1 << UDRE1)) && CDC_Device_BytesReceived(&VirtualSerial_CDC_Interface))
		{
			UDR1 = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);

			LEDs_TurnOnLEDs(LEDMASK_TX);
			PulseMSRemaining.TxLEDPulse = TX_RX_LED_PULSE_MS;
		}

		/* Check if the millisecond timer has elapsed */
		if (TIFR0 & (1 << OCF0A))
		{
			/* Clear flush timer expiry flag */
			TIFR0 |= (1 << TOV0);

			/* Check if the reset pulse period has elapsed, if so tristate the target reset line */
			if (PulseMSRemaining.ResetPulse && !(--PulseMSRemaining.ResetPulse))
			{
				LEDs_TurnOffLEDs(LEDMASK_BUSY);
				AVR_RESET_LINE_DDR &= ~AVR_RESET_LINE_MASK;
			}

			/* Check if the LEDs should be ping-ponging (during enumeration) */
			if (PulseMSRemaining.PingPongLEDPulse && !(--PulseMSRemaining.PingPongLEDPulse))
			{
				LEDs_ToggleLEDs(LEDMASK_TX | LEDMASK_RX);
				PulseMSRemaining.PingPongLEDPulse = PING_PONG_LED_PULSE_MS;
			}

			/* Turn off TX LED(s) once the TX pulse period has elapsed */
			if (PulseMSRemaining.TxLEDPulse && !(--PulseMSRemaining.TxLEDPulse))
			  LEDs_TurnOffLEDs(LEDMASK_TX);

			/* Turn off RX LED(s) once the RX pulse period has elapsed */
			if (PulseMSRemaining.RxLEDPulse && !(--PulseMSRemaining.RxLEDPulse))
			  LEDs_TurnOffLEDs(LEDMASK_RX);

			/* Check if the receive buffer flush period has expired */
			uint16_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);
			if (!(--FlushPeriodRemaining) || (BufferCount > 200))
			{
				FlushPeriodRemaining = RECEIVE_BUFFER_FLUSH_MS;

				/* Start RX LED indicator pulse */
				if (BufferCount)
				{
					LEDs_TurnOnLEDs(LEDMASK_RX);
					PulseMSRemaining.RxLEDPulse = TX_RX_LED_PULSE_MS;
				}

				/* Echo bytes from the target to the host via the virtual serial port */
				while (BufferCount--)
				{
					/* Try to send the next byte of data to the host, abort if there is an error without dequeuing */
					if (CDC_Device_SendByte(&VirtualSerial_CDC_Interface,
											RingBuffer_Peek(&USARTtoUSB_Buffer)) != ENDPOINT_READYWAIT_NoError)
					{
						break;
					}
					
					/* Dequeue the already sent byte from the buffer now we have confirmed that no transmission error occurred */
					RingBuffer_Remove(&USARTtoUSB_Buffer);
				}
			}
		}

		CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
		USB_USBTask();
	}
}
/** HID class driver callback function for the creation of HID reports to the host.
 *
 *  \param[in]     HIDInterfaceInfo  Pointer to the HID class interface configuration structure being referenced
 *  \param[in,out] ReportID    Report ID requested by the host if non-zero, otherwise callback should set to the generated report ID
 *  \param[in]     ReportType  Type of the report to create, either REPORT_ITEM_TYPE_In or REPORT_ITEM_TYPE_Feature
 *  \param[out]    ReportData  Pointer to a buffer where the created report should be stored
 *  \param[out]    ReportSize  Number of bytes written in the report (or zero if no report is to be sent
 *
 *  \return Boolean true to force the sending of the report, false to let the library determine if it needs to be sent
 */
bool CALLBACK_HID_Device_CreateHIDReport(
    USB_ClassInfo_HID_Device_t* const HIDInterfaceInfo,
    uint8_t* const ReportID,
    const uint8_t ReportType,
    void* ReportData,
    uint16_t* const ReportSize)
{
	if (ReportData != NULL && ReportSize != NULL)
	{
		if (ReportType == HID_REPORT_ITEM_Feature && *ReportID == 0x44)
		{
			uint8_t *reportp = ReportData;
			uint8_t id = *ReportID;

			*reportp++ = id;			

			memcpy(reportp, TouchBlob,
					       sizeof(TouchBlob));

			*ReportSize = sizeof(TouchBlob) + 1;
			return true;
		}
		else if (ReportType == HID_REPORT_ITEM_Feature)
		{
			USB_SurfaceReport_Feature_t *reportp = (USB_SurfaceReport_Feature_t*)ReportData;
			uint8_t maximumContactCount;
			maximumContactCount = 10;
			uint8_t id = *ReportID;

			reportp->ReportId = id;			
			reportp->MaximumContactCount = maximumContactCount;
			
			*ReportSize = sizeof(USB_SurfaceReport_Feature_t);
			return true;
		}
		else
		{
			USB_SurfaceReport_Data_t *reportp = (USB_SurfaceReport_Data_t*)ReportData;
		
			RingBuff_Count_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);
			uint8_t reportId = 1;		
			if (BufferCount >= SURFACE_REPORT_SIZE) 
			{
				uint8_t *ptr = ReportData;
				uint8_t TipSwitch = RingBuffer_Remove(&USARTtoUSB_Buffer);
				uint8_t ContactId = RingBuffer_Remove(&USARTtoUSB_Buffer);
				uint16_t  X = RingBuffer_Remove(&USARTtoUSB_Buffer) | (RingBuffer_Remove(&USARTtoUSB_Buffer) << 8);
				uint16_t  Y = RingBuffer_Remove(&USARTtoUSB_Buffer) | (RingBuffer_Remove(&USARTtoUSB_Buffer) << 8);
				uint16_t  ScanTime  = RingBuffer_Remove(&USARTtoUSB_Buffer) | (RingBuffer_Remove(&USARTtoUSB_Buffer) << 8);
				uint8_t ContactCount = RingBuffer_Remove(&USARTtoUSB_Buffer);
/*				
				*ptr++ = reportId;
				*ptr++ = TipSwitch;
				*ptr++ = ContactId;
				*ptr++ = (uint8_t)(X & 0xff);
				*ptr++ = (uint8_t)((X >> 8) & 0xff);
				*ptr++ = (uint8_t)(Y & 0xff);
				*ptr++ = (uint8_t)((Y >> 8) & 0xff);				
				*ptr++ = (uint8_t)(ScanTime & 0xff);
				*ptr++ = (uint8_t)((ScanTime >> 8) & 0xff);
				*ptr++ = ContactCount;
				
				*/
				reportp->ReportId = reportId;
				reportp->TipSwitch = (TipSwitch > 0) ? 0xff : 0 ;
				reportp->ContactId = ContactId;
				reportp->ScanTime = ScanTime;
				reportp->X = X;
				reportp->Y = Y;
				reportp->ContactCount = ContactCount;
				
				LEDs_TurnOnLEDs(LEDS_LED1);
				led1_ticks = LED_ON_TICKS;
			}
			else
			{
				
				reportp->ReportId = reportId;
				reportp->TipSwitch = 0;
				reportp->ContactId = 0;
				reportp->ScanTime = 0;
				reportp->X = 0;
				reportp->Y = 0;
				reportp->ContactCount = 0;
				
				*ReportSize = 0;
				return false;
			}
			*ReportSize = sizeof(USB_SurfaceReport_Data_t);
			return true;
		}
		*ReportSize = 0;
    }
    return false;
}
예제 #26
0
uint16_t network_read(void)
{
	uint8_t c;
	
	while (!RingBuffer_IsEmpty(&Modem_ReceiveBuffer))
	{
		c = RingBuffer_Remove(&Modem_ReceiveBuffer);

		switch (PacketState)
		{
			case PACKET_STATE_NULL:
				if (c == 0x7e)												// New Packet
				{
					PacketState = PACKET_STATE_INHEADER;					// We're now in the header
					PacketLength = 0;
					CurrentChecksum = 0xffff;								// Start new checksum
				}
			break;

			case PACKET_STATE_INHEADER:
				if (c == 0x7d)												// Escaped character. Set flag and process next time around
				{
					Escape = true;
					continue;
				}
				else if (Escape)											// Escaped character. Process now.
				{
					Escape = false;
					c = (c ^ 0x20);
				}
				
				if (PacketLength == 1 && c != 0xff)							// Should be 0xff. If not then Address-and-Control-Field-Compression is switched on
				{
					PacketLength += 2;										// Adjust the length as if the 0xff 0x03 was there
				}		

				if (PacketLength == 3)
				{
					if (c & 1)												// Should be even. If it's odd then Protocol-Field-Compression is switched on
					{
						PacketProtocol = 0x00;								// Add in the initial 0x00
						PacketLength++;										// Adjust the length as if the 0x00 was there
					}
					else
						PacketProtocol = c * 256;							// Store the MSB of the protocol
				}

				if (PacketLength == 4)										// End of header
				{														
					PacketProtocol |= c;									// Store the LSB of the protocol
					PacketLength = -1;										// This will be incremented to 0 at the end of this loop
					Escape = false;
					PacketState = PACKET_STATE_INBODY;						// We're now in the body
				}

				CurrentChecksum = CALC_CRC16(CurrentChecksum, c);			// Calculate checksum
			break;

			case PACKET_STATE_INBODY:
				if (c == 0x7e)												// End of packet
				{
					uip_len = PacketLength - 2;								// Strip off the checksum and framing
					Escape = false;
					PacketState = PACKET_STATE_NULL;						// Back to waiting for a header

					Debug_Print("\r\nReceive ");
					DumpPacket();

					if (~TwoBackChecksum == (*(uip_buf + PacketLength - 1) * 256 + *(uip_buf + PacketLength - 2)))
						return PacketProtocol;
					else
						Debug_Print("Bad CRC\r\n");
				}
				else
				{	
					if (c == 0x7d)											// Escaped character. Set flag and process next time around
					{
						Escape = true;
						continue;
					}
					else if (Escape)										// Escaped character. Process now.
					{
						Escape = false;
						c = (c ^ 0x20);
					}
					
					*(uip_buf + PacketLength) = c;							// Store the character in the buffer

					TwoBackChecksum = OneBackChecksum;						// Keep a rolling count of the last 3 checksums
					OneBackChecksum = CurrentChecksum;						// Eventually we need to see if the checksum is valid
					CurrentChecksum = CALC_CRC16(CurrentChecksum, c);		// and we need the one two back (as the current one includes the checksum itself)
				}
			break;
		}
		
		PacketLength++;														// Increment the length of the received packet
	}

	return 0;																// No data or packet not complete yet 
}
예제 #27
0
void parse_SER_buffer(uint8_t EGT_H, uint8_t EGT_L, uint8_t CHT_H, uint8_t CHT_L, uint32_t total_time_RPM)
{
	uint8_t OBD_headers = 0;
	uint16_t RPM_calc;
	uint8_t temp_ringer;
	uint8_t temp_mode;
	uint16_t tempEGTCHT1;
	uint16_t tempEGTCHT2;

	uint8_t ascii_1;
	uint8_t ascii_2;
	uint8_t ascii_3;
	uint8_t ascii_4;
	
	if( (!(RingBuffer_IsEmpty(&BTtoFF_Buffer))))
	{
		
		temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
		
		if(temp_ringer == 'A')
		{
			temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
			
			if(temp_ringer == 'T')	// We now have an AT command to parse
			{
				temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
				
				if(temp_ringer == 'Z')	// Reset command, fake it
				{
					//Serial_SendString_P(ELM327_ID);
					RingBuffer_Insert(&FFtoBT_Buffer,'E');
					RingBuffer_Insert(&FFtoBT_Buffer,'L');
					RingBuffer_Insert(&FFtoBT_Buffer,'M');
					RingBuffer_Insert(&FFtoBT_Buffer,'3');
					RingBuffer_Insert(&FFtoBT_Buffer,'2');
					RingBuffer_Insert(&FFtoBT_Buffer,'7');
					RingBuffer_Insert(&FFtoBT_Buffer,0X20);	// space
					RingBuffer_Insert(&FFtoBT_Buffer,'v');
					RingBuffer_Insert(&FFtoBT_Buffer,'1');
					RingBuffer_Insert(&FFtoBT_Buffer,'.');
					RingBuffer_Insert(&FFtoBT_Buffer,'3');
					send_ELM327_CR();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flag
				}
				else if(temp_ringer == 'E')	// Echo Command
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					send_ELM327_OK();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flag
				
				}
				else if(temp_ringer == 'M')	// Protocol Memory Command
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					send_ELM327_OK();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flag
				
				}
				else if(temp_ringer == 'L')	// Line Feed Command
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					send_ELM327_OK();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flag
				
				}
				else if(temp_ringer == 'S')	// Blank Spaces or Store Protocol Command
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					if(temp_ringer == 'H')	// Set Header
					{
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					}
					else if(temp_ringer == 'P')	// Set Protocol
					{
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// 0 or 1
					}
					
					send_ELM327_OK();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer		
					CR_flag = 0;	// Clears CR flag
				
				}
				else if(temp_ringer == 'H')	// Headers Command
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					//SendSERBuffer[temp_USB_indexer++]  = temp_ringer;
					if(temp_ringer == '1')
					{
						OBD_headers = 1;
					}
					else
					{
						OBD_headers = 0;
					}
					send_ELM327_OK();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flag
				
				}
				
				else if(temp_ringer == 'R')	// Responses Command
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					//SendSERBuffer[temp_USB_indexer++]  = temp_ringer;
					if(temp_ringer == 'V')
					{
						//Serial_SendString_P(FAKE_VOLTAGE);
						RingBuffer_Insert(&FFtoBT_Buffer,'1');
						RingBuffer_Insert(&FFtoBT_Buffer,'2');
						RingBuffer_Insert(&FFtoBT_Buffer,'.');
						RingBuffer_Insert(&FFtoBT_Buffer,'6');
						RingBuffer_Insert(&FFtoBT_Buffer,'V');
						send_ELM327_CR();
						send_ELM327_prompt();
					}
					else
					{					
						send_ELM327_OK();
						send_ELM327_prompt();
					}
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flag
				
				}
				else if(temp_ringer == 'V')	// Variable DLC Command
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					//SendSERBuffer[temp_USB_indexer++]  = temp_ringer;
					send_ELM327_OK();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flag
					
				}
				else if(temp_ringer == '1')	// ATAT1 Adaptive headers Command
				{
					send_ELM327_OK();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flagg
				
				}
				else if(temp_ringer == '@')	// Blank Spaces Command
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					//SendSERBuffer[temp_USB_indexer++]  = temp_ringer;
					if(temp_ringer == '1')	// Descriptor
					{
						//Serial_SendString_P(FF_mini);
						RingBuffer_Insert(&FFtoBT_Buffer,'F');
						RingBuffer_Insert(&FFtoBT_Buffer,'F');
						RingBuffer_Insert(&FFtoBT_Buffer,'m');
						RingBuffer_Insert(&FFtoBT_Buffer,'i');
						RingBuffer_Insert(&FFtoBT_Buffer,'n');
						RingBuffer_Insert(&FFtoBT_Buffer,'i');
						send_ELM327_CR();
						send_ELM327_prompt();
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
						CR_flag = 0;	// Clears CR flag
					}
					else
					{
						send_ELM327_OK();
						send_ELM327_prompt();
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
						CR_flag = 0;	// Clears CR flag
					}
				
				}
				else if(temp_ringer == 'I')	// ID Yourself command
				{
					//Serial_SendString_P(ELM327_ID);
					RingBuffer_Insert(&FFtoBT_Buffer,'E');
					RingBuffer_Insert(&FFtoBT_Buffer,'L');
					RingBuffer_Insert(&FFtoBT_Buffer,'M');
					RingBuffer_Insert(&FFtoBT_Buffer,'3');
					RingBuffer_Insert(&FFtoBT_Buffer,'2');
					RingBuffer_Insert(&FFtoBT_Buffer,'7');
					RingBuffer_Insert(&FFtoBT_Buffer,0X20);	// space
					RingBuffer_Insert(&FFtoBT_Buffer,'v');
					RingBuffer_Insert(&FFtoBT_Buffer,'1');
					RingBuffer_Insert(&FFtoBT_Buffer,'.');
					RingBuffer_Insert(&FFtoBT_Buffer,'3');
					send_ELM327_CR();
					send_ELM327_prompt();
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
					CR_flag = 0;	// Clears CR flag
				
				}
			
			}
		}
	//***********************************************************
	//	Didnt find AT command, so look for OBD command
	//***********************************************************
		else if (temp_ringer == '0')
		{
			temp_mode = RingBuffer_Remove(&BTtoFF_Buffer);
			//SendSERBuffer[temp_USB_indexer++]  = temp_mode;
			switch (temp_mode)
			{
				case '1':	// Mode 01
				temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
				//SendSERBuffer[temp_USB_indexer++]  = temp_ringer;
				if ((RingBuffer_Peek(&BTtoFF_Buffer)== '0'))
				{
					RingBuffer_Remove(&BTtoFF_Buffer);	// Removes peeked value above
					//SendSERBuffer[temp_USB_indexer++]  = '0';
					if(temp_ringer == '0')	// What PIDS are supported	0100
					{
						//Serial_SendByte('4');
						//Serial_SendByte('1');
						RingBuffer_Insert(&FFtoBT_Buffer,'4');
						RingBuffer_Insert(&FFtoBT_Buffer,'1');
						
						if(OBD_headers)
						{
							send_ELM327_header();		
						}
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						// Supported PIDS below
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('1');	// Support for RPM PID 0x0C
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'1');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						send_ELM327_CR();
						send_ELM327_prompt();
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
						CR_flag = 0;	// Clears CR flag
					}
					else if (temp_ringer == '2')	// 0120, PIDS 21-40 supported bit mask
					{
						//Serial_SendByte('4');
						//Serial_SendByte('1');
						//Serial_SendByte('2');
						//Serial_SendByte('0');
						RingBuffer_Insert(&FFtoBT_Buffer,'4');
						RingBuffer_Insert(&FFtoBT_Buffer,'1');
						RingBuffer_Insert(&FFtoBT_Buffer,'2');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');						
						// Supported PIDS below
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');	// Support for EGT bank PID 0x78
						//Serial_SendByte('1');
						//Serial_SendByte('8');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'1');
						RingBuffer_Insert(&FFtoBT_Buffer,'8');
						send_ELM327_CR();
						send_ELM327_prompt();
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
						CR_flag = 0;	// Clears CR flag
					}
				
					else    // kind of assuming its asking for what we support
					{
						//Serial_SendByte('4');
						//Serial_SendByte('1');
						//Serial_SendByte(temp_ringer);
						//Serial_SendByte('0');
						RingBuffer_Insert(&FFtoBT_Buffer,'4');
						RingBuffer_Insert(&FFtoBT_Buffer,'1');
						RingBuffer_Insert(&FFtoBT_Buffer,temp_ringer);
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						// Supported PIDS below
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						//Serial_SendByte('0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						send_ELM327_CR();	//	CR
						send_ELM327_prompt();
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
						CR_flag = 0;	// Clears CR flag
					}
				
				}
			
				else if (temp_ringer == '0')	// 010x
				{
					temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);
					
					if(temp_ringer == 'C')		// 010C
					{
						// RPM request
						//if((!first_cycle)&&(total_time_RPM))
						if(total_time_RPM)
						{
							//	This takes the total_time = timer1_OVF + timer1_HIGH + timer1_LOW
							//	and converts to the format required for OBD msg
							//	AND IT NEEDS TO BE OPTIMIZED TOO LARGE!!
							RPM_calc = (uint16_t)(((0xE4E1C000)/total_time_RPM));	
							ascii_4 =  pgm_read_byte(&hex_map[RPM_calc&0x000F]);
							RPM_calc >>=0x04;
							ascii_3 =  pgm_read_byte(&hex_map[RPM_calc&0x000F]);
							RPM_calc >>=0x04;
							ascii_2 =  pgm_read_byte(&hex_map[RPM_calc&0x000F]);
							RPM_calc >>=0x04;
							ascii_1 =  pgm_read_byte(&hex_map[RPM_calc&0x000F]);
						}
						else
						{
							// IDLE
							ascii_1 = '0';
							ascii_2 = '0';
							ascii_3 = '0';
							ascii_4 = '0';
						}
						//Serial_SendByte('4');
						//Serial_SendByte('1');
						//Serial_SendByte('0');
						//Serial_SendByte('C');
						RingBuffer_Insert(&FFtoBT_Buffer,'4');
						RingBuffer_Insert(&FFtoBT_Buffer,'1');
						RingBuffer_Insert(&FFtoBT_Buffer,'0');
						RingBuffer_Insert(&FFtoBT_Buffer,'C');
						//Serial_SendByte(ascii_1);
						//Serial_SendByte(ascii_2);
						//Serial_SendByte(ascii_3);
						//Serial_SendByte(ascii_4);
						RingBuffer_Insert(&FFtoBT_Buffer,ascii_1);
						RingBuffer_Insert(&FFtoBT_Buffer,ascii_2);
						RingBuffer_Insert(&FFtoBT_Buffer,ascii_3);
						RingBuffer_Insert(&FFtoBT_Buffer,ascii_4);
						send_ELM327_CR();
						send_ELM327_prompt();
						temp_ringer = RingBuffer_Remove(&BTtoFF_Buffer);	// PULLS CR out of buffer
						CR_flag = 0;	// Clears CR flag
					}
				}
예제 #28
0
/** Main program entry point. This routine contains the overall program flow, including initial
 *  setup of all components and the main program loop.
 */
int main(void)
{
	SetupHardware();
	
	RingBuffer_InitBuffer(&USBtoUSART_Buffer);
	RingBuffer_InitBuffer(&USARTtoUSB_Buffer);

    setupEeprom();

	sei();


	for (;;)
	{

		// Only try to read in bytes from the CDC interface if the transmit buffer is not full
		if (!(RingBuffer_IsFull(&USBtoUSART_Buffer)))
		{
			int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);

			// Read bytes from the USB OUT endpoint into the USART transmit buffer
			if (!(ReceivedByte < 0))
			  RingBuffer_Insert(&USBtoUSART_Buffer, ReceivedByte);
		}
		
		// Check if the UART receive buffer flush timer has expired or the buffer is nearly full
		RingBuff_Count_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);
		if ((TIFR0 & (1 << TOV0)) || (BufferCount > BUFFER_NEARLY_FULL))
		{
			TIFR0 |= (1 << TOV0);

			if (USARTtoUSB_Buffer.Count) {
				LEDs_TurnOnLEDs(LEDMASK_TX);
				PulseMSRemaining.TxLEDPulse = TX_RX_LED_PULSE_MS;
			}

			// Read bytes from the USART receive buffer into the USB IN endpoint
			while (BufferCount--)
			  CDC_Device_SendByte(&VirtualSerial_CDC_Interface, RingBuffer_Remove(&USARTtoUSB_Buffer));
			  
			// Turn off TX LED(s) once the TX pulse period has elapsed
			if (PulseMSRemaining.TxLEDPulse && !(--PulseMSRemaining.TxLEDPulse))
			  LEDs_TurnOffLEDs(LEDMASK_TX);

			// Turn off RX LED(s) once the RX pulse period has elapsed
			if (PulseMSRemaining.RxLEDPulse && !(--PulseMSRemaining.RxLEDPulse))
			  LEDs_TurnOffLEDs(LEDMASK_RX);

			if (ResetTimer > 0)
			{
				// SAM3X RESET/ERASE Sequence
				// --------------------------
				if (ResetTimer == 95) {
                    eepromInterruptDisable();
					setErasePin(true);
					setResetPin(false);
				}
				if (ResetTimer == 35) {
                    eepromInterruptDisable();
					setErasePin(false);
					setResetPin(false);
				}
				if (ResetTimer == 25) {
                    eepromInterruptDisable();
					setErasePin(false);
					setResetPin(true);
				}
				if (ResetTimer == 1) {
                    eepromInterruptDisable();
					setErasePin(false);
					setResetPin(false);
				}
				ResetTimer--;
			} else {
				setErasePin(false);
				setResetPin(false);
                eepromInterruptEnable();
			}
		}
		
		// Load the next byte from the USART transmit buffer into the USART
		if (!(RingBuffer_IsEmpty(&USBtoUSART_Buffer))) {
			Serial_TxByte(RingBuffer_Remove(&USBtoUSART_Buffer));
			LEDs_TurnOnLEDs(LEDMASK_RX);
			PulseMSRemaining.RxLEDPulse = TX_RX_LED_PULSE_MS;
		}

        // CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
        // USB_USBTask();
        serviceEepromRequest();
		CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
		USB_USBTask();
	}

}
예제 #29
0
//------------------------------------------------------------------------------
static uint8_t serialProcess(Application *app)
{
    uint16_t count = RingBuffer_GetCount(&app->buffer_);
    if(count == 0)
        return true;

    uint8_t cmd = RingBuffer_Peek(&app->buffer_);
    switch(cmd)
    {
        case 'L':
            RingBuffer_Remove(&app->buffer_);
            LEDs_ToggleLEDs(LEDS_LED1);
            break;

        case 'R':
            RingBuffer_Remove(&app->buffer_);
            asicReset();
            asicResetSpi();
            app->state.state = STATE_RESET;
            sendCmdReply(app, cmd, (uint8_t *)&app->state, sizeof(State));
            break;

        case 'I':
            RingBuffer_Remove(&app->buffer_);
            sendCmdReply(app, cmd, (uint8_t *)&ID, sizeof(ID));
            break;

        case 'A':
            RingBuffer_Remove(&app->buffer_);
            app->state.state = STATE_RESET;
            asicStop();
            sendCmdReply(app, cmd, (uint8_t *)&app->state, sizeof(State));
            break;

        case 'S':
            RingBuffer_Remove(&app->buffer_);
            sendCmdReply(app, cmd, (uint8_t *)&app->state, sizeof(State));
            break;

        case 'W':
            if(count > 44) // 32 bytes midstate + 12 bytes data
            {
                RingBuffer_Remove(&app->buffer_);

                uint8_t i = 0;
                uint8_t *midstate = (uint8_t *)app->worktask.midstate;
                uint8_t *data = (uint8_t *)app->worktask.data;
                for(i=0; i<32; i++)
                {
                    midstate[i] = RingBuffer_Remove(&app->buffer_);
                }
                for(i=0; i<12; i++)
                {
                    data[i] = RingBuffer_Remove(&app->buffer_);
                }

                asicPrecalc(app->worktask.midstate, app->worktask.data, app->worktask.precalc);

                app->state.state = STATE_WORKING;
                app->state.nonce_valid = 0;
                app->state.nonce = 0;

                asicReset();
                asicResetSpi();
                pushWork(app, &app->worktask);
                timerSet(&app->work_timer, 16000);

                sendCmdReply(app, cmd, (uint8_t *)&app->state, sizeof(State));
            }
            break;

        default:
            RingBuffer_Remove(&app->buffer_);
            break;
    }

    return true;
}
예제 #30
0
int main(void)
{
    SetupHardware();

    RingBuffer_InitBuffer(&RF12toUSB_Buffer, RF12toUSB_Buffer_Data, sizeof(RF12toUSB_Buffer_Data));
    RingBuffer_InitBuffer(&USBtoRF12_Buffer, USBtoRF12_Buffer_Data, sizeof(USBtoRF12_Buffer_Data));
    RingBuffer_InitBuffer(&Transmit_Buffer,  Transmit_Buffer_Data,  sizeof(Transmit_Buffer_Data));

    sei();

    for (;;)
    {
        uint16_t RFM12B_status = RFM12B_SPI_Transfer(0);
        
        if (( RFM12B_status & RFM12B_STATUS_RSSI )
           && !RFM12B_Transmit_Active )
        {
            PORTD &= ~0x40;
        }
        else
        {
            PORTD |= 0x40;
        }
        
        /* Only try to read in bytes from the CDC interface if the transmit buffer is not full */
        if (  !RingBuffer_IsFull( &USBtoRF12_Buffer )
           && !RFM12B_Transmit_Active )
        {
            int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);

            /* Read bytes from the USB OUT endpoint into the USART transmit buffer */
            if (!(ReceivedByte < 0)) 
            {  
               if ( ReceivedByte != END_OF_PACKET )
               {
                   RingBuffer_Insert( &USBtoRF12_Buffer, ReceivedByte );
               }
               else
               {
                   /* TODO : Need to implement LBT */
                   RFM12B_Start_Transmit();
               }
            }
        }

        /* Check to see if there's an RGIT or an FFIT bit set in the status
           register indicating that we need to send or receive a byte */
        if ( RFM12B_status & RFM12B_STATUS_RGIT )
        {
            if ( RFM12B_Transmit_Active )
            {
                RFM12B_Transmit();
            }
            else
            {
                RFM12B_Receive();
            }
        }
        
        /* Check the flush timer.  This is used to timeout incoming packets
           that don't arrive in time or to flush the data to the USB host.
           First, check to see if we are in the middle of receiving a packet */
        if ( RxLength )
        {
            /* A packet is being received. Check the flush timer
               and timeout the packet if it takes too long */
            if ( TIFR0 & _BV(TOV0))
            {
                /* Clear flush timer expiry flag */
                TIFR0 |= _BV(TOV0);

                /* Flush timer overflows every 4ms.  256 bytes at ~50k
                   should take approximately 42ms so we allow 12 counts
                   for overflow.  This should probably be calculated
                   based on the bit rate and max message length */
                if ( ++RxTimeout > 12 )
                {
                    RingBuffer_Insert( &RF12toUSB_Buffer, END_OF_PACKET );
                    RFM12B_SPI_Transfer( 0xCA81 );
                    RFM12B_SPI_Transfer( 0xCA83 );
                    RxLength = 0;
                }
            }
        }
        else
        {
            /* No packet is being received.  Check if the UART receive 
               buffer flush timer has expired or the buffer is nearly full */
            uint16_t BufferCount = RingBuffer_GetCount(&RF12toUSB_Buffer);
            if ((TIFR0 & (1 << TOV0)) || (BufferCount > (uint8_t)(sizeof(RF12toUSB_Buffer_Data) * .75)))
            {
                /* Clear flush timer expiry flag */
                TIFR0 |= _BV(TOV0);
    
                /* Read bytes from the USART receive buffer into the USB IN endpoint */
                while (BufferCount--)
                {
                    /* Try to send the next byte of data to the host, abort if there is an error without dequeuing */
                    if (CDC_Device_SendByte(&VirtualSerial_CDC_Interface,
                                            RingBuffer_Peek(&RF12toUSB_Buffer)) != ENDPOINT_READYWAIT_NoError)
                    {
                        break;
                    }
    
                    /* Dequeue the already sent byte from the buffer now we have confirmed that no transmission error occurred */
                    RingBuffer_Remove(&RF12toUSB_Buffer);
                }
            }
        }
        
        CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
        USB_USBTask();
    }
}