Library 04- USART for STM32F4

USARTA lot of times when you work on some project, you want to display data on computer. This can be done with USART peripheral on MCU. With USART you can connect more than just computer, you can connect with GSM modules, GPRS, bluetooth and so much more. Our discovery board supports up to 8 USART channels. In this tutorial we will use USART1 to show principle how to use USART in our project. But first, we have to initialize our pins and peripheral.

Pins pack 1 Pins pack 2 Pins pack 3
U(S)ARTx TX RX TX RX TX RX APB
USART1 PA9 PA10 PB6 PB7 2
USART2 PA2 PA3 PD5 PD6 1
USART3 PB10 PB11 PC10 PC11 PD8 PD9 1
UART4 PA0 PA1 PC10 PC11 1
UART5 PC12 PD2 1
USART6 PC6 PC7 PG14 PG9 2
UART7 PE8 PE7 PF7 PF6 1
UART8 PE1 PE0 1

USART1 uses pins

  • PA9 for transmitting data
  • PA10 for receiving data

so they must have enabled clock, set for alternating function and set them this alternating function.

Then, when you initialized pins, we have to initialize USART peripheral too

Because our USART uses interrupt for incoming data, we have to initialize NVIC (Nested Vector Interrupt Controller). Everytime when data will come, our main program will stop executing and our interrupt routine will jump in.

Library

Features

  • Operate with up to 8 U(S)ARTs in UART mode
  • Selectable pins for USART
  • Receive interrupt handler

Dependencies

  • CMSIS
    • STM32F4xx
    • STM32F4xx RCC
    • STM32F4xx GPIO
    • STM32F4xx USART
  • TM
    • defines.h
    • attributes.h
    • TM GPIO

Functions and enumerations

Hardware

Your computer probably has not RS232 connector, but it has USB for sure. You need USB to serial converter. I prefer FTDI which is very stable and support 3V3 levels. You can buy converter on ebay for about 5$. Connect converter’s TX with board’s RX and converter’s RX with board’s TX. To display data, you need some terminal, I use one from Bray. Open program and set:

  • Select your COM port
  • baudrate to 9600
  • Data bits to 8
  • Parity to none
  • Stop bits to 1

Example

Project available on Github, download library below.

Icon
TM STM32F4 USART Library

USART library for all USART peripherals

tilz0R

Owner of this site. Also electronic enthusiasts, web developer, 3D printer fan, handball player and more. Big fan of STM32F4 devices. In anticipation of the new Discovery board for STM32F7 lines.

You may also like...

Read before commenting!

Before you make a new comment, make sure you agree with things listed below:

  • - Read post to make sure if it is already posted what you are asking for,
  • - Make sure you have the latest version of libraries used in your project,
  • - Make a clean and grammatically correct written message,
  • - Report as many details as possible, including what have you done so far,
  • - Do NOT post any code here. Use Pastebin,
  • - Do NOT post any error codes here. Use Pastebin,
  • - Specify STM32Fxxx family and used Discovery/EVAL/Nucleo or custom made board,
  • - Make sure your clock is set correct for PLL,
  • - If you are using my HAL drivers, please check this post how to start.
