Using LUFA USART-Serial Module with XMEGA C3-Xplained Kit

Go To Last Post
20 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I'm fairly new to both evaluation boards and posting:

 

I have been trying to set up two serial communication lines being PC Terminal-XMEGA and XMEGA - Arduino Uno.

I have managed to setup the first one using the LUFA CDC Application, which works fine in both directions.

 

However, the second one has proven rather difficult. In contrast to the LUFA approach, setting up the USART via Atmel Start has worked fine which does not make any sense to me.

Through debugging I have found that the transmission is blocked by the isSendReady() check in my LUFA implementation.

 

Any ideas anybody?

Code dumped below, please indulge the lack of other information (which will happily provide) for this is my first attempt at posting.

void inputCallback();
void calc_checksum();

#include "VirtualSerial.h"
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "asf.h"

char inputFrame[10];
bool messageComplete = false;
char in[10];
int i = 0;
uint8_t c0 = 0x35;
uint8_t c1 = 0x37;
uint8_t sc = 0x3B;
uint8_t checksum[2];


/** LUFA CDC Class driver interface configuration and state information. This structure is
 *  passed to all CDC Class driver functions, so that multiple instances of the same class
 *  within a device can be differentiated from one another.
 */
USB_ClassInfo_CDC_Device_t VirtualSerial_CDC_Interface =
	{
		.Config =
			{
				.ControlInterfaceNumber   = INTERFACE_ID_CDC_CCI,
				.DataINEndpoint           =
					{
						.Address          = CDC_TX_EPADDR,
						.Size             = CDC_TXRX_EPSIZE,
						.Banks            = 1,
					},
				.DataOUTEndpoint =
					{
						.Address          = CDC_RX_EPADDR,
						.Size             = CDC_TXRX_EPSIZE,
						.Banks            = 1,
					},
				.NotificationEndpoint =
					{
						.Address          = CDC_NOTIFICATION_EPADDR,
						.Size             = CDC_NOTIFICATION_EPSIZE,
						.Banks            = 1,
					},
			},
	};

/** Standard file stream for the CDC interface when set up, so that the virtual CDC COM port can be
 *  used like any regular character stream in the C APIs.
 */
static FILE USBSerialStream;



/** 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();

	/* Create a regular character stream for the interface so that it can be used with the stdio.h functions */
	CDC_Device_CreateStream(&VirtualSerial_CDC_Interface, &USBSerialStream);
	
	// Initialize the serial USART driver before first use, with 4800 baud (and no double-speed mode)
	Serial_Init(&USARTC0,4800,false);
	
		  
	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
	GlobalInterruptEnable();
	
	calc_checksum();
	
	while (true)
	{
	
	
		/* Must throw away unused bytes from the host, or it will lock up while waiting for the device */
		//CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);
		
		
		/* VCOM Communication Process Block: PC - MCU */
		
	  /*  fputs("First Byte: ",&USBSerialStream);
		CDC_Device_SendByte(&VirtualSerial_CDC_Interface,checksum[0]);		
		fputs("Second Byte: ",&USBSerialStream);
		CDC_Device_SendByte(&VirtualSerial_CDC_Interface,checksum[1]);
		*/
		
		if(messageComplete) {
		
		messageComplete = false;
		fputs("Frame Complete \r\n",&USBSerialStream);
		fputs(inputFrame,&USBSerialStream);
		memset(inputFrame,0,10);
		i=0;	
		}
		
		else if(!messageComplete){
		
		inputCallback();	
		}
		
		
		/* USART Communication Process Block */
		
		
		Serial_putchar(0x41,&USARTSerialStream); // Send Test Character
		
	
		
		CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
		USB_USBTask();
		
		
	}
}


void inputCallback() {
	


	while((CDC_Device_BytesReceived(&VirtualSerial_CDC_Interface)>0)&&(!messageComplete)) {
	
	uint8_t inbyte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);
	if((char)inbyte==*"E") {
	messageComplete	= true;
		
	}
	else{}	 
	inputFrame[i] = inbyte;	
	i = i +1;
	}
	//fputs(inputFrame,&USBSerialStream);	
}

