Как передать данные по uart keil c51

от admin

How to Retarget/Redirect printf & scanf to UART in KEIL

Debugging embedded systems can be frustrating at times. When debugging your embedded projects, won’t it be better if we can use C standard library functions like printf() ? Many of us have same questions in mind i.e. How to use printf in keil uvision? or How to retarget printf for my ARM microcontroller? Also, after learning UART programming an obvious though would be like, how can I redirect printf to UART/Serial port in keil and print the debug output on my PC using Terminal software? Well, in this Tutorial I will try to anwser these questions.

Low-Level I/O functions used by printf()

For ARM based Microcontrollers, C Standard library functions are supported via ARM C Library and Microlib. As with the standard library, printf() and scanf() are declared in stdio.h (Standard Input/Ouput header) file. Hence, the first thing to note is that we need to include stdio.h in your Keil projects. The printf() function depends on stream I/O function fputc() for printing on target device, depending on how fputc() is retargeted. Similarly scanf() function depends on fgetc() for fetching user input.

Bascially fputc() writes a character to a stream ( FILE * ). A stream represents a communication channel to either: a Device, File or Process. Generally when we want to display the output in console/terminal , the stream is either STDOUT or STDERR . Writing to either of the stream will divert or redirect the written characters to console output. Likewise fgetc() reads a character from a given stream. For getting input from user via a console, the stream used is STDIN .

Re-Implementing C Library functions for Retargeting printf()

So, our job now is rewrite fputc() and fgetc() so we can perform Output and Input from UART or Serial Port. These functions are in turn dependent on UART routines which are responsible for tranmission and reception of data characters (BYTEs). If you want to use ARM C Library which is default, then you must also redefine __FILE structure along with __stdout for fputc() and __stdin for fgetc() as given below:

Since we want to use printf to redirect output to UART/Serial port, the paramter stream is not required. As saw in the code above, to re-implement them we will need 2 basic UART functions: one to read and other to write a character. Hence, Lets define 2 functions viz. uartWrite() and uartRead() . Note that these are like driver functions which are device specific i.e. you need to rewite these functions for your specific microcontroller. I have given the code for LPC176x and LPC214x microcontrollers in Example section below. These can implemented for any ARM microcontroller of your choice like STM32, LPC13xx, LPC11xx etc in KEIL uVision.

The function call heirarchy:

And thats pretty much it. Now you can directly use printf redirected to UART in KEIL. Lets do some real world examples.

Retargeted printf() UART Examples

Redirect/Retarget printf() output using UART on ARM-Cortex-M3 LPC1768/LPC1769

In this example we will use UART0 of LPC176x MCU to redirect printf output running at a baud-rate of 115200. The uart routines used below are from my previous LPC1768 UART Tutorial. Here is screenshot of this example in action on LPC176x:

example showing retarget printf using UART on ARM

Redirect/Retarget printf() output using UART on ARM7 LPC2148

In this example we will use UART0 of LPC214x MCU to redirect printf() output and scanf() input. The baud-rate is configured to 9600 bauds. The UART functions for read and write are taken from my previous LPC2148 UART Tutorial.

Overview

When developing C/C++, we all need to print debugging information. When printing debugging information, we are accustomed to using the printf function, but in the Keil C51 environment, since our program is downloaded to the microcontroller, we cannot directly print to the serial port when using the printf function Above, this time we need to redirect the output of the printf function.

Redirect

Redirecting printf is very simple. We know that the printf function calls putchar to transfer character data. We just needRewrite putchar function, You can redirect the output of printf.

Code list

The following is the code list for testing the printf redirection function using the microcontroller STC12 in the Keil 5 environment

Open the serial port and adjust the baud rate to 115200bps, you can see that the serial port prints the following information:

Русские Блоги

C51 Микроконтроллер ———— Последовательный интерфейс

C51 Микроконтроллер ———— Последовательный интерфейс

Эй, брат, я изучаю последовательный интерфейс недавно?

Думаю об этом! Что со мной

Где не понимаю вау

количество! Не понимаю

1. Цитирование

Обмен информацией между компьютером и внешним миром называется коммуникацией.

Последовательный и параллельный

Существует два основных способа связи: последовательный и параллельный.
Последовательная связь: Этот метод связи отправляет / получает данные последовательно по битам (эквивалентно улице с односторонним движением на шоссе!)

Несколько линий передачи (еще одна линия для каждой передачи), дорого, подходит для передачи на короткие расстояния и высокая скорость передачи

Параллельное общение: Отправка / прием данных могут передаваться одновременно несколькими битами (сколько битов передается вместе, зависит от аппаратного устройства)

Требуется только одна или две линии передачи, дешевая, передача на большие расстояния, но скорость медленная (другие люди пропускают несколько раз за раз, если вы передаете по одной за раз, вы говорите, что это не медленно)

Синхронный и асинхронный

Как отличить это?
Различается в соответствии с форматом информации о кадре!
Синхронизировать:Насколько я понимаю, обе стороны коммуникации имеют одинаковую временную шкалу и общаются в строгом соответствии с этой временной шкалой.
1. Формат передачи данных: байт проверки непрерывной символьной проверки данных
2. Скорость выше, чем в асинхронном режиме, а структура оборудования высокая
асинхронный:Может рассматриваться как операции на разных временных шкалах
1. Формат данных связи: формат кадра с 11 битами данных: начальный бит-8 битов, бит данных, стоп-бит проверки данных (1 кадр == 11 бит)

Популярное понимание:
Каждый купил одежду! Покупка в торговом центре и покупка на сокровище — это как синхронные и асинхронные операции.
Когда вы покупаете одежду в торговом центре, вам нужно выбрать одежду. После того, как вы выбрали одежду, дайте официанту завернуть ее для вас, а затем закончите брать ее домой. Этот процесс продолжается.
А как насчет сокровища? Вам просто нужно выбрать одежду, оформить заказ и дождаться экспресс-доставки. Хотя одежда еще не доставлена ​​на дом, ваша задача по покупке одежды выполнена. После того, как продавец получит ваш заказ, он перейдет к организации доставки, конечно, все это не имеет к вам никакого отношения, вы уже заплатили, вы можете делать все, что захотите.
сумма. , , Кажется не популярным. , ,

