Beginners - Serial Echo (UART)

This forum is about you. Feel free to discuss anything is related to embedded and electronics, your awesome projects, your ideas, your announcements, not necessarily related to ChibiOS but to embedded in general. This forum is NOT for support.
Post Reply
Juzujka
Posts: 3
Joined: Wed Jun 11, 2014 10:24 am

Beginners - Serial Echo (UART)

Post by Juzujka »

Code sample for Serial (UART)
ChibiOS has two UART implementations. Serial is simpler for using in terminal application.
Programm echoes byte to terminal.
Here is example for
  • thread creation
  • waiting for event
  • receiving and transmiting to UART

Changes in halconf.h

Code: Select all

#if !defined(HAL_USE_SERIAL) || defined(__DOXYGEN__)
#define HAL_USE_SERIAL              TRUE
#endif
#if !defined(SERIAL_DEFAULT_BITRATE) || defined(__DOXYGEN__)
#define SERIAL_DEFAULT_BITRATE      115200 // set baudrate here
#endif

Choose USART1 in mcuconf.h

Code: Select all

#define STM32_SERIAL_USE_USART1             TRUE


main.c

Code: Select all

#include <ch.h>
#include <hal.h>
#include <stm32f10x.h>

static WORKING_AREA(waSerEcho, 128);
static msg_t thSerEcho(void *arg)
{
   (void)arg;
   chRegSetThreadName("SerEcho");
   EventListener elSerData;
   flagsmask_t flags;
   chEvtRegisterMask((EventSource *)chnGetEventSource(&SD1), &elSerData, EVENT_MASK(1));

   while (TRUE)
   {
      chEvtWaitOneTimeout(EVENT_MASK(1), MS2ST(10));
      chSysLock();
      flags = chEvtGetAndClearFlags(&elSerData);
      chSysUnlock();
      if (flags & CHN_INPUT_AVAILABLE)
      {
         msg_t charbuf;
         do
         {
            charbuf = chnGetTimeout(&SD1, TIME_IMMEDIATE);
            if ( charbuf != Q_TIMEOUT )
            {
              chSequentialStreamPut(&SD1, charbuf);
            }
         }
         while (charbuf != Q_TIMEOUT);
      }
   }

   return 0;
}
int main(void) {
  halInit();
  chSysInit();

  /*
   * Activates the serial driver 1 using the driver default configuration.
   */
  sdStart(&SD1, NULL);

  chThdCreateStatic(waSerEcho, sizeof(waSerEcho), NORMALPRIO, thSerEcho, NULL);

  while (!chThdShouldTerminate()) {
    chThdSleepMilliseconds(500);
  }
  return 0;
}
User avatar
Giovanni
Site Admin
Posts: 14891
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 996 times

Re: Beginners - Serial Echo (UART)

Post by Giovanni »

Hi,

Thanks for the samples, just a small note, you don't need those lock/unlock around chEvtGetAndClearFlags() because it is not an I-class function, those are harmless but the state checker would complain.

I recommend to enable the state checker in chconf.h while developing code (and, in general, all the other debug support options).

Giovanni
Post Reply