/** Calculates the Checksum via modulo 256 summation as per sheet */
void calc_checksum(){ 
	
	uint8_t sum = c0+c1+sc+sc;
	checksum[0] = (sum%256)/16;
	checksum[1] = (sum%256)%16;
	
}


/** Configures the board hardware and chip peripherals for the demo's functionality. */
void SetupHardware(void)
{
#if (ARCH == ARCH_AVR8)
	/* Disable watchdog if enabled by bootloader/fuses */
	MCUSR &= ~(1 << WDRF);
	wdt_disable();

	/* Disable clock division */
	clock_prescale_set(clock_div_1);
#elif (ARCH == ARCH_XMEGA)
	/* Start the PLL to multiply the 2MHz RC oscillator to 32MHz and switch the CPU core to run from it */
	XMEGACLK_StartPLL(CLOCK_SRC_INT_RC2MHZ, 2000000, F_CPU);
	XMEGACLK_SetCPUClockSource(CLOCK_SRC_PLL);

	/* Start the 32MHz internal RC oscillator and start the DFLL to increase it to 48MHz using the USB SOF as a reference */
	XMEGACLK_StartInternalOscillator(CLOCK_SRC_INT_RC32MHZ);
	XMEGACLK_StartDFLL(CLOCK_SRC_INT_RC32MHZ, DFLL_REF_INT_USBSOF,F_USB);

	PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_HILVLEN_bm;
#endif

	/* Hardware Initialization */
	
	LEDs_Init();
	USB_Init();
}



/** Event handler for the library USB Connection event. */
void EVENT_USB_Device_Connect(void)
{
	LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
}

/** Event handler for the library USB Disconnection event. */
void EVENT_USB_Device_Disconnect(void)
{
	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
}

/** Event handler for the library USB Configuration Changed event. */
void EVENT_USB_Device_ConfigurationChanged(void)
{
	bool ConfigSuccess = true;

	ConfigSuccess &= CDC_Device_ConfigureEndpoints(&VirtualSerial_CDC_Interface);

	LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
}

/** Event handler for the library USB Control Request reception event. */
void EVENT_USB_Device_ControlRequest(void)
{
	CDC_Device_ProcessControlRequest(&VirtualSerial_CDC_Interface);
}

/** CDC class driver callback function the processing of changes to the virtual
 *  control lines sent from the host..
 *
 *  \param[in] CDCInterfaceInfo  Pointer to the CDC class interface configuration structure being referenced
 */
void EVENT_CDC_Device_ControLineStateChanged(USB_ClassInfo_CDC_Device_t *const CDCInterfaceInfo)
{
	/* You can get changes to the virtual CDC lines in this callback; a common
	   use-case is to use the Data Terminal Ready (DTR) flag to enable and
	   disable CDC communications in your application when set to avoid the
	   application blocking while waiting for a host to become ready and read
	   in the pending data from the USB endpoints.
	*/
	bool HostReady = (CDCInterfaceInfo->State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR) != 0;
}


 

Last Edited: Wed. Sep 29, 2021 - 08:05 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 1

LUFA on an Xmega ? I'm pretty sure Dean suggested this was "alpha" at best. Most folks would turn to ASF for USB support on Xmega rather than LUFA.

 

EDIT: this... LUFA and Xmega

Last Edited: Wed. Sep 29, 2021 - 03:05 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I am aware of that, but surprisingly USB support is working fine so far. I'm rather stuck on the USART part.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

oozdelalune wrote:

I have been trying to set up two serial communication lines being PC Terminal-XMEGA and XMEGA - Arduino Uno.

I have managed to setup the first one using the LUFA CDC Application, which works fine in both directions.

 

However, the second one has proven rather difficult.

...

Through debugging I have found that the transmission is blocked by the isSendReady() check in my LUFA implementation.

 

So If I understand this correctly you have two COMMS channels:

  1. PC Terminal-XMEGA uses a USB physical link using the USB peripheral.
  2. XMEGA - Arduino Uno uses logic level RS-232 type asynchronous comms using the USART peripheral.

 

If the above is correct.

  1. How does isSendReady() in LUFA relate to the Channel-2 problem ?
  2. Did you disable the USB-UART Bridge chip on the UNO ?

 

