Page 1 of 1

Beginners - Serial Echo (UART)

Posted: Wed Jun 11, 2014 11:17 am
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;
}

Re: Beginners - Serial Echo (UART)

Posted: Mon Jun 16, 2014 8:05 am
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