Comment will be deleted on breaking these rules without notification!
  • Mahendar

    Simple tutorials, easily get things around stm32f4. great thanks to you…..:)

    • tilz0R

      Thank you, I appreciate that! 😉

  • Aaron

    The line:
    GPIO_InitTypeDef GPIO_InitStruct;

    should be:
    GPIO_InitTypeDef GPIO_InitStructure;

    • I don’t see a reason for that, it is just variable name, it can be whatever!

  • Where I can find your libraries:

    #include “tm_stm32f4_usart.h”

    etc…

    Eldad

    • If you read content you will notice that every library has link to my Github account.

      • zoli emqua

        @tilz0R help me

  • zoli emqua

    fail?

  • zoli emqua

    fail? help me

  • محــمد مهــدی سلطانی

    Dear Tilen
    How we can use the internal interrupt of USART?

    • Library already uses receive interrupt for usart. Data from usart is stored into cyclic buffer in library.

      • محــمد مهــدی سلطانی

        I know that the library is using it…
        but the problem starts when I need to do something else when there is an interrupt on the USART…

        • Explain the problem.
          Interrupts are set like normal, added to nvic, set priority amd receive interrupt enabled.

          • محــمد مهــدی سلطانی

            You mean that I do what ever I want at your library and change what will go on when the interrupt is coming?

          • I dont know what is problem with your hardware. You said that something breaks when usart interrupt happen.

          • محــمد مهــدی سلطانی

            No!
            I need to do something when the USART interrupt comes but I thing when I edit the USART1_IRQ every thing goes wrong…
            How do I edit that interrupt whitout any distrucyion in the library?

          • محــمد مهــدی سلطانی

            Thanks, it was so useful…

  • bobby

    .hello_world.axf: Error: L6218E: Undefined symbol NVIC_Init (referred from tm_stm32f4_usart.o).

  • bobby

    I compile it and find such error. Why?

  • bobby

    I modify it based on hello_word project.

  • bobby

    Need I configurate anything in “run-time environment”?

    • misc.c/h is missing in your project.
      This file is included in standard peripheral library from ST.

  • arkogol arkogo

    Hi,
    What I should define i defines.h so I can fireup your libraries and send string via usart? Right now I get some unrecognized signs.

    • Just check if your terminal matches baudrate.
      Also verify your clock on mcu

  • arkogol arkogo

    I checked baudrate and is correct.
    Can you create project in CooCox for stm32f4 discovery and send to my email. I spend hole day trying to fireup usart on stm32f4 but I failed.

    • No, I’m not that kind.
      However, I can take a look at your project, if you send me to my mail, or share it public.

  • bobby

    Thank you. Realy misc.c/h is missing in my project.

  • stracho

    Hello, is avaible on STM to set :
    Baud: 19200
    Data bit: 7
    Stop Bit: 2
    Parity: Even

    It should be work when I set USART_WordLength_8b but it doesn’t 🙁

    • 8 or 9 data bits is possible only.
      Other settings can be like you specify.

      • stracho

        Thanks for the reply, But when I try to do this with your Library it ‘s work fine with

        #ifndef TM_USART1_HARDWARE_FLOW_CONTROL

        #define TM_USART1_HARDWARE_FLOW_CONTROL USART_HardwareFlowControl_None

        #endif

        #ifndef TM_USART1_MODE

        #define TM_USART1_MODE USART_Mode_Tx | USART_Mode_Rx

        #endif

        #ifndef TM_USART1_PARITY

        #define TM_USART1_PARITY USART_Parity_Even

        #endif

        #ifndef TM_USART1_STOP_BITS

        #define TM_USART1_STOP_BITS USART_StopBits_2

        #endif

        #ifndef TM_USART1_WORD_LENGTH

        #define TM_USART1_WORD_LENGTH USART_WordLength_8b

  • Nikolaj

    Thank you Tilen,
    It’s a very usefull example. I was struggling a bit with strange UART data, until I changed to pin-pack 2. Everything is smooth, and your TM libraries are easy to use and work well.

    • Hi,

      Thanks for that.
      If you are using F4-Discovery, then you can’t use PA9/PA10 combination for USART.
      This board has capacitor for USB there.

      Maybe, it will work with 300baud or less, but for sure not with 115200.

      • Sean

        Can you please advice on what i’m doing wrong here. Im trying to pint characters on realterm using usart. I have written functions here to initiaise my desired usart gpio and initialise gpio heere using :

        #include “stm32f4xx.h”

        #include “stm32f4xx_hal.h”

        #include “stm32f4xx_hal_usart.h”

        //Configuring the initial setup for usart

        void usart3_gpio_init (void)

        {

        GPIO_InitTypeDef GPIO_InitStruct;

        __GPIOD_CLK_ENABLE(); //enabling the clocks on GPIOD Calling that function that comes from “stm32f4xx_hal_rcc.h”

        //Configure the Pin: PD8 UASRT3 TX “PD9” USART3 RX

        GPIO_InitStruct.Pin = GPIO_PIN_6 | GPIO_PIN_7;

        GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;

        GPIO_InitStruct.Speed = GPIO_SPEED_FAST;

        HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);

        }

        void usart_init (void)

        {

        USART_InitTypeDef USART_InitStruct;

        USART_HandleTypeDef USART_Init;

        __USART3_CLK_ENABLE(); //Enabling the clock for USART 3

        USART_InitStruct.BaudRate= 9600;

        USART_InitStruct.WordLength= USART_WORDLENGTH_8B;

        USART_InitStruct.Mode = USART_MODE_TX_RX;

        USART_InitStruct.Parity=USART_PARITY_NONE;

        USART_InitStruct.StopBits= USART_STOPBITS_1;

        USART_Init.Init = USART_InitStruct;

        HAL_USART_Init (&USART_Init); //This function wants a pointer to the address of the USART_HandleTypeDef variable which is USART_Init

        }

        then my main code is :

        #include “stm32f4xx.h”

        #include “stm32f4xx_hal.h”

        #include “stm32f4xx_hal_usart.h”

        #include “usart_init_h.h”

        int main()

        {

        usart3_gpio_init();

        usart_init();

        uint8_t tx_data = ‘p’;

        usart3_gpio_init();

        usart_init();

        //HAL_USART_Transmit(USART_Init, &tx_data, 8, 0);

        }

        I am using hal drivers. and my c isnt that great. can anyone help?

        • Sean

          has anyone implement usart prinitng using the HAL at all? 🙁 🙁

          • I’m not using HAL drivers (for now) so I can’t really help you here right now

  • Sean

    Hi tilen, Ive been trying to implement this on my STM32f429. However I have the new HAL drivers.

    Could you be of help at all? My C is very intermediate. I’m just trying to get into embedded systems. Are you going to be updating your codes for this at any points.

    I also see that some people are printing text to the screen? Is there a link on how this was implemented at all?

    • Hi,

      if you are using HAL drivers, then you don’t need my library, because everything is performed and done there.
      Search for ILI9341 library on this site.

  • abdurrahman korkmaz

    .Objectsusart1.axf: Error: L6218E: Undefined symbol TM_DELAY_Init (referred from usartx.o).

    .Objectsusart1.axf: Error: L6218E: Undefined symbol TM_USART_Getc (referred from usartx.o).

    .Objectsusart1.axf: Error: L6218E: Undefined symbol TM_USART_Init (referred from usartx.o).

    .Objectsusart1.axf: Error: L6218E: Undefined symbol TM_USART_Putc (referred from usartx.o).

    .Objectsusart1.axf: Error: L6218E: Undefined symbol TM_USART_Puts (referred from usartx.o).

    • You’ve made some filename changes, so I can’t help you here.

  • abdurrahman korkmaz

    help me please

    .Objectsusart1.axf: Error: L6218E: Undefined symbol TM_DELAY_Init (referred from usartx.o).

    .Objectsusart1.axf: Error: L6218E: Undefined symbol TM_USART_Getc (referred from usartx.o).

    .Objectsusart1.axf: Error: L6218E: Undefined symbol TM_USART_Init (referred from usartx.o).

    .Objectsusart1.axf: Error: L6218E: Undefined symbol TM_USART_Putc (referred from usartx.o).

    .Objectsusart1.axf: Error: L6218E: Undefined symbol TM_USART_Puts (referred from usartx.o).

    this errors are given all project example.
    how can we solve?
    please help

    • Again, you’ve made filename changes.
      I can’t help you here!

  • iMattmax

    is it possible to have 8 USART an two I2C at the same time?

    • If you have pins available for both, then yes.

      • iMattmax

        what does it mean

        • You really need all these specs?
          If you dont know what it means then im not sure if you need it.

          Well, each peripheral like usart and i2c need external pins for the output to the world 😉

          • iMattmax

            Okay, I’m looking for an option to reralize a copter controll board with an F4Discovery. So, there is a need for 8 pwm inputs, 8 pwm output, USART as much as posible and the same with I2C.

          • Everything can be realized.
            But why 8USARTs for copter?

            For GPS you need on, next?

          • iMattmax

            telemetrie, bluetooth, led-strip

          • Huh, ok. Why you need then pwm input? Arent pwm input for telemetry?
            Bluetooth is usart, but led strip?

          • iMattmax

            so I mean 8 control inputs and 8 outputs for the motors. than GPS, bluetooth, telemetry, external GY-86, and led-strip (WS5812)

          • With f427/429/437/439 you can have 8 usarts.
            Lib supports them all. Also for 3i2c channels you can use the same chips. For develop use f429disco

          • iMattmax

            okay, do you know how to configurated the rcinputs and the output? on which timer etc.?

          • You are developer now.
            You can look at my pwm library or tutorial how to make outputs.

          • iMattmax

            do I need the programm MicroXplorer?

          • I dont know.

          • iMattmax

            it’s a tool from stm

          • Never tried for now.

          • iMattmax

            If I have a stm32f4discovery.h file with all my avaible pin’s, what else do I need to buil up an stm32f4 bootloader file. Or in other words, with other file do I have to change so that all the settings (USART, I2C, PWM) are correct?

          • Contact me via email, with CLEAR things you wanna do.
            I have no idea what is your point here.

  • Glen

    Hi Majerle thanks for the great libraries and tutorials. Has allowed me to progress rapidly. I am wanting to debug my code by sending a integer (uint8_t in this case). I cannot find a way to convert uint8_t to char[]. I am using GCC compiler.

    How can I convert this to a char array to send with TM_USART_Puts()?

      • Glen

        Thanks for the quick reply and suggestions. I wasn’t able to get sprintf to compile but your method does compile but not displaying what I expect.

        Option seems good but I am only getting blank spaces come through the USART. Can I use TM_USART_Putc and TM_USART_Puts in the same program?

        uint8_t data[] = {0, 1, 2, 4, 5, 6, 7, 8, 9};
        uint8_t i;

        /* Option one, use put character function */
        for (i = 0; i < 8; i++) {
        /* Send via Put character function */
        TM_USART_Putc(USART6, (char)data[i]);
        }

        • I see the problem here. send data like this:

          TM_USART_Putc(USART6, (char)(data[i] + 48));

          48 is zero in char, so you will see on your USART terminal “0123456789”.

          • Glen

            That was it thanks! I assumed it was doing a int to char conversion but it was only a type change.

            Now problem is need more maths to display > 9.

            Is there a simpler way to do what I want. I’m trying to write to USART the results from a TM_I2C_Read() for debugging purposes.

          • Make a function which will do that for you.
            This is tle simoles way for you.
            Inside this func use for loop like above.

  • oattao

    Dear Majerle Tilen,
    I used your USART library on my STM32F429 Discovery board, but when I send text from the board to PC, I received the wrong letter. I’m sure that the PC and the board have same baud rate. I think the HSE on the board have problem.
    Can you show me how to use the HSI on the board? Thank you very much.

  • oattao

    Dear Majerle Tilen,

    In the picture I attached here, I saw that on board, SB18 and SB20 are good, but SB19 is not connected. Is there any problem with that? Maybe it make the HSE work not well?

    • Which board is that?
      Is Nucleo?
      On STM32F429-DIscovery HSE should be used.
      Try to remove SB18 and add SB19 but it should work without modification.

      • oattao

        My board is STM32F429-Discovery. I removed SB18, added SB19 but I still got wrong letter from the board.
        Can you show me a way to disable HSE and use HSI on the board?

        • Just don’t enable HSE oscillator.
          It is disabled by default.

          Download clock tool from ST and set there options.
          I’m sure you have some other problems, not with crystal.

          • matus

            I have same problem, I tried the same, example, that you , but still, is something wrong, and I have no Idea what ist the problem, my bord is STM32F429-discovery , core stm32f429zi

          • Clock is not OK for sure.
            Nothing else, you failed somewhere.

            Send me project to my mail for check.

          • matus

            http://uloz.to/xNFejRxY/00-pr6-3-rar

            here is the projekt file

          • Open “Options for Target” and under C/C++ tab add define:
            HSE_VALUE=8000000

          • matus

            it ist there, when you open my projekt, is’n it there ?

          • matus

            USE_STDPERIPH_DRIVER,STM32F4XX,KEIL_IDE,STM32F429_439xx,
            HSE_VALUE=8000000
            , I am using all this and PLL_M=8, PLL_Q=7, PLL_N=336, PLL_P=2

            IT ist possible tha is wrong something other else ?

  • Cahya

    Hi Majerle,

    I tried to use your usart library on an application which uses old standard peripheral driver (version V1.0.2). I configured it to use the baudrate of 115200, but I see only funny character as output. But after I changed the baudrate on client side (I use minicom) to 38400 (the usart library is still set to 115200), the output is working properly. What do you think the reason of this baudrate issue?

    This is the application that I want to add usart functionality: http://vedder.se/2012/12/stm32f4-discovery-usb-host-and-mp3-player/

    Thanks.

    • Hi,

      if you are using STD periph drivers in keil uvision (1.0.2 packs), you have probably set them like your board has 25MHz crystal, but it has 8MHz and your device is about 3 (25/8) times slower.

      115200 / 38400 is 3.
      Change files:
      stm32f4xx.h: HSE_VALUE define set to 8000000
      system_stm32f4xx.c: PLL_M set from 25 to 8

      Try and report.

      • Cahya

        Thanks for the hint. Actually the HSE_VALUE has been set to 8M already in stm32f4xx_conf.h, but it seems your code read it from stm32f4xx.h. After I changed it also in stm32f4xx.h, everything is working properly again. Thanks again.

        • HSE_VALUE is used from stm32f4xx.h by standard peripheral drivers not by my libs.
          Nice to hear that 🙂

  • Jasur

    Hi Tilen,

    Thank you for your time and efforts to bring us this kind of awesome tutorials.

    I’m a beginner and I have some problems running this tutorial. I have stm32f407VG Discovery board. I have downloaded the libraries and copy-paste the code. It compiles well, but after downloading it to the board, I cannot transmit or receive data.

    Then I included the DISCO library to turn on LED after each line. After “TM_USART_Puts” line it does not goes to next line. I removed this line and tried “c = TM_USART_Getc(USART1);” line, and this one also gives 0 all the time, IF statement is not working after it.

    Could you please give any idea what might be wrong?

    p.s. I have shorted my TX and RX pins on my serial cable and it echoes back what I transmit. I’m using FTDI 3.3 USB to serial cable. I connect only GND, TX, RX pins to the board.

    • Hi,

      if you are trying to use PA9/PA10 combination for USART1, then it will not work, because discovery board has low-pass filter connected there for USB purpose.

      Right now I don’t know what can be wrong, but if you send me project I can take a look.
      Maybe is just problem in clock settings.

      If you want, send project to my email address.

  • matus

    Hi Tilen, please I have one question, I am yousing your driver exactly, a a did everything like I saw in your tutorials, but I have still same bugs.

    in Keil , i use this defines USE_STDPERIPH_DRIVER,STM32F4XX,KEIL_IDE,STM32F429_439xx,
    TM_DISCO_STM32F4_DISCOVERY,HSE_VALUE=8000000

    • Which pins you use for USART?
      PA9/PA10 does not work on STM32F4-Discovery.

      Second thing, how you have set PLL_M? It has to be set to 8, in system_stm32f4xx.c.

      • matus

        i am using PB6 and PB7, and like you can see, on the other picture, PLL_M is set to 8, can by possible that is wrong something else ?

        • Send me project to my mail for testing.
          Or try to manually set HSE_VALUE to 8000000 in stm32f4xx.h file.

          • matus

            i send it, and I also tried other usart and other pin, but it is still same

          • matus

            HI I couldnt send it by mail, but it ist there http://uloz.to/xej1kjpk/00-pr6-3-rar

          • Jasur

            Hi matus,
            I have the similar problem, let me know if you solve the problem, thnx

          • matus

            I did not solve problem, now I am using Vistual Com Port., and this work corectly, so I think that problem is no in clock setting,

          • I have no idea how your hardware looks like.

          • matus

            STM32F429 discovery ,

  • Khoa Tran

    How to use uint16_t TM_USART_Gets(USART_TypeDef* USARTx, char* buffer, uint16_t bufsize)
    I’m can send data from Discovery to PC and receive a char by using uint8_t TM_USART_Getc(USART_TypeDef* USARTx) but I can’t use TM_USART_Gets to receive a string.
    Help me please.
    Thank you.
    Khoa Tran.

    • Gets aka get string from usart buffer.
      My lib has internal buffer where incoming data is stored. If you call gets function, then this function will return data from this buffer,but only in case that string separator n is in buffer or buffer is full.

      When you send stribg from computer, add n at the end and try this function.

      • Khoa Tran

        Thank you.

  • abdurrahman korkmaz

    please help,,
    my usart dont work.
    why?
    code is below
    thanks
    //—————————–

    SystemInit();

    /* Initialize USART1 at 9600 baud, TX: PB6, RX: PB7 */

    TM_USART_Init(USART1, TM_USART_PinsPack_1, 9600);

    /* Put string to USART */

    TM_USART_Puts(USART1, “Hello worldnr”);

    USART_SendData(USART1, 0x0D);

    while (1) {

    TM_USART_Puts(USART1, “Hello worldnr”);

    USART_SendData(USART1, 0x0D);

    }

    • You are using stm32f4-discovery board and there PA9/PA10 pins don’t work

  • Gustavo Sousa

    Hello,

    First, thank you a lot for all your help and work.

    I could open, setup and run your project without problem in my stm32f4-discovery. But, I try use your lib in other project and have some problems.

    I can build all the project with no error, but looking for the reason, I find some thing, when I click with the right button on TM_USART1_InitPins function and select “go to Definition of…” the error appear.

    this function is called by the usart initialize.

    do you have any idea?

    • Because this is disabled in my projects.

      http://screencloud.net/v/rWg1

      “Browse information” must be activated. Then rebuild.

      • Gustavo Sousa

        Thanks Majerle for fast awser.

        So, I already checked this before. In other function the browser information is working, but in that specific funtion not.

        And its fun, ’cause the prototype and the defition is in the same file. So, the problem with linker was not to happen.

  • Janitha Ananda Thalagoda

    // Device header

    #include “stm32f4xx.h”

    #include “stm32f4xx_rcc.h”

    #include “stm32f4xx_gpio.h”

    #include “stm32f4xx_tim.h”

    #include

    #include

    #include

    #include “math.h”

    #include /* for printf */

    #include

    int rxup=0;

    char rxmsg[100];

    void USART6Init(void)

    {

    USART_InitTypeDef USART_InitStructure;

    // RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);

    USART_InitStructure.USART_BaudRate = 115200;

    USART_InitStructure.USART_WordLength = USART_WordLength_8b;

    USART_InitStructure.USART_StopBits = USART_StopBits_1;

    USART_InitStructure.USART_Parity = USART_Parity_No;

    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;

    USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;

    /* Configure USART1 */

    USART_Init(USART6, &USART_InitStructure);

    /* Enable the USART1 */

    USART_ITConfig(USART6,USART_IT_TXE,DISABLE);

    USART_ITConfig(USART6,USART_IT_RXNE,ENABLE);

    USART_Cmd(USART6, ENABLE);

    }

    void NVIC_setup(){

    NVIC_InitTypeDef NVIC_InitStructure;

    /* Configure one bit for preemption priority */

    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);

    NVIC_InitStructure.NVIC_IRQChannel = USART6_IRQn;

    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;

    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;

    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;

    NVIC_Init(&NVIC_InitStructure);

    }

    void SendStringUSART6(volatile char *s)

    {

    while(*s){

    // wait until data register is empty

    while( !(USART6->SR & 0x00000040) );

    USART_SendData(USART6, *s);

    *s++;

    }

    }

    void USART1_IRQHandler(void){

    // check if the USART1 receive interrupt flag was set

    if( USART_GetITStatus(USART6, USART_IT_RXNE) ){

    static uint8_t cnt = 0; // this counter is used to determine the string length

    char t = USART6->DR; // the character from the USART1 data register is saved in t

    if( (t != ‘n’) && (cnt < 100) ){

    rxmsg[cnt] = t;

    cnt++;

    }

    else{ // otherwise reset the character counter and print the received string

    cnt = 0;

    rxup=1;

    //SendStringUSART1(received_string);

    //USART_puts(USART1, "n");

    //memset(received_string, 0, MAX_STRLEN+1);

    }

    }

    }

    void TM_LEDS_Init(void) {

    GPIO_InitTypeDef GPIO_InitStruct;

    /* Clock for GPIOD */

    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD|RCC_AHB1Periph_GPIOB|RCC_AHB1Periph_GPIOA|RCC_AHB1Periph_GPIOC, ENABLE);

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART6,ENABLE);

    //RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);

    GPIO_PinAFConfig(GPIOC, GPIO_PinSource6, GPIO_AF_USART6);

    GPIO_PinAFConfig(GPIOC, GPIO_PinSource7, GPIO_AF_USART6);

    // Initialize pins as alternating function

    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_7;

    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;

    GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;//GPIO_OType_OD;

    GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;//GPIO_PuPd_UP;

    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_100MHz;

    GPIO_Init(GPIOC, &GPIO_InitStruct);

    }

    int main(void) {

    /* Initialize system */

    SystemInit();

    /* Init leds */

    NVIC_setup();

    TM_LEDS_Init();

    USART6Init();

    NVIC_setup();

    while (1) {

    if(rxup==1){

    i=0;

    SendStringUSART6(rxmsg);

    rxup=0;

    }

    }

    pl help me to find error prone line this code does not work

    • you have function USART1_IRQHandler, but you initialized USART6.

      Well, this code is really bad written.

  • Tomáš Stejskal

    Hi Tilen,

    I have a problem with the library, on my board STM32F407 (MCU STM32F407VGT6) does not work. I’ve set HSE_VALUE to 8000000, and PLL_M to 8 and still does not work.

    Here is my project:

    https://www.dropbox.com/s/klz4u29m8vtcscp/usart.zip?dl=0

    Could you please have a look at it?

    • Check for PLL_M setting, also read my post about proper clock.

  • Onur Akgün

    Hi Majerle,

    That’s a great work, thank you. I have a problem with getting data accurately.
    I’m using Tera Term and trying to get data which I send from STM32F4 but meaningless characters appear. Do you think why does it happen?
    Baud rate,data,parity,stop,flow control settings are same and connections are true

    Thank you

    PS: I try to get MPU6050 data and I set the baud rate 9600 on both side. Does this cause the problem?

    • Clock is not set correct in your STM32F4xx.
      HSE_VALUE = 8000000
      PLL_M = 8

      Search for these defines.

  • Peter Mather

    Hi Majerle

    Thanks for the great libraries. I’m porting Geoff Graham’s Micromite Basic Interpreter from PIC32 to the STM and using your libraries is making getting the peripheral hardware working very much easier than using the STM base libraries.

    One quick question. I assume the pinspack concept is used to ensure a self-consistent set of pin selections? Is this something which must be maintained between libraries? So can I use pinspack2 for USARTs and pinspack1 for SPI or must they be the same?

    Based on a quick scan I can’t see any similar concept in the STM32F4xx reference manual or am I missing something?

    Thanks

    Peter

    • Hi,

      yes, of course you can use different for different peripheral. As you can see, you have TM_USART_PinsPack.. and TM_SPI_PinsPack.. . This is just a way how to quickly init pins for peripheral without too much work 🙂

      You can also use PP1 for USART1 and simultaneously PP2 for USART2 for example.

  • Mengu Ucok

    Hi Majerle,

    Which pins are used for flow control RTS/CTS ? Is UART flow control with stm32f4 reliable ?
    I need flow control to communicate with GSM Click board.

    • Hi,

      yes, you can use flow control on all USART (not UART) peripherals.
      My library does not support this signals. At least, pins are not declared for this.

      To get pins for you MCU, you will need to check it’s manual.
      For example, USART1 has RTS/CTS pins on PA11 and PA12.

      • Mengu Ucok

        Thanks,

        If it’s possible with the hardware I’ll implement the feature someway.

        • Yes, it is possible without any problems.
          I’ve tried this already and works great. But it is not common setting so I didn’t implement this.

  • Ronak Patel

    Hello again Majerle,
    I’m having trouble in sending a floating point number using USART. Can you explain how I may do this?

    float angle = 0;
    That’s my floating point. I do some calculation to change it but I”m having difficulties sending it through USART.

    • Use sprintf() function to convert to string first, then send.

      • Ronak Patel

        I did this
        char str[120];
        sprintf(str,angle);
        It still has an error.

        • If you use google, believe me, you will find solution for sprintf function

          sprintf(str, “%f”, angle);

          • Ronak Patel

            Thank you, I forgot the %f.

  • Vimukthi Pathirana

    i’m trying to print values of an external pulse in USART. always get the value zero. please help.

    int main()
    {
    char str[120];
    float x_dot;

    SystemInit();

    TM_DELAY_Init();

    TM_USART_Init(USART1, TM_USART_PinsPack_2, 9600);

    while(1){

    if (TM_DELAY_Time() >= 500) {

    TM_DELAY_SetTime(0);

    x_dot = TIM_GetCounter(TIM3);

    sprintf(str, “x_dot- %frn”, x_dot);

    TM_USART_Puts(USART1, str);
    }
    }
    }

    • Nice, really nice.
      Who will initialize timer?

      • Vimukthi Pathirana

        yes. sorry. after initializing it gives values. but values does not make any sense. gives crazy values. sorry i’m new at this.
        thank you for replying.

        • I don’t know what you want here now.
          Init timer with proper prescaler/period, make sure STM clock is correct set (PLL) and that’s all.

  • Victor

    Hello,

    I’m working with the STM32F407VG Discovery board.

    I’ve read and gone through the 01, 02, and 03 tutorials. All is working well there.

    Unfortunately, with this tutorial (running the example code provided), the board hangs on the command: “TM_USART_Puts”. More specifically the line “USART_WAIT” within the function. As a result the code won’t get to the main loop.

    I am using USART3 with PinPack3 (PD8 and PD9). The code is your example code modified accordingly to change USART1 to USART3 and PinsPack2 to PinsPack3.

    I have read your post about timing and I can assure you I have the values setup correctly. I have however been using the same project for tutorials 01, 02, and 03; replacing the main.c file with each example. Not sure if this would cause the problem.

    Any suggestions?

    • Hello Victor,

      that sounds like a strange problem.
      Please, make sure that you use USART3 in TM_USART_Puts() function too.
      USART_WAIT function waits till USART ends with sending.

      The clock is not a problem here because sending does not even stop.

      So try these:
      – Use another pinspack for testing if there works,
      – Make sure you have everywhere replace USART1 with USART3.

      Report if it worked.

      • Victor

        Thanks for the quick reply.

        I’ve replaced everywhere in main.c the USART1 with USART3 and I’ve tried PinsPack1, 2, and 3.

        I’ve also tried using UART2 PinsPack1 to use PA2 and PA3.

        In all cases the code hangs at the same spot.

        Please note that I am using CoIDE v1.7.8 with the v4.9 2015q1 gcc compiler (if this makes a difference or could be the source of the problem).

        • I have Coocox installed.
          If this is not a big secret code, you can send it to my address and I will take a look for you.

          • Victor

            Sent to your e-mail. Hopefully we can figure this out.

          • András Varga

            Hello,

            I has the same problam as Victor.
            Could you please share, how you solve the problame?

            A lot of thanks

    • Arun M

      hej,i am also working on STM32F407VG Discovery board. i would like to disscuss some topics related to the board, can i have ur mail id ….thank you

      • Hi,

        Use contact form or look at example header for address.

  • Pete

    Hi Mr Tilen,

    I am using your usart library to receive a usart signal from a maxsonar HRLV EZ2 sensor. the sensor outputs the following info. ; “RXXXXr” where XXXX is the distance in mm.

    with your ‘gets’ function; TM_USART_Gets(USART1, &string, 6); (where ‘string’ is defined as: char string;)

    I only get a single char (ie R or 7 or 5 etc.) being produced in ‘string’ at a time, not a string or array.

    Any help would be much appreciated as I have been spending many hours without getting anywhere.

    Thanks ,Pete

    • Of course.
      String by default ends with “n” character.
      Your sensor does not output this character as I see and then your string does not end ever.

      • Pete

        Thanks for your quick response Mr Tilen!
        I have tried changing the function so that it stops the string when ‘r’ is received but then it outputs nothing. nice to know where the problem stems from now though! will focus more on this area now.
        Thanks for your help, Pete

  • Onur Akgün

    Hi Majerle,

    Is there any way to realize whether new data came? I used “TM_USART_BufferFull” function but it didn’t work

    • Using a liiitle bit of logic, you should know, that BufferFull means “When buffer is full”. If you need to know if any data is available, use “BufferEmpty” function. If function returns 0, then you have data available for read using Gets or Getc functions.

  • ryan

    Hi Majerle, I’m noticing some odd behavior when I sample my autopilot board via TTL using USART. I have noticed that in order to continue to receive “good” values from your Getc() function, I have to also call Putc() before calling Getc() again. i.e. I’m calling Getc() calling Putc() and then looping back to the beginning. If I do it like this, I get good values from the Getc() function. If I remove the Putc() function (even though I don’t even have a TX wire connected), Getc() returns zeroes instead of good values. This doesn’t make any sense to me…have you experienced this before?

    • This for sure can’t be true.
      Make sure that you don’t do long time operations in your interrupt handlers.

      • ryan

        So I didn’t redefine my own interrupt for receiving a byte, I’m just using the default one in your library. Do you mean, make sure the code I’m executing after the Getc() call before recalling Getc() isn’t too time consuming?

        • ryan

          Also, The TTL device I am receiving from is a 5V line. This should be fine for the USART receiving pins right? I’m not sure what’s going on. I get good changing values for the first 10 reads and then it only returns the value 85 which is “U” in ASCII or 01010101 in binary. Think this could be due to a grounding problem where I’m receiving false triggers or something? I appreciate how helpful you are.

          • Did you check if you read with getc too fast? Characters needs to come over usart.

          • ryan

            Majerle, I did some more investigating and I’m starting to wonder if my micro can’t keep up with the 115200 baud rate of the autopilot. I’ve attached a screen shot from a logic analyzer that was probed on the RX line from the AP and the TX line of the micro. My code would call Getc() and if it received a byte would then Putc(). I used the logic analyzer on the RX and TX lines and as you can see, there’s a missed (missinterpreted) byte on the TX line that doesn’t match the autopilot RX byte. Do you think 115200 is too high of a baud rate?

          • ryan

            Sorry, attached wrong photo initially.

          • Looking at this pic. What is not ok here?
            TX and RX are asynchronous signals.

            I’m using 1.5Mbaud without any problem.

          • ryan

            What’s not ok here? The micro receives the right bits up until the point where I drew the arrow. At this point, the autopilot sent a bit, but the micro received it as two bits indicated by the thicker wave in the bottom graph. Right?

          • Ok, library works correct up to (tested) 1.5Mbaud but will go higher.

            Make sure that your clock is correct abd ardupilot works correct. Its not library problem for sure.

          • ryan

            For completeness, I figured out my problem. I was calling Getc() and then Putc() just like your example. Problem was, if autopilot sent a 0, I would never call Putc() because the “if” statement was looking at the value of “c”. I wrote a new function identical to your Getc() with the added functionality that it returns a 1 or 0 for whether it read a byte. I use this in the “if” statement and I’m now reading from the AP perfectly. Thanks for your help. I’m a grad student in aerospace engineering and your libraries have been absolutely crucial in allowing me to make as much progress as I have in developing code on an STM32F4!

  • Christian Julius

    Did you use ring buffers in yoou lib? Or can I add them, if I want to have more buffer? Normally I use two, one for RX and one for TX, handeld by interrupts.

    • Guest

      ops…. ring buffers

    • If you take a look at library, you will see it for RX.
      If you need for TX too, I use DMA for that stuff. Library is also available on my web for DMA.

      • Christian Julius

        DMA for TX (outgoing chars) is ok, the CPU continues to work during transmission. Nice hair cut! Makes you look younger!

  • Jacky

    Hi Tilen,

    I use USART communication in main block by controlling whether ‘TM_USART_BufferEmpty’ is 0 or not. I want to do this in interrupt block which is triggered when the new data is available such as void USART1_IRQHandler() function. How can I do it? When I use void USART1_IRQHandler() function I get ‘multiply defined’ error

    • http://stm32f4-discovery.com/api/group___t_m___u_s_a_r_t.html

      Section “USART Receive interrupt handlers”

      • Jacky

        Thanks for your answer.
        I put “#define TM_1_USE_CUSTOM_IRQ” in defines.h

        and I defined this function in my main file

        void TM_1_ReceiveHandler(uint8_t c) {
        TM_PWM_SetChannelPercent(&TIM4_Data, TM_PWM_Channel_1, c);
        }

        Unlike my previous example I explained above, this doesn’t work. Is this because I didn’t assign new pins which is used for communication? If it is so, how can I do that? I couldn’t find TM_USART_PinsPack_Custom function

        • Well, if you would read correct, it will work.

          In api, it says “Change X with your usart….” so in your case it is not 1,but is USART1.

          • Jacky

            I’m terribly sorry. Thanks a lot

          • I’ve updated library.
            It now allows you to use custom IRQ Handler, so in your case, you can do somewhere in your project this:

            void USART1_IRQHandler(void) {
            //Detect what causes USART1 interrupt here.
            }

            And you won’t get error for multiple definitions.

  • Pingback: Library 53- GPIO for STM32F4 - STM32F4 Discovery()

  • Onur Akgün

    Majerle,

    Is there any way to use usart interrupt with timer interrupt properly? Whenever I try to use both of them, I think they conflict but when I comment out timer, usart interrupt works well

    • You can use preemption interrupts.
      Preemption interrupts will run interrupt inside interrupt if needed.

      For example: If TIM interrupt has higher priority, then if interrupt inside USART will work and timer interrupt occurs, USART interrupt execution will stop, timer interrupt will be executed and usart then back.

      Understand?

      • Onur Akgün

        I put this line in defines.h
        #define TM_USART_NVIC_PRIORITY 0x00
        //because I want this to have first priority

        //In timer block
        NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;

        Isn’t this true?

        • This would work (with preemption) in case you have preemption interrupts enabled.
          Check for NVIC_PriorityGroupConfig() function in misc.c file for standard peripheral drivers.

          • Onur Akgün

            void NVIC_PriorityGroupConfig(uint32_t NVIC_PriorityGroup)
            {
            /* Check the parameters */
            assert_param(IS_NVIC_PRIORITY_GROUP(NVIC_PriorityGroup));

            /* Set the PRIGROUP[10:8] bits according to NVIC_PriorityGroup value */
            SCB->AIRCR = AIRCR_VECTKEY_MASK | NVIC_PriorityGroup;
            }

            Is the interruption enabled?

          • After your main, add this:

            NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);

            and try again.

          • Onur Akgün

            I added but nothing has changed.

            I use custom usart interruption, could this be the reason of the problem?

          • I don’t know how your software is done.
            Do you clear interrupts when they happen.

          • Onur Akgün

            void TIM7_IRQHandler(void)
            {
            if (TIM_GetITStatus(TIM7, TIM_IT_Update) != RESET)
            {
            //
            }
            }

            void TM_USART1_ReceiveHandler(uint8_t receivedData)
            {
            //
            }

            These are my interrupts

          • TM_USART1_ReceiveHandler this function is called in case TIM7 interrupt is disabled?

            Or it is not called at all?
            You will have to clear TIM7 pending interrupt bits.

          • Onur Akgün

            It is called when new data available in buffer. According to my priority settings, when Usart is called, TIM7 is disabled but I think they conflict

          • Well, I think that is not a problem.
            Show me entire code.

            Use pastebin for that!

          • Onur Akgün
          • I think problem is because you don’t clear TIM interrupts

            Use TIM_ClearITPendingBit() function and TIM_ClearFlag() functions inside TIM interrupt handler.

            PS: I said that set group config at beginning of main function, not at the end.

          • Onur Akgün

            Yes Majerle, you’re right. That was the reason of problem. Thank you. Now, I send data but usually I get different error. For example I send ’80’ and after stm gets this data, it sends back but irrelevant data appears. Normally I never had this error without timer interruption. Why does it happen?

          • I didn’t check your code in detail, but anything is possible here.

          • Onur Akgün

            Thanks a lot for your help

          • Onur Akgün

            Majerle,

            I found the reason of the problem. If process in timer block is too much, I get that error. When I translate some of them into while block, No error happens. How can I solve this problem in timer block?

          • Use preemptive interrupts or use while block.

          • Onur Akgün

            I already use it

            NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
            //This is for timer

            #define TM_USART_NVIC_PRIORITY 1
            //in defines.h

            NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
            //in main block

            Is there any problem about it?

  • Lucas

    Hello Tilen!

    How I can transmit in 300 or 100 baud? It’s possible?

    The minimum in your lib is about 1300 baud.

    Thanks buddy.

  • Pavel Teroschin

    Hello everybody.
    I have a problem.
    Could anyone say me, how i can check when the wire has broken?
    For example: two CPU, one CPU send data to another, its OK, but if one of two wires will be broken, it is some flags? or interrupts?

    Thnaks in advance

    • No

      • Pavel Teroschin

        Maybe I can send some info to another cpu, and if he wil not answer me for example 5sec, I can suggest that communication is out? How I can check the communication between them?

        • What if one cpu stuck somewhere?

          • Pavel Teroschin

            I am confused. May be you can tell me some things how to make good and quality communication between CPU? And what about this interrupt EIE in CR register? NE, FE, PE? Will this help? Also a read about LIN. There is LINE BREAK DETECTION.

          • I don’t know what exactly you have in mind in “good quality”. For sure you will need some error checking like CRC for received/sent data.
            For all interrupt sources, take a look at reference manual for F4

            To get line break detection, then communication must be done in repeated time period.

        • Christian Julius

          You have to use the methods of the “Functional Safety”, used in industry for safe communication.break and crossover can be detected. But this is a little bit complicated for hobbyists. The easiest thing is using timeouts.

          Regards,
          Christian
          (FS Expert 🙂

  • Nafi Abdul Hakim

    Hello Tilen, i have some problem in USART, is it possible to use 2 USARTs at the same time? I’ve choose PA2 PA3 and PB6 PB7, 1st for communicate w/ Servo Controler and 2nd for communicate w/ my Laptop.

    I;ve already delcared “.. TM_USART_Init.. ” at my Main, 1st i send it from my Main, and 2nd from my timer interrupt, but i can only use one of them (only at main, but at interrupt disable, viceversa). Any idea why?
    Thanks

    • The problems I see here are:
      Too long in interrupt. In interrupt just set flags and do work in main.
      Delay in interrupt with my functions does not work by default.

      You have priority group for nvic set to 0 (by default) and that means that wheb obe interrupt is working, all others are waiting.

      • Nafi Abdul Hakim

        thanks ya 🙂

  • Jack

    I tried your USART Library, and the result is following the image.

    I already try USART of pinspack 1 and pinspack 2. Sometimes it does not show anything, but in better situation is shown as image.

    I don’t know what happen in this situation. Do I use VCP (as known as Library 23) instead of this ?

    Thanks.

    • Ok, 2 main reasons are possible:

      1. Ground connection is missing between computer and discovery,
      2. PLL clock is not set correct. I would say that this is problem.

      • Jack

        The first situation would measure between 3V and GND, then I should get 3V in voltmeter. Is that right ?

        The second situation, I don’t know how to set the PLL clock. Any advice ?

        • I have a post about setting pll clock properly. Please use search.

  • Vishnu

    Here is my code below
    http://pastebin.com/w7bwcWLn
    Upon debugging I found that my code gets stuck at the below line.
    /* Wait to be ready, buffer empty */
    USART_WAIT(USARTx);
    What could be the reason for it? I tried manually clearing the buffer using the
    TM_USART_ClearBuffer(USART1);

    But it did not help.
    I get no output at the terminal as the code gets stuck in the above while loop

    Thanks for the help

    • For some reason is flag for USART not cleared. Is project correctly set up?
      Drivers, defines and other stuff for standard peripheral library is OK?

      • Vishnu

        I use Coocox ide, There seems to be no problem in the project. Could the problem be due to hardware?
        I am using this module
        http://robokitsworld.com/index.php?main_page=product_info&cPath=7&products_id=523

        I didn’t do any setup of hardware. Just connected the 4 pins to microcontroller. The PC side drivers are installed automatically. And the Terminal window shows connected. But in Microcontroller the code gets stuck at while loop. Does this mean that microcontroller is unable to connect to the wireless module?

        • Module has nothing to do with that.
          Well, I can guarantee to you that if you have latest usart lib from me, then it works properly.

          Go to debug and check register values of USART1 and show here.
          You can use print screen aswell.

          • Vishnu

            On the bottom right are the values of the variables
            USARTx is 0x40011000

          • This are not registers. This are local variables.

          • Vishnu

            I dont know what happened but all the registers jumped from being 0x00 to 0xff.. As soon as the while loop started executing.

          • xl4m3rx

            Add “STM32F40_41xxx” to your project configuration… or the proper define for your board …

            http://i.imgur.com/92NlP8Z.jpg

            http://i.imgur.com/kYi8B0o.jpg

  • samit

    Here is my code–> http://pastebin.com/eQmB8399

    I am flashing this code but on tera term hyper terminal, it is not displaying anything.

    I am using stm32f103 board on which RS232 port is there i am directly connecting it to usb port of PC but nothing is displaying.

    Please help me SIR.

    Thankyou

    • If you would read content, you will notice that you have to enable clock for USART, enable clock for GPIO, enable GPIO pins and then USART.

      • samit

        sir when i am using direct port of rs232 on my board, then which gpio pin will i be needed. I am not getting.

        • That’s why you should read manual for you chip. I really don’t know which USART is used here and which GPIO pins are associated with it.

          • samit

            ohk i got you. I need to set gpio configuration for Tx and Rx and need to enable that USART, right?

  • samit

    refer my code http://pastebin.com/C7LtHAkr

    Nothing is been displayed on terminal.Please tell me where I am getting stuck?

  • Roman Zavyalov

    I adapted the code for STM32F37x but it does not work.

    code:

    static __INLINE void TM_USART_Putc(USART_TypeDef* USARTx, volatile char c) {

    /* Check USART */

    if ((USARTx->CR1 & USART_CR1_UE)) {

    /* Wait to be ready, buffer empty */

    USART_WAIT(USARTx);

    /* Send data */

    USARTx->TDR = (uint16_t)(c & 0x01FF); // Register DR is modifed to TDR for STM32F37x

    /* Wait to be ready, buffer empty */

    USART_WAIT(USARTx);

    }

    }

    ======================================================

    /* Private functions */

    void TM_GPIO_INT_EnableClock(GPIO_TypeDef* GPIOx) {

    /* Set bit according to the 1 <APB2ENR |= (1 <AHB1ENR |= (1 << TM_GPIO_GetPortSource(GPIOx));

    }

    void TM_GPIO_INT_DisableClock(GPIO_TypeDef* GPIOx) {

    /* Clear bit according to the 1 <APB2ENR &= ~(1 <AHB1ENR &= ~(1 <ISR & USART_FLAG_TXE)) // Status register SR is modifed to ISR for STM32F37x

    ===================================================
    Compiling is ok, but USART MCU not worked.
    Please, help me?

  • Roman Zavyalov

    I adapted the code for STM32F373 MCU for operating with SPL Library but it does not work.
    Copmiling is ok, but USART not worked.

    Status Register SR is modified to ISR for STM32F37x

    Data register (DR) is modified to Transmit Data Register (TDR) for STM32F37x

    AHB1ENR bus is modified to AHBENR bus for STM32F37x

    Modified alternate function GPIO_AF_USART2 to GPIO_AF_7 for STM32F37x

    what is missing?

    my code changes –> http://pastebin.com/mufe6MQ4

    • Gpio clock enable function works properly? Make sure it does.

      • Roman Zavyalov

        It seems that the compiler does not see the initialization function TM_USART_Init

      • Roman Zavyalov

        in the debug session can not reach this line. The compiler does not go into the function TM_USART_Init();

        • Maybe you should call function for init, ha?

          • Roman Zavyalov

            of course.My main.c code here –> http://pastebin.com/vQXuswnQ

          • Roman Zavyalov

            Yes!

            It is worked!
            I forgot to add #define USE_USART2 in defines.h file.

            Thank you very mutch for your help 🙂

  • leonardo

    I have a prblem with UART’s. No one example works on my board. It’s to weir… I put my oscilloscope on Tx pin and put a breack point befor TM_USART_Puts and when I execute the line nothing happend. am I missing something?

    • What are you doing man? 😀
      Select proper target in Keil uVision before compile.

      • leonardo

        My mistake, or not… If I put a breck point on TM_USART_Puts, when the programs stops on this line, if I press Step the cursor goes to next line and nothing happend on my oscilloscope. But, I can see now that the code doesn’t execute, I have to press Step again to execute TM_USART_Puts.
        Sorry!

  • Saff

    Hello Tilen,thanks for the awesome librarys that you wrote,actualy i’m having a problem to work with the USART and the LCD16*2 at the same time,there is a pin conflit,can you suggest a solution ? thanks

    • Hi,

      you can use different PINs for USART and for LCD. Both libs allows you to select custom pins for your devices.

  • Vineeth

    Hii TM , I was trying to implement your example 1 , and I have used the virtual COM port
    library and successfully combined the two examples without any errors, but I failed to get the hello world text on my desktop. Please tell me if I need to connect any pins to TX,RX. I will be waiting for your reply.

    • You have to. You need usb-uart converter.
      Read post again how usart works here.

      • Vineeth

        Thanks for the reply,So, if we cannot send the data without USB UART converter , then what will the USB CDC library does that creates a virtual com port. Is there any chance that without using FTDI or CP210X we can send data through virtual com port which is created through that library.

        • If you have VCP lib, then communication goes through usb directly, no converters here.

          But for usart, you need converter.

          • Vineeth

            Ohh thanks, but that was the thing I mentioned earlier. I am not getting the hello world on the terminal. I have also used the same terminal that you mentioned in the above tutorial.I have combined both the USBCDC and the USART library and executed the example. Here I am attaching my code and the files I included.

            refer it http://pastebin.com/yUAex6XM

          • Vineeth

            Hii Tilen, I was actually waiting for your reply since morning . So please find what is mistake I might have done in that,I think that my logic have been got wrong.

          • Vineeth,

            I’m not always at computer to answer question. This is not my job here, so please be patient.

            According to your example, USART will never be ececuted, because while loop is blocking it of USB VCP.

            Printf function also won’t work, because I don’t see fputc printf handler function which sends data to your stream.

          • Vineeth

            Thank you, I noticed that I have initialized system in while loop which is a blunder, but I did not exactly understood what you have told, here I am attaching a new code in which I think I minimized my mistakes but not getting the output.I have changed printf function here.
            http://pastebin.com/iw98EDMT
            http://pastebin.com/jeBAzWfP

            In the above codes Ihave changed the if code in that. One I used USART and for other I used USB VCP.
            Please dont feel that I am irritating you and I am very new to these kind of coding stuff
            Thank you
            Hope you reply soon

          • This code looks better.
            So, 9600 bauds is also set in your computer, and there is no response about “Hello world” message?

          • Vineeth

            Yes, and I am confused whether to use “putc” on VCP or UART, So I tried on both and got no result. Do I need to make any settings in the terminal? You have made the custom BR . I think (custom baud rate) as 250000 and I dont understand why? Or am I missing anything?

          • Putc for vcp is going via usb, putc for usart works via usart port. Both needs terminal.

            I dont know where you found 250k baudrate.

          • Vineeth

            I have seen that custom baud rate setting in the terminal photo you have kept in the starting of this blog. So, I am a bit confused on how to write a code so that I can see any data coming from USART port . Actually I need to send some data from bluetooth via usart to my pc using VCP .It would be very helpful to me if you send a code which solves my purpose and I will be thankful to you.

          • I’m not so kind to do that for you, but you can add me to skype (search for skype account here on site) and I will show you via teamviewer.

          • Vineeth

            Ohh, thanks

  • Pingback: HAL library 07- USART for STM32Fxxx - STM32F4 Discovery()

  • Prabhu Chawandi

    Hi TM,

    I want to enable the RX IRQ handler over UART. I got more example of configuring USART but I could not find it doing on UART.

    Could you please help me ? Below is the code, I am using to init, but how can I configure RX IRQ handler on UART5 ?

    Uart5_Init(){
    handle->Instance = UART5;

    handle->Init.BaudRate = 115200;

    handle->Init.WordLength = UART_WORDLENGTH_8B;

    handle->Init.StopBits = UART_STOPBITS_1;

    handle->Init.Parity = UART_PARITY_NONE;

    handle->Init.Mode = UART_MODE_TX_RX;

    handle->Init.HwFlowCtl = UART_HWCONTROL_NONE;

    handle->Init.OverSampling = UART_OVERSAMPLING_16;

    HAL_UART_Init(handle);

    }

    Many Thanks,
    Prabhu Chawandi

  • Jorge Del Aguila

    Hello Majerle,

    I’m trying to stablish a comunication between two stm32 discovery boards. I have modified the code you provided in your example to do this. Please see the code:

    This is the code I have for the receiver:
    http://pastebin.com/uVFKkZBa

    This is the code I have for the emitter:
    http://pastebin.com/bjyWPZVz

    I also have connected the Tx of one to the Rx of the other and vice versa. Still I don’t get the leds to turn on. Do you have an idea of why does it happen? Thanks 🙂

    • Looks ok. Grounds are connected? And pll is set ok? 😀

      • Jorge Del Aguila

        Hi! Yes ground connected :D. Not sure about the pll. I haven’t set any frequency. Could you further explain that part?

    • Jorge Del Aguila

      Using stm32f407 and trying to turn on PORTG :(. I changed it to PORTD and leds are shining 😀 Thanks for the libraries!

  • julien terrier

    Hello
    Tilen, in first congratulation for these huge works! My name is julien I’m
    french and beginner in embedded system so forgive me if I do any mistakes, it’s
    not my native language! Currently I’m trying to display some string on my
    disco-board (STM32F429I) I wish used STemWin library but every example provide
    by ST.com are too big for my lite version of keil µvision5. Therefore I tried to
    use Coocox as IDE because it‘s free. In fact it’s thank to coocox that I have
    found your site, because I followed ” First time with STM32F429
    discovery”! Then I continued to look at your great works, I downloaded
    “stm32f429-master”, I compiled and loaded several of your project (with
    keil), « 02-STM32F429_LED_BUTTON », « 08-STM32F429_ILI9341 »
    etc… But then I met a problem with “04-STM32F429_USART” I can’t
    work with it, and I’m very interesting by this project for my own project.

    I compiled
    and loaded every files in the good target without problem

    I used a
    FTDI “FT232R” compliant 3V3, with the suitable driver. It is
    recognized by my PC

    I
    connected and crossed the wires between TX/RX of each other device, I connected
    too the gnd between FTDI and my disco-board.

    I
    downloaded and installed Bray. I setted terminal according your advices 9600
    bauds etc..

    I wrote
    “Hello world” in the transmit window then I send the message and I
    didn’t answer on the Receive window.

    (It seems
    that my FTDI works indeed each message sended LEDRED2 on the FTDI board toggle
    moreover I recovered the transmit signal with my USB-oscilloscope but I didn’t
    succeed to recover a receive signal).

    Thank for
    your help!

    • How exactly are connected pins? Explain in detail please.

      • julien terrier

        Tx FTDI is connected on PA10 and Rx FTDI is connected on PA9 then I connected both GND together.

        • You failed. Check example again, including comments.

          • julien terrier

            Thanks a lot dear! My setback is over, I was convinced that I have to used PA9 and 10 but now everything is good!
            PB 6 and 7, I’m a lazy man just read comments

          • julien terrier

            Actually I wish combine your LCD and usart project to display from hyperterminal some string on the lcd of my disco-board. Do you think it’s possible?

  • julien terrier

    Hello, I need some information because I’m not sure to understand everything about TM_USART_t structure:

    http://pastebin.com/f7kbKbJ6

    And I’d would know the link with USARTx_DR.

    – *buffer: Pointer to buffer where data will be stored from buffer.

    – size: buffer length in my case is 32Bytes I use default setting.

    -Num: Number of elements ==> elements = character ?

    -In: This corresponds to the RDR register?

    -Out: This corresponds to the TDR register?

    -Initialized: I don’t know simple variable used in USART_init ?

    -StringDelimiter: To indicate the end of line.

    Thank you TM.

    • You dont need to worry about that. This is private usart cyclic buffer which handles received data from usart. And stores it here.

      • julien terrier

        ok thx

  • batman Simon

    Hi Tilen, How can recive buffer from TM_USARTx_ReceiveHandler in interrupt?

    I using void TM_USART3_ReceiveHandler(uint8_t c) { // com 2

    TM_USART_Gets(USART3, buffer,sizeof(buffer));

    TM_USART_Puts(USART3,buffer);

    but buffer = zero .

    • Hi,

      yes, it is, because if you use custom receive interrupt function, by settings proper define as mentioned, then incoming data are not stored into cyclic buffer, because you can handle it by yourself and there is no need for double saving.

      http://stm32f4-discovery.com/api/group___t_m___u_s_a_r_t.html
      Check what it says under “USART receive interrupt handlers”

      Btw..to get string from USART, you need to wait for some characters first to be received. In your case, you are calling Get string function for every character you get. This is not proper logic.

      • batman Simon

        Thanks you! i recvice OK..

  • batman Simon

    Hi, I compile 04-STM32F429_USART_CUSTOM_PINS for stmf407vet. I configured for it :

    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);

    TM_USART_Init(USART2, TM_USART_PinsPack_Custom, 9600);

    and

    void TM_USART_InitCustomPinsCallback(USART_TypeDef* USARTx, uint16_t AlternateFunction) {

    /* Check for proper USART */

    if (USARTx == USART2) {

    /* Initialize custom pins */

    /* TX pin = PD13 */

    TM_GPIO_InitAlternate(GPIOD, GPIO_PIN_13, TM_GPIO_OType_PP, TM_GPIO_PuPd_NOPULL, TM_GPIO_Speed_High, AlternateFunction);

    /* RX pin = PD14 */

    TM_GPIO_InitAlternate(GPIOD, GPIO_PIN_14, TM_GPIO_OType_PP, TM_GPIO_PuPd_NOPULL, TM_GPIO_Speed_High, AlternateFunction);
    }
    }

    ->> Not run.
    So. Wrong???

    • OK, 2 violations here:
      1. Do not post code in comments
      2. Check USART pin table. You will see that PD13 and PD14 are NOT supported for USART2!

      • batman Simon

        So sorry! I fix it, I know PD13 and PD14 not support for usart2 if i using custom pin for usart2, How i can using pin??

        • You can’t use other pin than which are supported for your MCU. Check it’s datasheet if any more combination is supported for USART2 than listed on my table.

          Otherwise, you can do only software USART.

          • batman Simon

            I understand. So Thanks you.

          • batman Simon

            I’m sorry but my understanding is any port can also be configured to output uart. In the examples I have found using foot tx: B6 rx: A10 and A10, the B6 usart of your table. The question I want to ask you is can vacuum under uart pin board for data transmission com port or not? thanks a lot.

          • Vacuum under uart? What that means?

            Btw..your understandings are wrong. I dont know where you got them.

  • Teja ganesh kumar

    Hello Tilen,
    My name is Ganesh.I am working on STM32F401VCT6 discovery board. Trying to send message using UART ports but unable to send message. I used stm32cube software.Iam attaching code link . Please help Thanks in advance.link for code http://pastebin.com/TNysA7nd

    • Woow,

      Sorry, but it is very unreadable code. As I see for fast, you are using some strings you wanna send to your device. You might check my USART library for HAL based drivers and check how I send strings there. Maybe it will help you too.

      • Teja ganesh kumar

        HI Tilen,
        Can you provide an example code for IAP(In-Application Programming) for STM32F401VCTX.

  • RAVINDRA KANT

    Hello Tilen,
    I am using the STM32F4 discovery board for my purpose and at a time i have to configure two USART terminals,So for connecting my board to GSM i have used USAR1 PB6(TX) & PB7(RX),i am using sim900 module ,the problem is when i send AT commands one by one it works fine and i can move ahead.
    But if i send AT commands in order(shown below) from the same board,
    Commands:
    AT
    AT+CREG?
    AT+CGATT=1;
    AT+CSTT=”service provider”;
    AT+CIPSTART=…….etc
    I get response of only first command that is OK
    and nothing else .Can you tell me what mistake i am doing?
    Is it the problem of not declaring delay?

    Thanks in Advance

    • Hi, from this perspective, I, can only guess what is going wrong.
      Show code as well.

      • RAVINDRA KANT

        main()

        {

        GPIOInitialize();

        UART_Initialize();

        USART_puts(“ATr”);

        USART_puts(“AT+CREG?r”);

        USART_puts(“AT+CGATT=1r”); //GPRS ok

        USART_puts(“AT+CIPSHUTr”);

        USART_puts(“AT+CSTT=”airtelgprs.com”r”);

        USART_puts(“AT+CIICRr”);

        USART_puts(“AT+CIPSTART=”TCP”,”www.google.com”,”80″r”);

        }

        void USART1_IRQHandler()

        {

        if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) //it checks receive complete interrupt(USART_IT_RXNE) on USARTx

        {

        rx_web = USART_ReceiveData(USART1);

        if(rx_web == 0x0A || rx_web == 0x0D)

        {

        count++;

        if(count==4)

        {end_flag=1;}

        }

        else if(rx_index < LINEMAX)

        {

        rx_buf_web[rx_index++]=rx_web;

        }

        }

        }

        void UART_Initialize(void)

        {

        RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);

        RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);

        USART_InitStructure.USART_BaudRate = 9600;

        USART_InitStructure.USART_WordLength = USART_WordLength_8b;

        USART_InitStructure.USART_StopBits = USART_StopBits_1;

        USART_InitStructure.USART_Parity = USART_Parity_No;

        USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;

        USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;

        USART_Init(USART1, &USART_InitStructure); // USART configuration

        USART_Init(USART2, &USART_InitStructure); // USART configuration

        USART_Cmd(USART1, ENABLE); // Enable USART

        USART_Cmd(USART2, ENABLE); // Enable USART

        }

        void GPIOInitialize(void)

        {

        GPIO_InitTypeDef GPIO_InitStructure;

        RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE); //Enable clock for GPIOB

        RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);

        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7 ;

        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;

        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;

        GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;

        GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;

        GPIO_Init(GPIOB, &GPIO_InitStructure);

        GPIO_Init(GPIOD, &GPIO_InitStructure);

        GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_USART1);//Connect PB6 to USART1_Tx

        GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_USART1);//Connect PB7 to USART1_Rx

        GPIO_PinAFConfig(GPIOD, GPIO_PinSource5, GPIO_AF_USART2);//connect PA5 to USART2_Tx

        GPIO_PinAFConfig(GPIOD, GPIO_PinSource6, GPIO_AF_USART2);//Connect PA6 to USART2_Rx

        }

      • RAVINDRA KANT

        http://pastebin.com/ngXy3GZv
        u can find the code in pastebin

        • AT commands syntax is “Commandrn” not just “Commandr”.

  • RAVINDRA KANT

    Hi,Tilen Sir,
    is it possible to use two USART at the same time simultaneously in STM32F407.

    • Definetelly. You can use DMA/IRQ for this if you really need them “simultaneously”, otherwise you can send data from one usart first and then another.

      Receiver always works simultaneously because it uses interrupts.

      • RAVINDRA KANT

        Thanks Sir,
        and yes what is the purpose of using __WFI() in the program.

        • Not sure this has anything to do with USART, but __WFI is instruction for ARM Cortex-M processors, meaning “Go to sleep until interrupt” (Wait For Interrupt).

          • RAVINDRA KANT

            hello Tilen,
            I am getting problem while receiving response from the USART.My work is going on like this ,
            When i receive something on USART1 PB6 and PB7 terminal ,i transmit it to USART2 that is PD5 and PD6 ,but i cannot see anything coming from USART2 ,when i checked the USART1 receiver function i found actually no data has been received,when i print it i got nothing accept blank screen.
            Thanks in Advance

          • Wrong init, pll invalid, wrong pinout. These cases arepossible

          • RAVINDRA KANT

            Sir,Is it possible to use USART1, PA9 ,PA10,PB6 and PB7 at once instead of using any other USART

          • Obviously not. Just check what I said above.

  • RAVINDRA KANT

    Hello Tilen,
    The question is regarding use of USART1(Port B) and USART2(port D) synchronously
    In the nested interrupt vectored controller i have declared NVIC_struct.NVIC_IRQChannelPreemptionPriority = 1;
    is there something to set extra?

    • Each usarthas own settings in nvic.

      • RAVINDRA KANT

        Hi Marjele Tilen,
        I have written a simple code to glow the led when it receives something ,it aint working..http://pastebin.com/ydwfi7r9
        I need help to figure out the problem
        Thanks

  • Super Golem

    Hi Tilen, Thank you very much for sharing all libraries with us. I used your USB library with great success to communicate to a virtual COM port. No errors in 1000 commands. Now I also use your USART library 04 to communicate with the same program over Bluetooth. I can only make the communication flawless when I remove “|| u->In != u->Out)” from the Getc routine. So the check if there is data in the buffer becomes:
    /* Check if we have any data in buffer */
    if (u->Num > 0) {

    instead of

    if (u->Num > 0 || u->In != u->Out) {

    If I look into the USB routine, there is the same buffer topology. Reading is only possible when u->Num > 0, meaning there is data in the buffer. Thus it might be that the USART library needs a correction.

    • Buffer implementation in USART is not done properly. Because IRQs are used for write and read process it may happen some “shit”. Proper way would be to use only 2 vars for indicating buffer state, so only in and out pointers. Without “Num” pointer. This should be calculated from In and Out values. Check my BUFFER library on github for HAL and you might correct it to your needs.

      • Super Golem

        OK, maybe I will take a look. I tried HAL on microchip and it was HELL. If we call STM32 the client and Windows the server then as far as I can see the USART buffer is only used for reading by the Getc routine and writing by the IRQ when the server sends something. Thus as long as you do not send too many things from the server, you are fine because your buffer will not fill up. Thus you have to design a protocol between client and server so that the server only sends data after it knows that client understood the data.
        The USART buffer in library 04 is not used when writing from client to server. If you do not design your protocol properly, buffers will always fill up. Compare with some manager always talking to you, you never answer because you do not care, your buffer fills (or is always empty ?) and the manager never knows if you understand. With the proposed modification my protocol works like HAL 😉

  • Name

    Hello
    If i want to send 10 ADC values to the computer, what is the fastest usart communication speed, that I can earn? how high can I set the baudrate?

    Thank you for the help!

    • Something you might aee in reference manual for your mcu.

  • Bartosz Kościug

    Hello,
    I have a problem with reciving data from my PC bluetooth when I try to send for example “6.9”(which is the temperature from web) and put it on the LCD display HD44780 I get some crashed data. I use both functions TM_USART_GETC and TM_USART_GETS with no result ;(

    • Bartosz Kościug

      Should I use some other functions to wait untill data will come?

      • How you send data? As character or? Is baudrate the same on bt?

        • Bartosz Kościug

          The baudrate is set to 9600 I dont have this problem when I sending the data from my stm32 to PC… I send the data from my PC as a string

          • Bartosz Kościug

            Moreover when I use the TM_USART_GETS function in debugging mode the variable(my buffer) is empty 0x0

          • Show me pastebin code and show how you send data. All characters. Moreover, check how gets works. Its described.

          • Bartosz Kościug

            http://pastebin.com/XF5QRLaz this is the code on my pc I wrote it in Python, and the code from STM http://pastebin.com/1XvWyKEg

          • You cant use custom init and then my lib for read.

          • Bartosz Kościug

            You mean SystemInit(); ?

          • No, i dont. Usart init.

  • Jay Katira

    Hello Majerle Tilen, I want to know that If we want to use two USART at a time, then what should be priorities for that in NVIC sector?

    • Depends on what priority you need. By default, my library sets this that USART with lower number has higher priority.

      • Jay Katira

        Yes, I am using USART6 for SIM900 and I am USING USART1 for serial communication with PC. I am using both at a time so that i can get Sim900 reply to my pc right. but bu this priority i cant get sim output as i have used both USART1 and USART6 IRQ handler as you mentioned in NVIC page. But it doesnt work.

        • Interrupts are not problem here. Something else is you didn’t mention. You can show your code.

      • Jay Katira

        This is my NVIC declaration

      • Jay Katira

        nd this is my IRQ

        • Jay Katira

          Here i want to send USART6 received data to direct USART1. If i am not Defining USART1_IRQHandler() then i can send it to USART1 easily. but i want also USART1 IRQhandler.

      • Jay Katira

        Here i want to send USART6 received data to direct USART1. If i am not Defining USART1_IRQHandler() then i can send it to USART1 easily. but i want also USART1 IRQhandler. Whats the way?

  • Jay Katira

    Hello Majerle Tilen, Is there any way or i have written wrong code? any suggestions ???

  • Jean Louis Leclef

    Hello, Tile, all,
    first congrats for your excellent text, this is really useful.

    my name is Jean Louis Leclef and I designed a CPU board based on the excellent STM32F407ZGT7, using MikroPascal from MikroE for programming.
    My “Hello World” test is a LED connected to PF09 and I can control it beautifully. I am programming the device using the JTAG port and it works well. I would say everything works well… except receiving data on the USART1.
    USART1 is connected to a USB port through an FTDI FT232RL device. I can trace the serial data down to pin PA10. so I am sure the chip gets data on the pin. Sending data works fine, only receiving them does not work.

    my init code is

    GPIO_Clk_Enable(@GPIOA_BASE);
    GPIO_Alternate_Function_Enable(@_GPIO_MODULE_USART1_PA9_10);
    UART1_Init_Advanced(9600, _UART_8_BIT_DATA, _UART_NOPARITY, _UART_ONE_STOPBIT, @_GPIO_MODULE_USART1_PA9_10);

    and the receiving loop (I do not use interrupts yet) is

    while (TRUE) do begin
    if UART1_Data_Ready=1 then begin
    RXdata := UART1_Read;

    end;
    end;

    I spent hours trying eerything but I desperately need your help. Thanks in advance for that.
    best regards,
    Jean Louis

  • Harshit Kumar

    HI Tilen,
    I am facing a problem here. When I am compiling the code I am getting the error – u is not intialised
    When I run the code in debug mode I find that the following statement is executing :

    if (u->Initialized == 0) {

    return;

    }

    which means that the function TM_USART_INT_GetUsart(USARTx) is not returning the proper input. I am using USART1 ( the same code given in your example). I can’t seem to find the error. Please help. Thanks in advance.

    • DId you initialize lib?

      • Harshit Kumar

        Yes, I did. Here’s the code http://pastebin.com/MHUPm2ic

        • Harshit Kumar

          Waiting for a reply.

          • I’m checking this again, why GetUsart won’t return “PROPER INPUT”? Sounds strange from my side, since this code should work fine as it works for many users.

            Compiler you use is? What about define settings for toolchain?

          • Harshit Kumar

            I am using ARM-GCC, I used the following link while setting up Coocox :http://patrickleyman.be/blog/stm32f407-tutorial-with-coocox/

            One thing I have noticed is, in the debug mode, inside
            TM_USART_Init(USART1, TM_USART_PinsPack_2, 9600);
            the cursor directly moves to the end of the function. I can’t see the following line getting executed:
            #ifdef USE_USART1
            if (USARTx == USART1) {
            TM_USART_INT_Init(USART1, pinspack, baudrate, TM_USART1_HARDWARE_FLOW_CONTROL, TM_USART1_MODE, TM_USART1_PARITY, TM_USART1_STOP_BITS, TM_USART1_WORD_LENGTH);
            }
            #endif

            what if USE_USART1 is not getting defined? That would also explain ‘u’ not getting initialised.

            I’ve tested some other usart code and that is working so I don’t think there is any problem in my setup.

          • Use usart1 is my define. Check header to see when it is defined., ou are missing some define for sure. Define also used by std periph drivers.

          • Harshit Kumar

            /* F405/407/415/417/F446 */

            #if defined (STM32F40_41xxx) || defined(STM32F446xx)

            #define USE_USART1

            #define USE_USART2

            #define USE_USART3

            #define USE_UART4

            #define USE_UART5

            #define USE_USART6

            #endif

            I think it is getting defined.

          • Then you would see that statement could be executed in debug. But you dont. Meaning use_usart1 is not defined which means if statement you posted in last comment does not getting executed.

          • Harshit Kumar

            Can’t think of any reason of why this is not executed. Any ideas?

          • I said above.

          • Harshit Kumar

            I am asking why #if defined (STM32F40_41xxx) || defined(STM32F446xx) is not returning true?

            I am using stm32 discovery board with stm32f407vg.

          • Because you did not read drivers notes. Open stm32f4xx.h file and read on start what defines are required.

          • Harshit Kumar

            Got it. Thank you for the help.

          • Entropy

            Could you share the answer with others as well? i am having the same exact issue and don’t seem to know exactly what “#” to out in the dedicated “defines” header, besides that i have read the “stm32f4xx.h ” file and have uncommented “#define USE_STDPERIPH_DRIVER” but the issue remains. please help. Thanks

          • Entropy

            Hi mate, could you share the final answer to this issue? thanks

  • Tony

    hi, Tilen
    It is really a great job ! Thank you for sharing everything here.
    I use your library(TM_ILI9341_LTDC) and this USART library to do a simple test.
    I use USART1 with pinpack 2 which used PB6 & PB7 as TX&RX pins.When I trying to get a character from terminal and show it on the screen but it never work. The screen just flash but no character shows up. It seems that there is no pin conflict,what do you think the problem should be. Im a beginner and I found that your code did really help as a guildance.
    B.R
    tony

    • There is. PB6 is used for SDRAM.

      • Tony

        Thx,I’ll try to get this fix..

  • FELIX

    Now I can send from the terminal as a ASCII character or Decimal value through UART to STM32f4 device. If I send Decimal value directly (for eg: 100). How can I store this value into one variable. As it is receiveng in a serial manner. In the while loop, The num ‘1’ receives first then ‘0’ and then ‘0’. Therefore, I could not store 100 as in single variable. Is there anyway to help me.

    THANKS.

    • If you are sending number as string, then receive it as string. Use char arrayto store chars for number and later convert them to number.

      • Fels

        may I know some example with char array. ?

  • sel mesal

    When should one choose to use UART5 instead of USART1?

    • Anytime you want.

      • sel mesal

        Thanks Majerle. Are there are any limitations (capabilities that one might give up) by going with UART vs USART?

        • No, but USART in addition supports clock pin for synchronous communication. Check datasheet for more info!

  • Josh

    Hey there,
    I have downloaded your basic starter program for Keil that flashes the LEDs. This works fine. I then added your custom stdio.h and stdio.c libraries and this also compiled fine.
    I am now looking to add printf functionality and have therefore included your usart.c and usart.h libraries as above.
    I go to compile these and i get the following errors. any ideas as to what i may be doing wrong? thank you 🙂
    .TargetsSTM32F411_Discoveryproject.axf: Error: L6218E: Undefined symbol USART_DeInit (referred from tm_stm32f4_usart.o).
    .TargetsSTM32F411_Discoveryproject.axf: Error: L6218E: Undefined symbol USART_Init (referred from tm_stm32f4_usart.o).

  • AIYAPPA M G

    hallo ,
    after debugging in eclipse i am geting this error please help. MY source files are in the location. PLEASE HELP !!

    ////GNU gdb (GNU Tools for ARM Embedded Processors) 7.8.0.20150304-cvs
    Copyright (C) 2014 Free Software Foundation, Inc.
    License GPLv3+: GNU GPL version 3 or later
    This is free software: you are free to change and redistribute it.
    There is NO WARRANTY, to the extent permitted by law. Type “show copying”
    and “show warranty” for details.
    This GDB was configured as “–host=i686-w64-mingw32 –target=arm-none-eabi”.
    Type “show configuration” for configuration details.
    For bug reporting instructions, please see:
    .
    Find the GDB manual and other documentation resources online at:
    .
    For help, type “help”.
    Type “apropos word” to search for commands related to “word”.

    Warning: the current language does not match this frame.
    No source file named C:\ARM32\workspace\stm32f4_hands_on\src\timer.c.
    No source file named C:\ARM32\workspace\stm32f4_hands_on\src\usart.c.
    No line 15 in file “C:\ARM32\workspace\stm32f4_hands_on\include\usart.h”.

  • xD3monhunt3rx

    Hello
    I am trying to use your USART libraries to transmit and receive data with a bluetooth module. I am using an STM32F429I Disc1 board. The transmit works fine, but when ever I try use the serial monitor (TeraTerm) to send data to the board an infinite loop occurs. The loop is basically called when an unexpected interrupt occurs. I have set up my example exactly as you have done in your exampple, thus I do not know what the problem could be.

    Thanks

    • Hum, are you sure you did everything correct?

      • xD3monhunt3rx

        Yes. I am using a bunch of your other libraries as well but i dont think they would interfere. The PLL was correctly setup and I basically copypasted your code. It seems that the interrupt request is not being correctly called as i placed break points in it and the debugger never stopped at them. I have been successful in using the HAL libraries to do my application though. Thank you for the response.

  • G.H.ornil

    Hey Tilen
    I got this libs an main.c compiled without errors and I used Bray Terminal to see the transmitted “hello world” but I got only garbage values.

    • Means your baudrates don’t match. If you run example from ST, I’m sure you have wrong PLL clock.

      https://stm32f4-discovery.net/2015/01/properly-set-clock-speed-stm32f4xx-devices/

      • G.H.ornil

        I started to build the project from Default project for Keil uVision, then I add libs and modified the main.c code.

        • Then your baudrate don’t match in terminal and board.
          Check link I provide you. From default project, you also have to choose target to use.

          • G.H.ornil

            Can you help me out with clock setting for USART library, steps for clock setting would be enough me to manage. still I couldn’t get it done.

          • I gave you link for pll. Thats enough. Check if stm and pc grounds match, chech if baudrates are the same on pc and stm.