Last Edited: Thu. Sep 30, 2021 - 10:10 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hello,

 

Assumption Nr. 1 is correct.

 

To make things clear about Assumption Nr. 2: 

The XMEGA - UNO channel consists of three jumpers for the RX,TX and Ground respectively.

 

Question 1:

Well, I admit that was a shot in the dark. I tried incorporating a check through that function and it turned out that isSendReady() never returns true.

 

 

Question 2:

I did not disable said Bridge on the UNO because I'm using a dedicated SoftwareSerial.

 

Maybe I should turn to regular ASF after all?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I'm still confused by your question:

 

Are you saying the following line of code doesn't work ?

	Serial_putchar(0x41,&USARTSerialStream); // Send Test Character

 

Are they not ASF functions / structs anyway ??

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Correct, it is that specific line that doesn't work.

That particular function is implemented in the LUFA Framework. That being said, I have tried other functions such as 

Serial_SendByte(&USARTC0,0x41);

without success :/. 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

So you're trying to use LUFA routines on a real USART. I doubt that will work.

 

OK I think it's a simple solution. There's USARTSerialStream. If that's a real character stream you should be able to use the C standard I/O functions on it.  (fputc and fwrite etc).

 

You could also use the ASF functions directly on the USART object itself

usart_putchar(&USARTC0,0x41);

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Why should using LUFA on a real USART not be feasible? And if so, why is there an USART module anyway if a dedicated USB implementation exists next to it?

 

I have tried using the functions you suggested but no avail..

 

I'm really getting desperate at this point... Seems like no one tried implementing both a VCOM via USB and a real UART on the xmega?

 

I've tried setting up the USART with a ATMEL-Start configured project, and it seems to work fine with the stdio functions. But now I am stuck with getting the USB-CDC to work.

I have been trying a lot of approaches until this point but keep getting impeded at different stages of the modules.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The docs for LUFA say (for Xmega) that the interface is:

static void 	Serial_SendByte (USART_t *const USART, const char DataByte) ATTR_ALWAYS_INLINE ATTR_NON_NULL_PTR_ARG(1)

so I would probably have expected your:

Serial_SendByte(&USARTC0,0x41);

to work. However it obviously requires a call to:

static void 	Serial_Init (USART_t *const USART, const uint32_t BaudRate, const bool DoubleSpeed) ATTR_NON_NULL_PTR_ARG(1)

first.

 

Try putting together a 5 line main() that forgets all the USB stuff and ONLY does one call to Serial_Init() then repeated calls to Serial_SendByte() then put a scope on the TXD pin.

 

The usual problem with UARTs is simply a misunderstanding about the CPU clock speed (though I guess this must be right in the makefiles if USB works?).

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thank you for your suggestion. I have modified the code as you advised.

 

I have uploaded a screenshot with the updated main(). Unfortunately the scope on the TxD pin being the PC03 doesn't yield any information? I'm not sure if I did that right, please see provided screenshot.

Attachment(s): 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I don't know an awful lot about Xmega but I seem to remember that one of the ways they differ from traditional tiny/mega chips is that in the latter, when you enable a UART (TXEN) then at the same time the micro makes the TXD pin that the UART data goes out of an output. I seem to remember that in Xmega this does not happen automatically. So when a UART is used you also need code to set the transmit pin to output. Now maybe this happens" "inside" Dean's Serial_Init() but it's the kind of thing that could stop activity on a TX pin.

 

But in the OP you suggested the code was "blocking". That is something else entirely - sure the kind of code that transmits UART bytes usually checks first that the transmit holding register is empty before it loads the next byte to be sent and therefore there is often code sitting in a while() loop waiting to see the "register is now empty and ready to be written" flag but as long as a UART is actually enabled with a suitable clock then shortly after the UART data register is written and the transmission process begins then the holding register should become available. So a Serial_SendByte() might have to wait a very short while for "the last character sent to be cleared" but there's nothing in the process what should ever "block" so it just sits waiting indefinitely.

 

If you have a JTAG/PDI debugger I would watch this at the register level and see exactly where the code gets "stuck" if that is really what is happening.

 