Направление связи

Симплексная передача:Улица с односторонним движением, данные могут идти только в одном направлении!
Полудуплекс:Полосы, которые могут передаваться в обоих направлениях, но не могут использоваться в обоих направлениях одновременно
Полный дуплекс:Линия двусторонней передачи может быть отправлена ​​и получена одновременно.

Как передать данные по uart keil c51

ВЫЧ.ТЕХ / Лабораторные работы(Борисов) / Изучение последовательного порта UART

1 Изучить схему подключения микроконтроллера к компьютеру. 2 Изучить особенности работы последовательного асинхронного порта UART. 3 Освоить методику расчета скорости последовательного порта. 4 Изучить особенности программирования UART. 5 Изучить способы отладки программ на учебном лабораторном стенде LESO1.

2 Диаграмма передачи данных при помощи UART

Рисунок 2.1 – Диаграмма передачи данных при помощи последовательного порта.

3 Расчет параметров синхронизации

4 Графическая схема алгоритма программы

5 Исходный текст программы

6 Файл листинга

C51 COMPILER V8.12 LAB5 11/30/2011 17:17:03 PAGE 1

C51 COMPILER V8.12, COMPILATION OF MODULE LAB5

OBJECT MODULE PLACED IN Lab5.OBJ

COMPILER INVOKED BY: C:\Program Files\Keil\C51\BIN\C51.EXE Lab5.c BROWSE DEBUG OBJECTEXTEND SYMBOLS

line level source

2 sfr T3CON=0x9E;

C51 COMPILER V8.12 LAB5 11/30/2011 17:17:03 PAGE 2

NAME CLASS MSPACE TYPE OFFSET SIZE

T3FD . . . . . . . . . . . . . . . . . SFR DATA U_CHAR 009DH 1

TI . . . . . . . . . . . . . . . . . . ABSBIT —— BIT 0099H 1

main . . . . . . . . . . . . . . . . . PUBLIC CODE PROC 0000H ——

SBUF . . . . . . . . . . . . . . . . . SFR DATA U_CHAR 0099H 1

SCON . . . . . . . . . . . . . . . . . SFR DATA U_CHAR 0098H 1

T3CON. . . . . . . . . . . . . . . . . SFR DATA U_CHAR 009EH 1

MODULE INFORMATION: STATIC OVERLAYABLE

END OF MODULE INFORMATION.

C51 COMPILATION COMPLETE. 0 WARNING(S), 0 ERROR(S)

В ходе выполнения данной лабораторной работы я познакомился с особенностями последовательного порта UART микроконтроллера ADuC842. А именно:

— изучил схему подключения микроконтроллера к персональному компьютеру;

— изучил особенности последовательного порта UART, а также режимы его работы;

— научился конфигурировать последовательный порт UART при помощи регистра специальных функций SCON;

— познакомился с особенностями Таймера 3, научился его конфигурировать при помощи регистра специальных функций T3CON, а также использовать его для синхронизации работы последовательного порта UART;

— приобрел навыки по расчету скорости передачи последовательного порта;

— приобрел навыки по подключению стенда LESO1 к персональному компьютеру.

serial communication 8051 microcontroller using keil

In this tutorial, we will see a serial communication programming of 8051 microcontroller. when electronic devices communicate with each other, they can transfer data in two different ways. One is serial and the other one is parallel, When digital data is transferred serially, it is transmitted bit by bit, whereas in parallel transfer, many bits are transmitted at the same time. Though the parallel transfer of data is much faster but requires many wires. while a serial transfer is slower as compared to parallel transfer but requires few wires . Serial communication may be synchronous or asynchronous. In synchronous communication, the transmitter also transmits a clock along with data. This clock is used for synchronization between transmitter and receiver devices In an asynchronous transfer of data, there is no clock.

Introduction to SERIAL COMMUNICATION with 8051 microcontroller

serial communication may be simplex, half-duplex or full-duplex. simplex communication means that data will be transmitted only in one direction while half-duplex means data will be transmitted in both directions but at one time, only one device can transmit, whereas full-duplex means data may be transmitted in both directions at one time, while one device is transmitting, it can also receive data transmitted from other devices at same time. As I have mentioned before, the transmitter and receiver are configured to communicate at some data transfer rate before communication starts. This data transfer rate or a number of bits transmitted per second is called the baud rate for handling serial communication.

serial communication with microcontroller

Parallel communication is fast but it is not applicable for long distances (for printers). Moreover, it is also expensive. Serial is not much fast as parallel communication but it can deal with transmission of data over longer distances (for telephone line, ADC, DAC). It is also cheaper and requires less physical wires, that’s why we use serial communication. This article also deals with how to serially communicate in 8051 microcontroller.

METHODS OF SERIAL COMMUNICATION

serial communication types ASYNCHRONOUS and SYNCHRONOUS

There are two methods of Serial Communication:

SYNCHRONOUS: Transfer the block of data (characters) between sender and receiver spaced by fixed time interval. This transmission is synchronized by an external clock.

ASYNCHRONOUS: There is no clock involved here and transmission is synchronized by special signals along the transmission medium. It transfers a single byte at a time between sender and receiver along with inserting a start bit before each data character and a stop bit at its termination so that to inform the receiver where the data begins and ends. An example is the interface between a keyboard and a computer. Keyboard is the transmitter and the computer is the receiver. We use USART and UART for serial communications. USART or UART is a microcontroller peripheral which converts incoming and outgoing bytes of data into a serial bit stream. Both have same work but with different methods which is explained below.

USART:

USART stands for Universal Synchronous/Asynchronous Receiver-Transmitter. USART uses external clock so it needs separate line to carry the clock signal. Sending peripheral generates a clock and the receiving peripheral recover from the data stream without knowing the baud rate ahead of time. By use of external clock, USART’s data rate can be much higher (up to rates of 4 Mbps) than that of a standard UART.

It stands for Universal Asynchronous Receiver-Transmitter. A UART generates its internal data clock to the microcontroller. It synchronizes that clock with the data stream by using the start bit transition. The receiver needs the baud rate to know ahead of time to properly receive the data stream.

8051 SERIAL COMMUNICATION programming registers

