Detailed explanation of AVR serial communication

Publisher:数据舞者Latest update time:2015-12-30 Source: eefocusKeywords:AVR Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere
1. Familiar with AVR microcontroller UART resources, starting with baud rate and frame

 Baud rate: Different from 51, it has a separate baud rate generator, which does not require a timer to generate, saving resources.
         Baud rate calculation formula, here I use the configuration function of IccAVR to directly calculate and generate
      . Modes supported by the microcontroller: asynchronous normal mode, asynchronous multiple mode, and synchronous mode, generally the first mode is selected.
 Frame format: start bit + data bit (5-9 bits optional) + check bit (optional) + stop bit (1, 2 bits)   idle
              *********                                          
 The communication circuit is high when idle

2. After you have a general understanding of hardware resources, you need to understand the bridge between software and hardware - registers.
 1. Data registers: When data arrives, there must be a place to receive it, and when data is sent, there must be an envelope for sending data.
  This is the data register UDR (RXB and TXB). They are physically separated, but the addresses are the same. Just like when you write and receive letters, your home address is only

There is the same address, but the envelopes you write and others send you are the same. It is automatically controlled when used.
   Data can only be sent when the data register is empty, otherwise it will be invalid. After the data enters, it enters the shift register and is sent out bit by bit by pin TXD.
 2. Control and status register UCSRA
   RXC          TXC           UDRE            FE        DOR          PE         U2X       MPCM
Receive completion set 1  Send completion set 1     Data is empty flag    Frame error 1   Receive data   check bit error   Speed ​​mode  multi-machine communication
Read data clear 0  interrupt automatically clear 0   data completely to shift              overflow 1                        address bit
                            in the bit register 1
UCSRB  set related interrupt enable
RXCIE            TXCIE       UDRIE        RXEN          TXEN       UXSZ2      RXB8        TXB8
Receive interrupt enable  send interrupt enable  empty interrupt enable  data accept enable data send enable bit number set  accept 9th bit

RXEN, TXEN setting will change the normal IO port, or use it as a multiplexed port. Set it when sending data, and it will take effect after all the data is sent. 
RXB8, TXB8 needs to be read and written first

UCSRC

URSEL           UMSEL        UPM1       UPM0      USBS      UCSZ1     UCSZ0       UCPOL
register selects      the working mode,        check mode,         stop bit    and the above UXSZ2 settings
Need to be set to 1 when writing    1 Number of asynchronous                                           data
There is a shared register               00 Disable 11 Odd 10 Even     0 is 1 1 is 2

Baud rate register: UBRRL  UBRRH
 UBRRH and UCSRC share the bottom 4 bits  plus UBRRL for a total of 12 bits.  After setting, the data being transmitted will be interrupted.
Please pay attention to the setting of URSEL: 0  writes the high 4 bits of the bit rate
                     writes the contents of the register.
Read UBRRH, the first time is the content of the bit rate.  Read it again within 2 consecutive clock cycles to get the content of UCRSC. 

When using it, you can check the quick lookup table and directly use the ICCAVR generation tool.   

3. Related operations  and other exercises are added after the program.
1. Initialize and  turn off  the global interrupt    
TXC  RXC to see if the data is completed.   Before sending data, TXC must be zeroed 
and the data can be put into the sending buffer  in UDR  5-8 bits.
2. Note that after the interrupt  is enabled, data needs to be written continuously  , otherwise the interrupt will continue to occur.  Generally, it is OK to disable
 TXEN. After setting 0, all data will take effect after sending  , and then it will be used as a normal IO port.
 Disabling acceptance will immediately lose data.

Some bus standard
RS232 9-pin D-type interface 
 1 -3 ~-25      3-25V
needs to use level conversion circuit  MAX232

 

5. Serial Ports in Industrial Design

If you see this, it is better to pay attention to it. There are not many articles on the Internet. I also summarized it from engineering practice and searching a lot of reference books.

The design idea is based on the state machine and the protocol is customized. At the same time, CRC check and simple encryption technology are used in the protocol.

The idea is: master-slave mode, the upper computer sends data packets, the lower computer receives them in the interrupt, and when receiving data, it must confirm bit by bit and switch continuously, the position status of the send, put the preliminary confirmed data into the receive buffer, and wait for all the data to be received, the program enters the big loop, and executes the uart operation function added to the main program. This function first determines whether the command and setting sent by the host are accepted, and verifies the correctness in the completed state. After verification, according to the host command, assemble the data packet and store the host's setting data, and put the data packet to be sent or the setting completion data packet in the data buffer to be sent, and then change the state at this time: It is assembled for me, ready to send data, and then trigger the interrupt, you can directly send data to the serial port. After normal transmission, the microcontroller will execute other programs. After the upper computer receives the trigger data, the lower computer will interrupt. The interrupt program will generate the data in the buffer bit by bit according to the state until all the data is sent. After the sending is completed, it must be set to the receiving data state 0.

My environment is atmega128

initialization

 


uchar LED_Temp=0xFF;
uchar OUT_temp=0x04;
static uchar Uart_Status;
static uchar R_Data_Lenth;


float Tx_Buf[TxBufSize];
float Rx_Buf[RxBufSize];
float *P_Uart_Rx;
float *P_Uart_Tx;
float Rx_Count;
float Tx_Count;

 