Of course another alternative, if you can't get Dean's code to work is to simply write your own UART transmit stuff. The only complex bit about getting a UART to work is to get the baud rate set to what you require. The actual sending of bytes is usually trivial - like a say a short wait in a while() loop just to wait for any previous character to move on and then a write to a UARt data register and that's about it. I'm sure Atmel have an app note about driving the UARt in an Xmega somewhere.

 

(oh and I'm a luddite - I always call these things "UART" - because of other functionality they are technically "USART" these days).

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0


clawson wrote:
... the CPU clock speed (though I guess this must be right in the makefiles if USB works?).
CPU and USB are on separate clock domains; USB XMEGA have the four synchronization instructions in lieu of dual-port RAM.

Atmel AVR XMEGA C Manual

[page 74]

"Dare to be naïve." - Buckminster Fuller

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hey Clawson,

 

thanks again for bearing with me on this..

I have found that in the function body of sendByte below, the Byte is actually written to the Register during the first couple of iterations. Thereafter the blocking occurs. But Still, even with the registers being written to there is nothing happening on the receiving end of the arduino.

				while (!(Serial_IsSendReady(USART)));
				USART->DATA = DataByte;

Could this be related to the Pin-Mapping you spoke of?

I've tried setting PC02 and PC03 to RxD and TxD in the lines following Serial_Init below.

 

	Serial_Init(&USARTC0,4800,false);
	PORTC_OUTSET = PIN3_bm;
	PORTC_DIRSET = PIN3_bm;
	
	PORTC_OUTCLR = PIN2_bm;
	PORTC_DIRCLR = PIN2_bm;

 

That sadly did not do the trick.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

To be honest I've never really looked into Xmega deeply enough to be able to help at that level. Yes, you have to take control of pin IO directions yourself (unlike tiny/mega the peripheral does not do this for you), yes these devices often have pin muxing so you may need to switch the peripheral signals to the right pins and yes the baud rate setting is far more complex that previous AVR (though this allows for finer granularity) but how you achieve that is anyone's guess.

 

I would start at first principles though - make sure you are very sure what speed the CPU (and IO peripherals) are running at to stand any hope of getting the baud rate setting correct. But even if you get the clock/baud rate wrong I would expect that when UARTx.DATA is written that something would happen on the associated pin even if the signal is at the wrong speed. If the scope shows nothing then likely candidates do seem to be (a) the UART isn't actually enabled (does it need a clock switched through to it in the first place?), (b) the pin is not output and (c) the muxing is wrong so it's going to a different pin or no pin at all.

 

Perhaps Xmega users will have more detailed suggestions?

 

(because of the new Xmega: AVR-0, AVR-1, AVR-Dx I guess I should stop being a luddite one day and actually try using something Xmega based - the irony is that over the years Atmel have sent me eval boards for pretty much everything so I probably have some Xmega-ish things in a box somewhere!)

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Ok. I removed the LUFA USART Framework because I couldnt make any sense of it. Instead, I tried setting up the USART on my own and scraps of ATMEL Start code that weren't working on their own.

As it turned out, your hunch regarding the clock speeds was right. But oh boy, what a mess this is.

 

uint32_t cpu_hz = F_CPU;

The Baudrate section of the init function runs that line of code. Turns out that for some reason the F_CPU is taken from delay.h at 1 MHz rather than the actual 2 MHz from the config header. I ended up having to change that to static 2 MHz, and it FINALLY worked.

I really do not know a lot about allocating/asserting the speeds at which the peripherals run. Which sort of brings me to the next issue.

 

Like I stated in the OP, I am trying to run a USB VCOM together with a real U(S)ART.  Running both of these routines at once seems to be affecting the USART in a way where the data is compromised.

 

I am sending 0x45 on the real USART which corresponds to E in ASCII. With the USB-Module in place I get ⸮f⸮f⸮f⸮f 

Again, I have the strong suspicion that I am still dealing with the same issue, but only somewhere here:

 


#if (ARCH == ARCH_AVR8)
	/* Disable watchdog if enabled by bootloader/fuses */
	MCUSR &= ~(1 << WDRF);
	wdt_disable();

	/* Disable clock division */
	clock_prescale_set(clock_div_1);
#elif (ARCH == ARCH_XMEGA)
	/* Start the PLL to multiply the 2MHz RC oscillator to 32MHz and switch the CPU core to run from it */
	XMEGACLK_StartPLL(CLOCK_SRC_INT_RC2MHZ, 2000000, F_CPU);
	XMEGACLK_SetCPUClockSource(CLOCK_SRC_PLL);

	/* Start the 32MHz internal RC oscillator and start the DFLL to increase it to 48MHz using the USB SOF as a reference */
	XMEGACLK_StartInternalOscillator(CLOCK_SRC_INT_RC32MHZ);
	XMEGACLK_StartDFLL(CLOCK_SRC_INT_RC32MHZ, DFLL_REF_INT_USBSOF, F_USB);

	PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_HILVLEN_bm;
#endif

	/* Hardware Initialization */

	LEDs_Init();
	USB_Init();
	USART_0_initialization();

 

Could it be possible that there is a shift in the baudrate caused by the changes in the clock speeds? If so, how do I go by separating these two?

I think I am on the right track, as putting the USART_0_initialization() on top seems to have some effect on the USART data transmission. But that is as far as my limited knowledge goes.

 

edit: spelling

Last Edited: Wed. Oct 6, 2021 - 03:38 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

oozdelalune wrote:

/* Start the 32MHz internal RC oscillator and start the DFLL to increase it to 48MHz using the USB SOF as a reference */

There's a clue - The XMEGA target frequency is being adjusted in order to match your USB device's physical data link line speed with that of tthe USB Host.

 

You could test this theory by checking if the USART works OK until you plug in the USB cable for the first time.

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hmm the code in question is required in order to get the USB line to work in the first place, meaning that the connect / disconnect callbacks won't be functional.

Still, having the USB-related code removed from the program solves the issue. Which means it is definitely the issue? Also, opening and closing the port via putty also affects the bytes on the USART.

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Are you suggesting it gets "stuck" inside:

		USB_USBTask();

then? The main loop does have to call USB_USBtask() fairly regularly to keep the USB engine ticking over but it should come back out of that quickly.

Last Edited: Thu. Oct 7, 2021 - 03:20 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hmm I'm not sure if I can follow. Code atm looks like this: There is no being stuck anymore, both serial lines are working on their own, but the USART stops once the USB-CDC is in place.

 

/*
             LUFA Library
     Copyright (C) Dean Camera, 2017.

  dean [at] fourwalledcubicle [dot] com
           www.lufa-lib.org
*/

/*
  Copyright 2017  Dean Camera (dean [at] fourwalledcubicle [dot] com)

  Permission to use, copy, modify, distribute, and sell this
  software and its documentation for any purpose is hereby granted
  without fee, provided that the above copyright notice appear in
  all copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting
  documentation, and that the name of the author not be used in
  advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.

  The author disclaims all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

/** \file
 *
 *  Main source file for the VirtualSerial demo. This file contains the main tasks of
 *  the demo and is responsible for the initial application hardware configuration.
 */

#include "VirtualSerial.h"
enum port_output_pull_mode {
	PORT_CONFIGURATION_TOTEM,
	PORT_CONFIGURATION_BUSKEEPER,
	PORT_CONFIGURATION_PULLDOWN,
	PORT_CONFIGURATION_PULLUP,
	PORT_CONFIGURATION_WIREDOR,
	PORT_CONFIGURATION_WIREDAND,
	PORT_CONFIGURATION_WIREDORPULL,
	PORT_CONFIGURATION_WIREDANDPULL
};
int8_t USART_0_init();
void USART_0_initialization(void);
void USART_0_enable();
static inline void PORTC_set_pin_output_pull_mode(const uint8_t pin, const enum port_output_pull_mode output_pull_mode);
void USART_0_enable_rx();

void USART_0_enable_tx();

void USART_0_disable();

uint8_t USART_0_get_data();

bool USART_0_is_tx_ready();

bool USART_0_is_rx_ready();

bool USART_0_is_tx_busy();

uint8_t USART_0_read(void);

void USART_0_write(const uint8_t data);

/** LUFA CDC Class driver interface configuration and state information. This structure is
 *  passed to all CDC Class driver functions, so that multiple instances of the same class
 *  within a device can be differentiated from one another.
 */
USB_ClassInfo_CDC_Device_t VirtualSerial_CDC_Interface =
	{
		.Config =
			{
				.ControlInterfaceNumber   = INTERFACE_ID_CDC_CCI,
				.DataINEndpoint           =
					{
						.Address          = CDC_TX_EPADDR,
						.Size             = CDC_TXRX_EPSIZE,
						.Banks            = 1,
					},
				.DataOUTEndpoint =
					{
						.Address          = CDC_RX_EPADDR,
						.Size             = CDC_TXRX_EPSIZE,
						.Banks            = 1,
					},
				.NotificationEndpoint =
					{
						.Address          = CDC_NOTIFICATION_EPADDR,
						.Size             = CDC_NOTIFICATION_EPSIZE,
						.Banks            = 1,
					},
			},
	};

/** Standard file stream for the CDC interface when set up, so that the virtual CDC COM port can be
 *  used like any regular character stream in the C APIs.
 */
static FILE USBSerialStream;


/** 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();
	//USART_0_initialization();
	/* Create a regular character stream for the interface so that it can be used with the stdio.h functions */
	CDC_Device_CreateStream(&VirtualSerial_CDC_Interface, &USBSerialStream);

	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
	GlobalInterruptEnable();

	
	
	while (true)
	{	
		/* Must throw away unused bytes from the host, or it will lock up while waiting for the device */
		//CDC_Device_ReceiveByte(&VirtualSerial	Serial_SendByte(&USARTC0,0x41);				
		fputs("A",&USBSerialStream);
	    //fputc(0x41,&USARTSerialStream);
		
		USART_0_write(0x45);
		
		CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
		USB_USBTask();
		
		
	}
}