8051 microcontroller has a built-in serial port called UART. We can easily read and write values to the serial port. For using serial port we simply need to configure the serial port:

  • Operation mode (how many data bits we want)
  • Baud rate

There are 21 Special function registers (SFR) in 8051 microcontroller and 21 unique locations are for these 21 SFR. Each of these register is of 1 byte size. The “Serial Control” (SCON) is the SFR which is used to configure serial port.

8051 serial communication SCON register

SCON SFR:

SM0: Serial port mode
Bit 0 of serial port mode.

SM1: Serial port mode
Bit 1 of serial port mode.

SM2: Enable multiprocessor
Enable multiprocessor communication in modes 2 and 3 (for 9 bit UART).

REN: Receiver Enable
Set/clear by software to enable/disable receive operation

TB8: Transmit bit 8
Set or clear by software. The 9 bits will be transmitted in mode 2 and 3.
TB8 = 1, a value is written to the serial port, 9 th bit of data = 1.
TB8 = 0, 9 th bit of data = 0, RI will not set.

RB8: Receive bit 8
Set or clear by software. The 9 bits will be received in mode 2 and 3. First eight bits are the data received and 9 th bit received will be placed in RB8.

TI: Transmit Interrupt flag
Set by hardware when a byte is transmitted completely. Now the port is free and ready to send the next byte. This bit must be cleared by software.

RI: Receive Interrupt flag
Set by hardware when a byte has been completely received. This lets the program to know that it needs to read the value quickly before another byte is read. This bit must be cleared by software.

CONFIGURATION SETTINGS
  • Setting Operation Mode of Serial Port:

The Upper four bits are configuration bits. SM0 and SM1 set the serial mode between 0 and 3. The four modes along with the baud rates are in the table given below. In modes 0 and 2 the baud rate is fixed which is based on the oscillator frequency. In modes 1 and 3 the baud rate is variable which depends on how often Timer 1 overflows.

SM2 is a flag bit for Multiprocessor communication. When SM2 is set, the 8051 microcontroller will set the RI (Receive Interrupt) flag whenever a byte is received (if the 9th bit received is “1”). By this way, program knows that a byte has been received and it needs to be processed. If 9th bit is clear, the RI flag will never be set. We will clear this RI bit so that the flag is set upon reception of any character.

If SM2=1, RI=1 (only if 9 th bit of received byte is 1)

REN is Receiver Enable bit. Set this bit if we want to receive data through serial port.

REN=1 (for serial communication)

  • Setting the Baud Rate of Serial Port:

Baud Rate:

It is defined as number of bits transmitted or received per second and is usually expressed in Bits per second bps. After setting the operation mode of serial port, the program must configure the serial ports baud rate which is only applicable to Serial Port modes 1 and 3. For mode 0 and 2 oscillator frequency determines the Baud Rate.

For mode 0:

Baud rate is always the oscillator frequency divided by 12. For crystal of frequency 11.059MHz, Baud rate will be 921,583 baud.

Baud rate = (11.0592MHz/12) = 921,583 baud

For mode 2:

Baud rate is always the oscillator frequency divided by 64. For crystal of frequency 11.059MHz, Baud rate will be 172,797 baud.

Baud rate == (11.0592MHz/64) = 172,797 baud

For mode 1 and 3:

For them, the baud rate is determined by how frequently timer 1 overflows. The more frequent timer 1 overflows, the higher the baud rate. There are many ways due to which timer 1 overflows at a rate that determines a baud rate. The most common method is:

  • We put timer 1 in 8-bit auto-reload mode (timer mode 2).
  • This 8 bit timer that allows only values of 00 to FFH loaded in timer register TH1.
  • Set a reload value in TH1 that causes Timer 1 to overflow at a frequency appropriate to generate a baud rate.
  • If PCON.7 is clear (SMOD=0), then to generate a given baud rate, the value to be put in TH1 can be determined from an equation:

TH1 = 256 – ((Crystal / 384) / Baud)

  • If the value to be load in TH1 by above equation is not in whole number then we can’t get accurate baud rate. For that case, set PCON.7 (SMOD=1). The baud rate gets double and the equation becomes:

TH1 = 256 – ((Crystal / 192) / Baud)

How to calculate baud rate for serial communication in 8051 microcontroller

Let us take an example. If we have crystal of frequency 11.059MHz and we want to configure the serial port to 19,200 baud rate, firstly we try equation 1. By using equation 1:

TH1 = 256 – ((Crystal / 384) / Baud)
TH1 = 256 – ((11.059MHz/ 384) / 19200 )
TH1 = 256 – 1.5 = 254.5

By setting 254 and 255, we don’t achieve accurate baud rate so we need to set PCON.7 (SMOD=1). This doubles the baud rate and we will use equation 2 for determining TH1 value. By using equation 2:

TH1 = 256 – ((Crystal / 192) / Baud)
TH1 = 256 – ((11.059MHz/ 192) / 19200)
TH1 = 256 – 3 = 253

Thus by setting TH1 to 253 we get correct frequency for 19,200 baud rate.

Example of serial communication programming using Mikro C for 8051

If you do not want to do complicated programming using serial communications registers, you can simply use Mikro c compiler which has built in libraries for the UART communication. Now I will explain about UART programming through mikro c and after that I will provide an example of UART in keil compiler. We can use built-in UART library for handling 8051 serial communication, there are several functions . In this library.

  • UART_init() is used for initialization of 8051 UART module
  • UART_init() is used for initialization of 8051 UART module
  • UART_data_read() function checks if some data received on serial Port
  • UART_data_read() function checks if some data received on serial Port, UART_read() reads one byte from serial port
  • whereas UART_Read_Text() can read multiple bytes
  • UART_Write() writes one byte to serial port. UART_Write() writes one byte to serial port
  • while UART_Write_Text() can write multiple bytes.
  • UART_Set_Active() function is only used in micro-controllers that support more than one UART ports.