void Uart_Init(void)
{
 //UCSR0B = 0x00; //Close first
 UCSR0A=0x00;
 UCSR0C=0x06;                 //8 DATA ,1 STOP, NO PARITY
 UCSR0B = (1<  // RXCIE=1;TXCIE=1;UDREIE=0;RXEN=1;TXEN=1
 Com_baudrate (9600);
 P_Uart_Tx=Tx_Buf;     //Buffer pointer definition
 P_Uart_Rx=Rx_Buf;
 Uart_Status=0;        //The initial status is the receiving start bit status. In fact, this is because I used the communication protocol in the program

                        //Based on this article, the content of the protocol is deleted, and only the simplest framework that can run is provided.
 SEI(); //re-enable interrupts
}


//  Function description: baud rate setting

void Com_baudrate (unsigned int baudrate)
{
   unsigned int tmp;
   tmp= 8000000/baudrate/16-1;
   UBRR0H=(unsigned char)(tmp>>8);
   UBRR0L=(unsigned char)tmp;
}

//  Function description: serial port receive interrupt function

#pragma interrupt_handler uart0_rx_isr:iv_USART0_RXC
void uart0_rx_isr(void)

{

  //Fill in the content of serial port interrupt processing here, you can add protocols and use the state machine

  //Put the received content in the buffer, then create a function to process the buffer data and put it directly in the main loop
}

 

//Function description: Serial port transmission completion interrupt function 
#pragma interrupt_handler uart0_tx_isr:iv_USART0_TXC
void uart0_tx_isr(void)
{
   //Data transmission processing function

}


//  Function description: uart process function  , placed in the big loop
void Uart_Process(void)
{
  //Received data, then implemented in the system, such as upper computer monitoring, or data transmission, etc.

}


//Function description: uart test program 

void Uart_Test(uchar data)
{
  UDR0 = 0x01; //Send data
}

 


//- Function description: Function of sending bytes through the serial port
 //- Function attribute: external, for user use
 //- Parameter description: mydata: a byte to be sent
//  - Return description: none
//  - Note: sending a byte is the basic operation of serial port sending
void UART_Send_Byte(unsigned char mydata) 
{
 // UCSR0B = (1<  UCSR0B &= ~((1<  while(!(UCSR0A &(1<   // Wait for the send buffer to be empty
 UDR0 = mydata;
 // delay_nms(5);
 UCSR0B |= (1<// Do not affect other register bits when changing, turn on serial port interrupts
}

Keywords:AVR Reference address:Detailed explanation of AVR serial communication

Previous article:Reading and Writing EEPROM of AVR Microcontroller
Next article:AVR MCU reads PS2 mouse

Recommended ReadingLatest update time:2024-11-16 22:20

Design of digital controlled DC voltage regulated power supply based on AVR microcontroller
Since the late 1990s, with the demand for higher system efficiency and lower power consumption, the technological update of telecommunications and data communication equipment has promoted the development of DC/DC power converters in the power supply industry towards higher flexibility and intelligence. The DC regul
[Power Management]
Design of digital controlled DC voltage regulated power supply based on AVR microcontroller
Building your own AVR RTOS (Part 8: Perfect Service)
Chapter 8: Preemptive Kernel (Complete Service) If we combine the preemptive kernel and the cooperative kernel mentioned above, we can easily get a more complete preemptive kernel with the following functions: 1. Suspend and resume tasks 2. Task delay 3. Semaphores (including shared and exclusive types) In addition,
[Microcontroller]
TimerInterrupt.h header file download - AVR general timer/counter interrupt control
/********************************************************************************       File name: PORT.H       File ID: _PORT_H_       Abstract: General timer/counter interrupt control header file for AVR microcontroller       Current version: V1.0 *********************************************************************
[Microcontroller]
AVR IO port characteristics and applications
When DDRxn=1, it is in output state. The output value is equal to PORTxn. Therefore, DDRxn is the direction register. PORTxn is the data register.   Analyze the pull-up resistor. When the potential of E is 0, that is, when D is 1, the pull-up resistor is effective. From the analysis of the AND gate input, the pull
[Microcontroller]
AVR IO input independent key detection program
System functions Use the AVR to detect eight independent buttons, and once a button is detected, it will immediately indicate that it has been pressed. Very cool! hardware design For details about the I/O structure and related introduction of AVR, please refer to the Datasheet. Here we only briefly introduce some of
[Microcontroller]
AVR IO input independent key detection program
The construction of avr microcontroller development environment under win7
Operating system: win7 professional x86 Development software: avr studio 4.19 First, download AVR Studio 4.19, because it seems that this is the last development environment that Atmel officially supports JTAG ICE. And only this version 4 supports Windows 7. I happened to have a JTAG, so I decisively chose this versio
[Microcontroller]
The construction of avr microcontroller development environment under win7
Motor Actuator Control System Based on AVR Single Chip Microcomputer
Introduction: The motor actuator control system is a controller specially used to control the air volume of the cement plant ventilation duct. The CPU adopts the AVR single-chip microcomputer series ATMEGA16L. This control system directly drives a motor actuator, and the actuator drives a movable louver. By adjusting
[Microcontroller]
Motor Actuator Control System Based on AVR Single Chip Microcomputer
24C02 Communication Program of AVR Microcontroller
#include avr/io.h #define  uchar  unsigned char #define  uint   unsigned int #define setbit(sfr,bit) (sfr|=(1 bit)) #define clrbit(sfr,bit) (sfr&=~(1 bit)) #define SDA_out() setbit(DDRD,0) //Set SDA to output #define SCL_out() setbit(DDRD,2) //Set SCL to output #define SDA_in() clrbit(DDRD,0) //Set SDA to input #defi
[Microcontroller]
Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号