/** Configures the board hardware and chip peripherals for the demo's functionality. */
void SetupHardware(void)
{
	
	
 #if (ARCH == ARCH_AVR8)
	/* Disable watchdog if enabled by bootloader/fuses */
	MCUSR &= ~(1 << WDRF);
	wdt_disable();

	/* Disable clock division */
	clock_prescale_set(clock_div_1);
#elif (ARCH == ARCH_XMEGA)
	/* Start the PLL to multiply the 2MHz RC oscillator to 32MHz and switch the CPU core to run from it */
	XMEGACLK_StartPLL(CLOCK_SRC_INT_RC2MHZ, 2000000, F_CPU);
	XMEGACLK_SetCPUClockSource(CLOCK_SRC_PLL);

	/* Start the 32MHz internal RC oscillator and start the DFLL to increase it to 48MHz using the USB SOF as a reference */
	XMEGACLK_StartInternalOscillator(CLOCK_SRC_INT_RC32MHZ);
	XMEGACLK_StartDFLL(CLOCK_SRC_INT_RC32MHZ, DFLL_REF_INT_USBSOF, F_USB);

	PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_HILVLEN_bm;
#endif

	/* Hardware Initialization */ 
	
	LEDs_Init();
	USB_Init();
	USART_0_initialization();



}