In above we are transmitting data through UART port and also displaying same data on LCD. If you don’t know how to display data on LCD, you can check tutorial here. Now lets see the explanation of code.

  • First we initialized serial port at 9600 baud rate using UART_Init() function.
  • Next we need to Clear SMOD bit of PCON register
  • Actually there is some bug in uart_init() function of UART library, it writes HIGH to SMOD bit that causes erroneous baud rate.
  • we can send some string to serial port with uart_write_text() function.
  • Now in while(1) loop, we are sending “P0+P1” string to serial port with uart_write_text function.
  • now we can send same text array to serial port that is being display on character LCD.
  • At the end, we are sending new line character, OK code is now ready we can compile and test it.
  • It is recommended to select 11.0592MHz crystal frequency for using serial port 11.0592MHz crystal frequency can give exact clock rates for most of the common baud rates for the UART.
  • we can use virtual terminal in Proteus for testing serial communication.
  • TX pin of 8051 will be connected to RX of virtual terminal.
  • In virtual terminal of proteus, you have to enter same baud rate as configured in your code.
  • When you run the code, You will see, sum of P0 & P1 is appearing on virtual terminal,
Example of serial communication 8051 microcontroller in Keil

8051 microcontroller is used in the schematic. Crystal frequency is set to 11.059MHz. Baud rate used is 9600. A virtual terminal is used. The data coming from transmitter pin of controller will be displayed on virtual terminal. The send to the microcontroller is also received on receiver pin of controller which is sent through virtual terminal by pressing specific key. The program is such that the baud rate is set to 9600.

For 9600 baud rate:

TH1 = 256 – ((Crystal / 384) / Baud)
TH1 = 256 – ((11.59MHz/ 384) / 9600 )
TH1 = 256 – 3 = 253

The Hex value of 253 is FD which should be loaded to TH1

  • Port 3 pin 0 receiver pin is connected to TX of virtual terminal.
  • Port 3 pin 1 transmitter pin is connected to RX of virtual terminal.
  • Port 1 lower four pins are connected with 4 LEDs.

PROTEUS SCHEMATIC:

WORKING of serial communication 8051 microcontroller

By pressing key 1, 1 st LED will glow and when key “a” is pressed, it goes off.

By pressing key 2, 2 nd LED will glow and when key “b” is pressed, it goes off.

By pressing key 3, 3 rd LED will glow and when key “c” is pressed, it goes off.

By pressing key 4, 4 th LED will glow and when key “d” is pressed, it goes off.

Как передать данные по uart keil c51

How to Retarget/Redirect printf & scanf to UART in KEIL

Debugging embedded systems can be frustrating at times. When debugging your embedded projects, won’t it be better if we can use C standard library functions like printf() ? Many of us have same questions in mind i.e. How to use printf in keil uvision? or How to retarget printf for my ARM microcontroller? Also, after learning UART programming an obvious though would be like, how can I redirect printf to UART/Serial port in keil and print the debug output on my PC using Terminal software? Well, in this Tutorial I will try to anwser these questions.

Low-Level I/O functions used by printf()

For ARM based Microcontrollers, C Standard library functions are supported via ARM C Library and Microlib. As with the standard library, printf() and scanf() are declared in stdio.h (Standard Input/Ouput header) file. Hence, the first thing to note is that we need to include stdio.h in your Keil projects. The printf() function depends on stream I/O function fputc() for printing on target device, depending on how fputc() is retargeted. Similarly scanf() function depends on fgetc() for fetching user input.

Bascially fputc() writes a character to a stream ( FILE * ). A stream represents a communication channel to either: a Device, File or Process. Generally when we want to display the output in console/terminal , the stream is either STDOUT or STDERR . Writing to either of the stream will divert or redirect the written characters to console output. Likewise fgetc() reads a character from a given stream. For getting input from user via a console, the stream used is STDIN .

Re-Implementing C Library functions for Retargeting printf()

So, our job now is rewrite fputc() and fgetc() so we can perform Output and Input from UART or Serial Port. These functions are in turn dependent on UART routines which are responsible for tranmission and reception of data characters (BYTEs). If you want to use ARM C Library which is default, then you must also redefine __FILE structure along with __stdout for fputc() and __stdin for fgetc() as given below:

Since we want to use printf to redirect output to UART/Serial port, the paramter stream is not required. As saw in the code above, to re-implement them we will need 2 basic UART functions: one to read and other to write a character. Hence, Lets define 2 functions viz. uartWrite() and uartRead() . Note that these are like driver functions which are device specific i.e. you need to rewite these functions for your specific microcontroller. I have given the code for LPC176x and LPC214x microcontrollers in Example section below. These can implemented for any ARM microcontroller of your choice like STM32, LPC13xx, LPC11xx etc in KEIL uVision.

The function call heirarchy:

And thats pretty much it. Now you can directly use printf redirected to UART in KEIL. Lets do some real world examples.

Retargeted printf() UART Examples
Redirect/Retarget printf() output using UART on ARM-Cortex-M3 LPC1768/LPC1769

In this example we will use UART0 of LPC176x MCU to redirect printf output running at a baud-rate of 115200. The uart routines used below are from my previous LPC1768 UART Tutorial. Here is screenshot of this example in action on LPC176x:

Читать:
Что такое круговая поляризация света

example showing retarget printf using UART on ARM

Redirect/Retarget printf() output using UART on ARM7 LPC2148

In this example we will use UART0 of LPC214x MCU to redirect printf() output and scanf() input. The baud-rate is configured to 9600 bauds. The UART functions for read and write are taken from my previous LPC2148 UART Tutorial.

ARM Учебный курс. USART

  • Однопроводном полудуплексном режиме
  • В режиме SmartCard — т.е. на том же языке на котором общаются с телефоном SIM карты. Вообще там вроде бы протокол отличается только таймингами немного
  • В режиме IrDA — помните на старых телефонах была такая фиговина? Вот это оно. Отличается от обычного протокола тем, что тут данные передаются краткими импульсами. Этакими вспышками. А 0 и 1 ловятся по паузам между ними. Так себя фотоприемники видать лучше чувствуют.
  • Также есть LIN режим. LIN это автомобильная сеть, этакий CAN для бедных. Вон во всяких приорах стекла и сигналки на LIN шине сидят.

Не все блоки одинаково могучи, зависит от номера. А количество блоков зависит от модели проца. Чем жирней проц, чем больше у него ног, тем больше у него блоков USART. Всего их может быть 6 и в зависимости от номера умеют они следующее:

▌Регистры
USART_SR Status Register. Регистр состояния автомата передатчика. Тут все флаги по которым можно понять, что происходит вообще с передачей данных.

  • CTS — ставится в 1 когда идет запрос на прием данных по линии CTS. Если конечно это разрешено в настройках битом CTSE. Также по этому флажку генерируется прерывание. Сбрасывается вручную.
  • LBD — LIN Break flag. Какой то запрос от LIN шины. Сбрасывается вручную, умеет выдавать прерывание.
  • TXE — Tx Empty. Передатчик пуст, можно кидать следующий байт. Может сгенерировать прерывание. Сбрасывается сам, когда записываем в USART_DR.
  • TC — Transmit Complete. Передача завершена. От TXE отличается тем, что у нас не просто буфер пустой, а еще и сдвиговый регистр отстрелялся. Может генерировать прерывание. Сбрасывается либо вручную, либо автоматически при чтении из USART_SR с последующей записью в USART_DR.
  • RXNE — Read data register not empty. Что то нам на вход пришло и можно забирать. Генерит прерывание и сбрасыватся либо ручками, либо чтением из USART_DR регистра.
  • IDLE — IDLE line detected. Линия свободна, можно вещать. Может генерировать прерывание и сбрасывается чтением сначала USART_SR, потом USART_DR. Думаю это можно трактовать как конец приема. Когда данные пришли и новых на линии нет.
  • ORE — Overrun error. Просрали байт. Сливай воду. Выскакивает когда данные не успеваем считывать, а новые все лезут и лезут. Генерирует прерывание (куда же без него) и сбрасывается когда мы сначала читаем регистр статуса, а потом заглядываем в регистр данных. Причем тут есть нюанс. Убиваются входящие данные только в сдвиговом регистре. Т.е. пока мы сами не прочитаем данные из регистра данных им ничего не грозит.
  • NE — Noise error flag. Срач в линии. Тоже есть прерывание. Сбрасывается точно также как и ORE.
  • FE — Frame Error. Ошибка кадра. Это если данные побились по ходу. Ну например, частота если плавает у передатчика и в линию идет какая то странная фигня. Ведь USART асинхронный и там все на время завязано. Дает прерывание, сбрасывается точно также как и ORE.
  • PE — Parity Error. Ошибка контроля четности. Очищается также как и прошлые три, но тут надо перед сборосом подождать пока встанет бит RXNE. Дает прерывание. Кто бы сомневался 🙂

USART_CR1 — регистр настроек.

  • UE — USART Enable — включить USART блок.
  • M — длина байта. 1 = 9 бит. 0 = 8 бит. Изначально 0
  • WAKE — какой то бит пробуждения (Из Sleep mode?) 0 = по свободной линии, 1 = по совпадению адреса. Что-то связанное с мультиконтроллерной связью.
  • PCE — Parity control enable. Контроль четности, если =1 то четность проверяется.
  • PS — Parity selection. Тип контроля четности. 0 = проверяем на четность. 1 = проверка на нечетность.
  • PEIE — PE interrupt enable. Включение прерывания по четности (флагу PE регистра состояния уарта).
  • TXEIE — TXE interrupt enable. Включение прерывания по опустошению буфера передатчика.
  • TCIE — Transmission complete interrupt enable. Включение прерывания по окончании передачи.
  • RXNEIE — RXNE interrupt enable. Включение прерывания по приему байта.
  • IDLEIE — IDLE interrupt enable. Включение прерывания по окончанию приема (освобождение линии)
  • TE — Transmitter enable. Включить передатчик.
  • RE — Receiver enable. Включить приемник.
  • RWU — Receiver wakeup. Что то с пробуждением по приходу.
  • SBK — Send break. Послать символ прерывания. Ставим этот бит и уарт отрыгивает в линию код BREAK и после сам снимает бит.

USART_CR2 — регистр настроек

  • LINEN — LIN mode enable. Режим LIN шины.
  • STOP[1:0] — два бита определяющие тип стоп бита. 00 = 1 стоп бит, 01 = полубит, 10 = 2 бита, 11 — полтора бита.
  • CLKEN — Clock enable. Разрешение CK входа. Это для синхронной передачи.
  • CPOL — Clock polarity. Полярность CK линии. Что там будет принято за готовность 0 или 1, соответственно.
  • CPHA — Clock phase. Фаза СК синхролинии. По первому дрыгу пойдут данные (0) или по второму (1).
  • LBCL — Last bit clock pulse. Что то там с последним дрыгом синхролинии при синхронной передаче.
  • LBDIE — LIN break detection interrupt enable. Разрешение прерывания от LIN шины.
  • LBDL — lin break detection length. Длина этого сигнала от LIN шины.
  • ADD[3:0] — Address of the USART node. Адрес на шине, для мультипроцессорной коммуникации.

USART_CR3 — регистр настроек

  • CTSIE — CTS interrupt enable. Разрешение прерывания от CTS
  • CTSE — CTS enable. Просто разрешение использования CTS входа.
  • RTSE — RTS enable. Разрешение использования RTS выхода.
  • DMAT — DMA enable transmitter. Разрешение DMA для передатчика.
  • DMAR — DMA enable receiver. Разрешение DMA для приемника.
  • SCEN — Smartcard mode enable. Режим работы со смарткартами.
  • NACK — Smartcard NACK enable. Разрешение передачи ошибки четности для смарткарт.
  • HDSEL — Half-duplex selection. Полудуплексный режим.
  • IRLP — IrDA low-power. Выбор режима работы IrDA. 1 = маломощный, 0 — обычный режим.
  • IREN — IrDA mode enable. Включение режима ИК передачи данных.
  • EIE — Error interrupt enable. Разрешение прерываний от ошибок. Это FE, ORE, NE)

DCD USART1_IRQHandler ; USART1 DCD USART2_IRQHandler ; USART2 DCD USART3_IRQHandler ; USART3

RCC->APB2ENR |= RCC_APB2ENR_USART1EN; //USART1 Clock ON

USART1->BRR = 0xEA6; // Bodrate for 19200 on 72Mhz

