cancel
Showing results for 
Search instead for 
Did you mean: 

How to use program outside the main while function

arduo
Senior

Hi there,

I am transmitting and receiving data via uart like an pl2303 bridge via USB FS. How can i manage the transmitting and receiving process outside the while so that i not block the mcu?

int main(void)
{
  USB_CDC_STATUS_t check_usb;
  uint16_t rx_usb;
  uint16_t rx_uart;
 
  char string_buf[RX_BUF_SIZE];
 
  SystemInit(); // Quarz Einstellungen aktivieren
 
  // init vom CDC
  UB_USB_CDC_Init();
 
  // init vom UART
  UB_Uart_Init();
 
  while(1)
  {
	  // test ob USB mit PC verbunden ist
	  check_usb=UB_USB_CDC_GetStatus();
	  if(check_usb==USB_CDC_CONNECTED) {
		  // USB -> UART
		  rx_usb=UB_USB_CDC_ReceiveData(string_buf);
		  if(rx_usb>0) {
			  // wenn Daten per USB empfangen wurden
			  // -> alle Daten per UART senden
			  UB_Uart_SendData(COM3,string_buf,rx_usb);
		  }
 
		  // UART -> USB
		  rx_uart=UB_Uart_ReceiveData(COM3,string_buf);
		  if(rx_uart>0) {
			  // wenn Daten per UART empfangen wurden
			  // -> alle Daten per USB senden
			  UB_USB_CDC_SendData(string_buf,rx_uart);
		  }
	  }
  }
}

2 REPLIES 2
Vprabhu
Associate II

you can use some timer for x sec of time and you can have these code in the timer Interrupt service handler so that for every x time elapses the code executes.

Piranha
Chief II

Your current approach is called super-loop:

https://en.wikibooks.org/wiki/Embedded_Systems/Super_Loop_Architecture

It's the same used in Arduino and is the worst possible "architecture".

Better and still simple approach is to use cooperative scheduler. You can make periodic task scheduling:

https://www.edn.com/electronics-blogs/embedded-basics/4434440/7-Steps-to-Writing-a-Simple-Cooperative-Scheduler

But even better is event based scheduling described here:

https://embeddedgurus.com/state-space/2012/05/superloop-vs-event-driven-framework/

You can build cooperative schedulers with either or even both of these principles.

The most advanced level is using RTOS. It has real-time and other capabilities, but also requires understanding of multi-threaded programming, which is not trivial.

For beginners and also for experts with small-medium sized projects often some type of cooperative scheduler is the best choice.