/** Event handler for the library USB Connection event. */
void EVENT_USB_Device_Connect(void)
{
	LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);

}

/** Event handler for the library USB Disconnection event. */
void EVENT_USB_Device_Disconnect(void)
{
	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
}

/** Event handler for the library USB Configuration Changed event. */
void EVENT_USB_Device_ConfigurationChanged(void)
{
	bool ConfigSuccess = true;

	ConfigSuccess &= CDC_Device_ConfigureEndpoints(&VirtualSerial_CDC_Interface);

	LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
}

/** Event handler for the library USB Control Request reception event. */
void EVENT_USB_Device_ControlRequest(void)
{
	CDC_Device_ProcessControlRequest(&VirtualSerial_CDC_Interface);
}

/** CDC class driver callback function the processing of changes to the virtual
 *  control lines sent from the host..
 *
 *  \param[in] CDCInterfaceInfo  Pointer to the CDC class interface configuration structure being referenced
 */
void EVENT_CDC_Device_ControLineStateChanged(USB_ClassInfo_CDC_Device_t *const CDCInterfaceInfo)
{
	/* You can get changes to the virtual CDC lines in this callback; a common
	   use-case is to use the Data Terminal Ready (DTR) flag to enable and
	   disable CDC communications in your application when set to avoid the
	   application blocking while waiting for a host to become ready and read
	   in the pending data from the USB endpoints.
	*/
	bool HostReady = (CDCInterfaceInfo->State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR) != 0;
}