USART1->CR1 |= USART_CR1_UE | USART_CR1_TE | USART_CR1_RE; // USART1 ON, TX ON, RX ON

RCC->APB2ENR |= RCC_APB2ENR_IOPAEN | RCC_APB2ENR_AFIOEN; // GPIOA Clock ON. Alter function clock ON GPIOA->CRH &=

GPIO_CRH_CNF9; // Clear CNF bit 9 GPIOA->CRH |= GPIO_CRH_CNF9_1; // Set CNF bit 9 to 10 — AFIO Push-Pull GPIOA->CRH |= GPIO_CRH_MODE9_0; // Set MODE bit 9 to Mode 01 = 10MHz

GPIO_CRH_CNF10; // Clear CNF bit 9 GPIOA->CRH |= GPIO_CRH_CNF10_0; // Set CNF bit 9 to 01 = HiZ GPIOA->CRH &=

GPIO_CRH_MODE10; // Set MODE bit 9 to Mode 01 = 10MHz


Вуаля!

GPIO_CRH_CNF9; // Clear CNF bit 9 GPIOA->CRH |= GPIO_CRH_CNF9_1; // Set CNF bit 9 to 10 — AFIO Push-Pull GPIOA->CRH |= GPIO_CRH_MODE9_0; // Set MODE bit 9 to Mode 01 = 10MHz RCC->APB2ENR |= RCC_APB2ENR_USART1EN; // USART1 Clock ON USART1->BRR = 0xEA6; // Bodrate for 19200 on 72Mhz USART1->CR1 |= USART_CR1_UE | USART_CR1_TE | USART_CR1_RE; // USART1 ON, TX ON, RX ON USART1->DR = 10; // Send Byte! // Config CRL GPIOB->CRL &=

GPIO_CRL_CNF5; // Clear CNF bit 5. Mode 00 — Push-Pull GPIOB->CRL |= GPIO_CRL_MODE5_0; // Set bit MODE for pin 5. Mode 01 = Max Speed 10MHz while(1) >

USART1->CR1 |= USART_CR1_UE | USART_CR1_TE | USART_CR1_RE | // USART1 ON, TX ON, RX ON USART_CR1_RXNEIE; // RXNE Int ON

GPIO_CRH_CNF9; // Clear CNF bit 9 GPIOA->CRH |= GPIO_CRH_CNF9_1; // Set CNF bit 9 to 10 — AFIO Push-Pull GPIOA->CRH |= GPIO_CRH_MODE9_0; // Set MODE bit 9 to Mode 01 = 10MHz // SET RX1 GPIOA->CRH &=

GPIO_CRH_CNF10; // Clear CNF bit 9 GPIOA->CRH |= GPIO_CRH_CNF10_0; // Set CNF bit 9 to 01 HiZ GPIOA->CRH &=

GPIO_CRH_MODE10; // Set MODE bit 9 to Mode 01 = 10MHz // SET USART1 REG RCC->APB2ENR |= RCC_APB2ENR_USART1EN; // USART1 Clock ON USART1->BRR = 0xEA6; // Baudrate for 19200 on 72Mhz USART1->CR1 |= USART_CR1_UE | USART_CR1_TE | USART_CR1_RE | // USART1 ON, TX ON, RX ON USART_CR1_RXNEIE; // RXNE Int ON // USART2 Settings // SET TX2 GPIOA->CRL &=

GPIO_CRL_CNF2; // Clear CNF bit 2 GPIOA->CRL |= GPIO_CRL_CNF2_1; // Set CNF bit 2 to 10 — AFIO Push-Pull GPIOA->CRL |= GPIO_CRL_MODE2_0; // Set MODE bit 2 to Mode 01 = 10MHz // SET RX2 GPIOA->CRL &=

GPIO_CRL_CNF3; // Clear CNF bit 3 GPIOA->CRL |= GPIO_CRL_CNF3_0; // Set CNF bit 3 to 01 HiZ GPIOA->CRL &=

GPIO_CRL_MODE3; // Set MODE bit 3 to Mode 01 = 10MHz // SET USART2 REG RCC->APB1ENR |= RCC_APB1ENR_USART2EN; // USART2 Clock ON USART2->BRR = 0x753; // Baudrate for 19200 on 36Mhz USART2->CR1 |= USART_CR1_UE | USART_CR1_TE | USART_CR1_RE | // USART2 ON, TX ON, RX ON USART_CR1_RXNEIE; // USART3 Settings // SET TX3 GPIOB->CRH &=

GPIO_CRH_CNF10; // Clear CNF bit 9 GPIOB->CRH |= GPIO_CRH_CNF10_1; // Set CNF bit 9 to 10 — AFIO Push-Pull GPIOB->CRH |= GPIO_CRH_MODE10_0; // Set MODE bit 9 to Mode 01 = 10MHz // SET RX3 GPIOB->CRH &=

GPIO_CRH_CNF11; // Clear CNF bit 9 GPIOB->CRH |= GPIO_CRH_CNF11_0; // Set CNF bit 9 to 01 HiZ GPIOB->CRH &=

GPIO_CRH_MODE11; // Set MODE bit 9 to Mode 01 = 10MHz // SET USART3 REG RCC->APB1ENR |= RCC_APB1ENR_USART3EN; // USART3 Clock ON USART3->BRR = 0x753; // Baudrate for 19200 on 36Mhz USART3->CR1 |= USART_CR1_UE | USART_CR1_TE | USART_CR1_RE | // USART3 ON, TX ON, RX ON USART_CR1_RXNEIE; //UART INT ON NVIC_EnableIRQ (USART1_IRQn); NVIC_EnableIRQ (USART2_IRQn); NVIC_EnableIRQ (USART3_IRQn); __enable_irq (); while(1) >

Запускаем первый байт…

39 thoughts on “ARM Учебный курс. USART”

Передача данных по UART из stm на ПК

serial communication 8051 microcontroller using keil

In this tutorial, we will see a serial communication programming of 8051 microcontroller. when electronic devices communicate with each other, they can transfer data in two different ways. One is serial and the other one is parallel, When digital data is transferred serially, it is transmitted bit by bit, whereas in parallel transfer, many bits are transmitted at the same time. Though the parallel transfer of data is much faster but requires many wires. while a serial transfer is slower as compared to parallel transfer but requires few wires . Serial communication may be synchronous or asynchronous. In synchronous communication, the transmitter also transmits a clock along with data. This clock is used for synchronization between transmitter and receiver devices In an asynchronous transfer of data, there is no clock.