void USART_0_initialization(void)
{

	// Set pin direction to input
	PORTC.DIRCLR = 1 << 2;
	
	PORTC_set_pin_output_pull_mode(2,PORT_CONFIGURATION_TOTEM);

	// Set pin direction to output
	PORTC.DIRSET = 1 << 3;
	PORTC.OUTCLR = 1 << 3;
	

	USART_0_init();
}


#if defined(__GNUC__)

int USART_0_printCHAR(char character, FILE *stream)
{
	USART_0_write(character);
	return 0;
}

FILE USART_0_stream = FDEV_SETUP_STREAM(USART_0_printCHAR, NULL, _FDEV_SETUP_WRITE);

#elif defined(__ICCAVR__)

int putchar(int outChar)
{
	USART_0_write(outChar);
	return outChar;
}
#endif

int8_t USART_0_init()
{

	int8_t   exp;
	uint32_t div;
	uint32_t limit;
	uint32_t ratio;
	uint32_t min_rate;
	uint32_t max_rate;

	uint32_t cpu_hz = 2000000;
	uint32_t baud   = 4800;

	/*
	 * Check if the hardware supports the given baud rate
	 */
	/* 8 = (2^0) * 8 * (2^0) = (2^BSCALE_MIN) * 8 * (BSEL_MIN) */
	max_rate = cpu_hz / 8;
	/* 4194304 = (2^7) * 8 * (2^12) = (2^BSCALE_MAX) * 8 * (BSEL_MAX+1) */
	min_rate = cpu_hz / 4194304;


	min_rate /= 2;

	if ((baud > max_rate) || (baud < min_rate)) {
		
		return -1;
	}


	baud *= 2;


	limit = 0xfffU >> 4;
	ratio = cpu_hz / baud;

	for (exp = -7; exp < 7; exp++) {
		if (ratio < limit) {
			break;
		}

		limit <<= 1;

		if (exp < -3) {
			limit |= 1;
		}
	}


	
	if (exp < 0) {
		cpu_hz -= 8 * baud;
		if (exp <= -3) {
			div = ((cpu_hz << (-exp - 3)) + baud / 2) / baud;
		} else {
			baud <<= exp + 3;
			div = (cpu_hz + baud / 2) / baud;
		}
	} else {

		baud <<= exp + 3;
		div = (cpu_hz + baud / 2) / baud - 1;
	}

	USARTC0.BAUDCTRLB = (uint8_t)(((div >> 8) & 0X0F) | (exp << 4));
	USARTC0.BAUDCTRLA = (uint8_t)div;



	USARTC0.CTRLB = 0 << USART_CLK2X_bp   /* Double transmission speed: disabled */
	                | 0 << USART_MPCM_bp  /* Multi-processor Communication Mode: disabled */
	                | 1 << USART_RXEN_bp  /* Receiver Enable: enabled */
	                | 1 << USART_TXEN_bp; /* Transmitter Enable: enabled */

#if defined(__GNUC__)
	stdout = &USART_0_stream;
#endif

	return 0;
}



/**
 * \brief Enable RX and TX in USART_0
 * 1. If supported by the clock system, enables the clock to the USART
 * 2. Enables the USART module by setting the RX and TX enable-bits in the USART control register
 *
 * \return Nothing
 */
void USART_0_enable()
{
	USARTC0.CTRLB |= USART_RXEN_bm | USART_TXEN_bm;
}

/**
 * \brief Enable RX in USART_0
 * 1. If supported by the clock system, enables the clock to the USART
 * 2. Enables the USART module by setting the RX enable-bit in the USART control register
 *
 * \return Nothing
 */
void USART_0_enable_rx()
{
	USARTC0.CTRLB |= USART_RXEN_bm;
}

/**
 * \brief Enable TX in USART_0
 * 1. If supported by the clock system, enables the clock to the USART
 * 2. Enables the USART module by setting the TX enable-bit in the USART control register
 *
 * \return Nothing
 */
void USART_0_enable_tx()
{
	USARTC0.CTRLB |= USART_TXEN_bm;
}

/**
 * \brief Disable USART_0
 * 1. Disables the USART module by clearing the enable-bit(s) in the USART control register
 * 2. If supported by the clock system, disables the clock to the USART
 *
 * \return Nothing
 */
void USART_0_disable()
{
	USARTC0.CTRLB &= ~(USART_RXEN_bm | USART_TXEN_bm);
}

/**
 * \brief Get recieved data from USART_0
 *
 * \return Data register from USART_0 module
 */
uint8_t USART_0_get_data()
{
	return USARTC0.DATA;
}

/**
 * \brief Check if the usart can accept data to be transmitted
 *
 * \return The status of USART TX data ready check
 * \retval false The USART can not receive data to be transmitted
 * \retval true The USART can receive data to be transmitted
 */
bool USART_0_is_tx_ready()
{
	return (USARTC0.STATUS & USART_DREIF_bm);
}

/**
 * \brief Check if the USART has received data
 *
 * \return The status of USART RX data ready check
 * \retval true The USART has received data
 * \retval false The USART has not received data
 */
bool USART_0_is_rx_ready()
{
	return (USARTC0.STATUS & USART_RXCIF_bm);
}

/**
 * \brief Check if USART_0 data is transmitted
 *
 * \return Receiver ready status
 * \retval true  Data is not completely shifted out of the shift register
 * \retval false Data completely shifted out if the USART shift register
 */
bool USART_0_is_tx_busy()
{
	return (!(USARTC0.STATUS & USART_TXCIF_bm));
}

/**
 * \brief Read one character from USART_0
 *
 * Function will block if a character is not available.
 *
 * \return Data read from the USART_0 module
 */
uint8_t USART_0_read()
{
	while (!(USARTC0.STATUS & USART_RXCIF_bm))
		;
	return USARTC0.DATA;
}

/**
 * \brief Write one character to USART_0
 *
 * Function will block until a character can be accepted.
 *
 * \param[in] data The character to write to the USART
 *
 * \return Nothing
 */
void USART_0_write(const uint8_t data)
{
	while (!(USARTC0.STATUS & USART_DREIF_bm))
		;
	USARTC0.DATA = data;
}


static inline void PORTC_set_pin_output_pull_mode(const uint8_t pin, const enum port_output_pull_mode output_pull_mode)
{
	volatile uint8_t *port_pin_ctrl = (volatile uint8_t *)(&PORTC.PIN0CTRL) + pin;

	*port_pin_ctrl &= PORT_OPC_TOTEM_gc;
	if (output_pull_mode == PORT_CONFIGURATION_BUSKEEPER) {
		*port_pin_ctrl |= PORT_OPC_BUSKEEPER_gc;
		} else if (output_pull_mode == PORT_CONFIGURATION_PULLDOWN) {
		*port_pin_ctrl |= PORT_OPC_PULLDOWN_gc;
		} else if (output_pull_mode == PORT_CONFIGURATION_PULLUP) {
		*port_pin_ctrl |= PORT_OPC_PULLUP_gc;
		} else if (output_pull_mode == PORT_CONFIGURATION_WIREDOR) {
		*port_pin_ctrl |= PORT_OPC_WIREDOR_gc;
		} else if (output_pull_mode == PORT_CONFIGURATION_WIREDAND) {
		*port_pin_ctrl |= PORT_OPC_WIREDAND_gc;
		} else if (output_pull_mode == PORT_CONFIGURATION_WIREDORPULL) {
		*port_pin_ctrl |= PORT_OPC_WIREDORPULL_gc;
		} else if (output_pull_mode == PORT_CONFIGURATION_WIREDANDPULL) {
		*port_pin_ctrl |= PORT_OPC_WIREDANDPULL_gc;
	}
}

Something changes with cpu_hz right? I "just" need to find out the clock that is running the port..