Table of Contents

Introduction to SERIAL COMMUNICATION with 8051 microcontroller

serial communication may be simplex, half-duplex or full-duplex. simplex communication means that data will be transmitted only in one direction while half-duplex means data will be transmitted in both directions but at one time, only one device can transmit, whereas full-duplex means data may be transmitted in both directions at one time, while one device is transmitting, it can also receive data transmitted from other devices at same time. As I have mentioned before, the transmitter and receiver are configured to communicate at some data transfer rate before communication starts. This data transfer rate or a number of bits transmitted per second is called the baud rate for handling serial communication.

serial communication with microcontroller

Parallel communication is fast but it is not applicable for long distances (for printers). Moreover, it is also expensive. Serial is not much fast as parallel communication but it can deal with transmission of data over longer distances (for telephone line, ADC, DAC). It is also cheaper and requires less physical wires, that’s why we use serial communication. This article also deals with how to serially communicate in 8051 microcontroller.

METHODS OF SERIAL COMMUNICATION

serial communication types ASYNCHRONOUS and SYNCHRONOUS

There are two methods of Serial Communication:

SYNCHRONOUS: Transfer the block of data (characters) between sender and receiver spaced by fixed time interval. This transmission is synchronized by an external clock.

ASYNCHRONOUS: There is no clock involved here and transmission is synchronized by special signals along the transmission medium. It transfers a single byte at a time between sender and receiver along with inserting a start bit before each data character and a stop bit at its termination so that to inform the receiver where the data begins and ends. An example is the interface between a keyboard and a computer. Keyboard is the transmitter and the computer is the receiver. We use USART and UART for serial communications. USART or UART is a microcontroller peripheral which converts incoming and outgoing bytes of data into a serial bit stream. Both have same work but with different methods which is explained below.

USART:

USART stands for Universal Synchronous/Asynchronous Receiver-Transmitter. USART uses external clock so it needs separate line to carry the clock signal. Sending peripheral generates a clock and the receiving peripheral recover from the data stream without knowing the baud rate ahead of time. By use of external clock, USART’s data rate can be much higher (up to rates of 4 Mbps) than that of a standard UART.

It stands for Universal Asynchronous Receiver-Transmitter. A UART generates its internal data clock to the microcontroller. It synchronizes that clock with the data stream by using the start bit transition. The receiver needs the baud rate to know ahead of time to properly receive the data stream.

8051 SERIAL COMMUNICATION programming registers

8051 microcontroller has a built-in serial port called UART. We can easily read and write values to the serial port. For using serial port we simply need to configure the serial port:

  • Operation mode (how many data bits we want)
  • Baud rate

There are 21 Special function registers (SFR) in 8051 microcontroller and 21 unique locations are for these 21 SFR. Each of these register is of 1 byte size. The “Serial Control” (SCON) is the SFR which is used to configure serial port.

8051 serial communication SCON register

SCON SFR:

SM0: Serial port mode
Bit 0 of serial port mode.

SM1: Serial port mode
Bit 1 of serial port mode.

SM2: Enable multiprocessor
Enable multiprocessor communication in modes 2 and 3 (for 9 bit UART).

REN: Receiver Enable
Set/clear by software to enable/disable receive operation

TB8: Transmit bit 8
Set or clear by software. The 9 bits will be transmitted in mode 2 and 3.
TB8 = 1, a value is written to the serial port, 9 th bit of data = 1.
TB8 = 0, 9 th bit of data = 0, RI will not set.

RB8: Receive bit 8
Set or clear by software. The 9 bits will be received in mode 2 and 3. First eight bits are the data received and 9 th bit received will be placed in RB8.

TI: Transmit Interrupt flag
Set by hardware when a byte is transmitted completely. Now the port is free and ready to send the next byte. This bit must be cleared by software.

RI: Receive Interrupt flag
Set by hardware when a byte has been completely received. This lets the program to know that it needs to read the value quickly before another byte is read. This bit must be cleared by software.

CONFIGURATION SETTINGS
  • Setting Operation Mode of Serial Port:

The Upper four bits are configuration bits. SM0 and SM1 set the serial mode between 0 and 3. The four modes along with the baud rates are in the table given below. In modes 0 and 2 the baud rate is fixed which is based on the oscillator frequency. In modes 1 and 3 the baud rate is variable which depends on how often Timer 1 overflows.

SM2 is a flag bit for Multiprocessor communication. When SM2 is set, the 8051 microcontroller will set the RI (Receive Interrupt) flag whenever a byte is received (if the 9th bit received is “1”). By this way, program knows that a byte has been received and it needs to be processed. If 9th bit is clear, the RI flag will never be set. We will clear this RI bit so that the flag is set upon reception of any character.

If SM2=1, RI=1 (only if 9 th bit of received byte is 1)

REN is Receiver Enable bit. Set this bit if we want to receive data through serial port.

REN=1 (for serial communication)

  • Setting the Baud Rate of Serial Port:

Baud Rate:

It is defined as number of bits transmitted or received per second and is usually expressed in Bits per second bps. After setting the operation mode of serial port, the program must configure the serial ports baud rate which is only applicable to Serial Port modes 1 and 3. For mode 0 and 2 oscillator frequency determines the Baud Rate.

For mode 0:

Baud rate is always the oscillator frequency divided by 12. For crystal of frequency 11.059MHz, Baud rate will be 921,583 baud.

Baud rate = (11.0592MHz/12) = 921,583 baud

For mode 2:

Baud rate is always the oscillator frequency divided by 64. For crystal of frequency 11.059MHz, Baud rate will be 172,797 baud.

Baud rate == (11.0592MHz/64) = 172,797 baud

For mode 1 and 3:

For them, the baud rate is determined by how frequently timer 1 overflows. The more frequent timer 1 overflows, the higher the baud rate. There are many ways due to which timer 1 overflows at a rate that determines a baud rate. The most common method is:

  • We put timer 1 in 8-bit auto-reload mode (timer mode 2).
  • This 8 bit timer that allows only values of 00 to FFH loaded in timer register TH1.
  • Set a reload value in TH1 that causes Timer 1 to overflow at a frequency appropriate to generate a baud rate.
  • If PCON.7 is clear (SMOD=0), then to generate a given baud rate, the value to be put in TH1 can be determined from an equation:

TH1 = 256 – ((Crystal / 384) / Baud)

  • If the value to be load in TH1 by above equation is not in whole number then we can’t get accurate baud rate. For that case, set PCON.7 (SMOD=1). The baud rate gets double and the equation becomes:

TH1 = 256 – ((Crystal / 192) / Baud)

How to calculate baud rate for serial communication in 8051 microcontroller

Let us take an example. If we have crystal of frequency 11.059MHz and we want to configure the serial port to 19,200 baud rate, firstly we try equation 1. By using equation 1:

TH1 = 256 – ((Crystal / 384) / Baud)
TH1 = 256 – ((11.059MHz/ 384) / 19200 )
TH1 = 256 – 1.5 = 254.5

By setting 254 and 255, we don’t achieve accurate baud rate so we need to set PCON.7 (SMOD=1). This doubles the baud rate and we will use equation 2 for determining TH1 value. By using equation 2:

TH1 = 256 – ((Crystal / 192) / Baud)
TH1 = 256 – ((11.059MHz/ 192) / 19200)
TH1 = 256 – 3 = 253

Thus by setting TH1 to 253 we get correct frequency for 19,200 baud rate.

Example of serial communication programming using Mikro C for 8051

If you do not want to do complicated programming using serial communications registers, you can simply use Mikro c compiler which has built in libraries for the UART communication. Now I will explain about UART programming through mikro c and after that I will provide an example of UART in keil compiler. We can use built-in UART library for handling 8051 serial communication, there are several functions . In this library.

  • UART_init() is used for initialization of 8051 UART module
  • UART_init() is used for initialization of 8051 UART module
  • UART_data_read() function checks if some data received on serial Port
  • UART_data_read() function checks if some data received on serial Port, UART_read() reads one byte from serial port
  • whereas UART_Read_Text() can read multiple bytes
  • UART_Write() writes one byte to serial port. UART_Write() writes one byte to serial port
  • while UART_Write_Text() can write multiple bytes.
  • UART_Set_Active() function is only used in micro-controllers that support more than one UART ports.

In above we are transmitting data through UART port and also displaying same data on LCD. If you don’t know how to display data on LCD, you can check tutorial here. Now lets see the explanation of code.

  • First we initialized serial port at 9600 baud rate using UART_Init() function.
  • Next we need to Clear SMOD bit of PCON register
  • Actually there is some bug in uart_init() function of UART library, it writes HIGH to SMOD bit that causes erroneous baud rate.
  • we can send some string to serial port with uart_write_text() function.
  • Now in while(1) loop, we are sending “P0+P1” string to serial port with uart_write_text function.
  • now we can send same text array to serial port that is being display on character LCD.
  • At the end, we are sending new line character, OK code is now ready we can compile and test it.
  • It is recommended to select 11.0592MHz crystal frequency for using serial port 11.0592MHz crystal frequency can give exact clock rates for most of the common baud rates for the UART.
  • we can use virtual terminal in Proteus for testing serial communication.
  • TX pin of 8051 will be connected to RX of virtual terminal.
  • In virtual terminal of proteus, you have to enter same baud rate as configured in your code.
  • When you run the code, You will see, sum of P0 & P1 is appearing on virtual terminal,
Example of serial communication 8051 microcontroller in Keil

8051 microcontroller is used in the schematic. Crystal frequency is set to 11.059MHz. Baud rate used is 9600. A virtual terminal is used. The data coming from transmitter pin of controller will be displayed on virtual terminal. The send to the microcontroller is also received on receiver pin of controller which is sent through virtual terminal by pressing specific key. The program is such that the baud rate is set to 9600.

For 9600 baud rate:

TH1 = 256 – ((Crystal / 384) / Baud)
TH1 = 256 – ((11.59MHz/ 384) / 9600 )
TH1 = 256 – 3 = 253

The Hex value of 253 is FD which should be loaded to TH1

  • Port 3 pin 0 receiver pin is connected to TX of virtual terminal.
  • Port 3 pin 1 transmitter pin is connected to RX of virtual terminal.
  • Port 1 lower four pins are connected with 4 LEDs.

PROTEUS SCHEMATIC:

WORKING of serial communication 8051 microcontroller

By pressing key 1, 1 st LED will glow and when key “a” is pressed, it goes off.

By pressing key 2, 2 nd LED will glow and when key “b” is pressed, it goes off.

By pressing key 3, 3 rd LED will glow and when key “c” is pressed, it goes off.

By pressing key 4, 4 th LED will glow and when key “d” is pressed, it goes off.

How to Interface UART with 8051

Hi guys, in this article we will see how to interface uart with 8051 using Keil IDE and runs in the proteus software. Let’s get started.

One of the 8051s many powerful features is its integrated UART, otherwise known as a serial port. The fact that the 8051 has an integrated serial port means that you may very easily read and write values to the serial port. If it were not for the integrated serial port, writing a byte to a serial line would be a rather tedious process requiring turning on and off one of the I/O lines in rapid succession to properly “clock out” each individual bit, including start bits, stop bits, and parity bits.

However, we do not have to do this. Instead, we simply need to configure the serial ports operation mode and baud rate. Once configured, all we have to do is write to an SFR to write a value to the serial port or read the same SFR to read a value from the serial port. The 8051 will automatically let us know when it has finished sending the character we wrote and will also let us know whenever it has received a byte so that we can process it. We do not have to worry about transmission at the bit level–which saves us quite a bit of coding and processing time.

Setting the Serial Port Mode

The first thing we must do when using the 8051s integrated serial port is, obviously, configure it. This lets us tell the 8051 how many data bits we want, the baud rate we will be using, and how the baud rate will be determined.

First, lets present the “Serial Control” (SCON) SFR and define what each bit of the SFR represents:

UART Receive

Thanks for reading this article for any assistance or doubts comment below.

Похожие публикации