搜档网
当前位置:搜档网 › KL25-UARTKL25串口例程

KL25-UARTKL25串口例程

KL25-UARTKL25串口例程
KL25-UARTKL25串口例程

Chapter 40

Universal Asynchronous Receiver/Transmitter (UART1 and UART2)

40.1Introduction

40.1.1Features

Features of UART module include:

?Full-duplex, standard non-return-to-zero (NRZ) format

?Double-buffered transmitter and receiver with separate enables ?Programmable baud rates (13-bit modulo divider)

?Interrupt-driven or polled operation:

?Transmit data register empty and transmission complete

?Receive data register full

?Receive overrun, parity error, framing error, and noise error

?Idle receiver detect

?Active edge on receive pin

?Break detect supporting LIN

?Hardware parity generation and checking

?Programmable 8-bit or 9-bit character length

?Programmable 1-bit or 2-bit stop bits

?Receiver wakeup by idle-line or address-mark

?Optional 13-bit break character generation / 11-bit break character detection ?Selectable transmitter output polarity

?5-channel DMA interface

40.1.2Modes of operation

See Section Functional description for details concerning UART operation in these modes:

?8- and 9-bit data modes ?Stop mode operation ?Loop mode

?Single-wire mode

40.1.3Block diagram

The following figure shows the transmitter portion of the UART.

PE

PT

H 8

7

6

5

4

3

2

1

L 11-BIT TRANSMIT SHIFT REGISTER S T O P

S T A R T

T8

TDRE TIE TCIE

SBK TC PARITY GENERATION

M S B

UART DATA REGISTER (UART_D)

L O A D F R O M U A R T _D

S H I F T E N A B L E

P R E A M B L E (A L L 1s )

B R E A K (A L L 0s )

TRANSMITTER CONTROL

M INTERNAL BUS

SBR12–SBR0

BAUD DIVIDER

÷16

TDRE INTERRUPT/DMA

TC INTERRUPT/DMA

MODULE LOOP RSRC

CLOCK

TE TO

CONTROL

RECEIVER

LOOPS TXINV

TxD Pin Control TXDIR

TxD

SHIFT DIRECTION

TXINV

DMA done

REQUEST Tx Pin Logic

REQUEST

Figure 40-1. UART transmitter block diagram

The following figure shows the receiver portion of the UART.

A L L 1s

M WAKE ILT

PE PT

RE H

8

7

6

5

4

3

2

1

L

11-BIT RECEIVE SHIFT REGISTER S T O P

S T A R T DATA WAKEUP PARITY CHECKING

M S B

UART DATA REGISTER (UART_D)

R8

RWU INTERNAL BUS

MODULE SBR12–SBR0 BAUD DIVIDER

CLOCK

RAF RECOVERY

LOGIC

RDRF SHIFT DIRECTION

RXINV

From RxD Pin LOOPS RSRC

SINGLE-WIRE LOOP CONTROL

FROM TRANSMITTER ACTIVE EDGE DETECT

LBKDE

RIE IDLE ILIE

LBKDIF LBKDIE RXEDGIF RXEDGIE

OR

ORIE FE FEIE NF NEIE

PF PEIE

RWUID

Rx

Error Request

Interrupt/DMA Requestt

Interrupt Figure 40-2. UART receiver block diagram

40.2Register definition

The UART has 8-bit registers to control baud rate, select UART options, report UART status, select DMA options, and for transmit/receive data.

Refer to the direct-page register summary in the memory chapter of this document or the absolute address assignments for all UART registers. This section refers to registers and control bits only by their names. A Freescale-provided equate or header file is used to translate these names into the appropriate absolute addresses.

40.2.1UART Baud Rate Register: High (UART x_BDH)

This register, along with UART_BDL, controls the prescale divisor for UART baud rate generation. To update the 13-bit baud rate setting [SBR12:SBR0], first write to

UART_BDH to buffer the high half of the new value and then write to UART_BDL. The working value in UART_BDH does not change until UART_BDL is written.

Address: Base address + h offset

Bit76543210 Read LBKDIE RXEDGIE SBNS SBR

Write

Reset00000000

40.2.2UART Baud Rate Register: Low (UART x_BDL)

This register, along with UART_BDH, control the prescale divisor for UART baud rate generation. To update the 13-bit baud rate setting [SBR12:SBR0], first write to

UART_BDH to buffer the high half of the new value and then write to UART_BDL. The working value in UART_BDH does not change until UART_BDL is written.

UART_BDL is reset to a non-zero value, so after reset the baud rate generator remains disabled until the first time the receiver or transmitter is enabled; that is, UART_C2[RE] or UART_C2[TE] bits are written to 1.

Address: Base address + h offset

Bit76543210 Read SBR

Write

Reset0000010

0 Array 40.2.3UART Control Register 1 (UART x_C1)

This read/write register controls various optional features of the UART system. Address: Base address + h offset

Bit76543210 Read LOOPS UARTSWAI RSRC M WAKE ILT PE PT Write

Reset00000000

40.2.4UART Control Register 2 (UART x_C2)

This register can be read or written at any time.

Address: Base address + h offset

Bit76543210 Read TIE TCIE RIE ILIE TE RE RWU SBK Write

Reset00000000

40.2.5UART Status Register 1 (UART x_S1)

This register has eight read-only status flags. Writes have no effect. Special software sequences, which do not involve writing to this register, clear these status flags. Address: Base address + h offset

Bit

Read

Write

Reset

40.2.6UART Status Register 2 (UART x_S2) This register contains one read-only status flag.

When using an internal oscillator in a LIN system, it is necessary to raise the break detection threshold one bit time. Under the worst case timing conditions allowed in LIN, it is possible that a 0x00 data character can appear to be 10.26 bit times long at a slave running 14% faster than the master. This would trigger normal break detection circuitry designed to detect a 10-bit break symbol. When the LBKDE bit is set, framing errors are inhibited and the break detection threshold changes from 10 bits to 11 bits, preventing false detection of a 0x00 data character as a LIN break symbol.

Address: Base address + h offset

Bit

Read

Write

Reset

40.2.7UART Control Register 3 (UART x _C3)

Address: Base address + h offset

Bit

Read Write Reset

40.2.8UART Data Register (UART x _D)

This register is actually two separate registers. Reads return the contents of the read-only receive data buffer and writes go to the write-only transmit data buffer. Reads and writes of this register are also involved in the automatic flag clearing mechanisms for the UART status flags.

Address: Base address + h offset

Bit

7

6

5

4

3

2

1

Read R7T7R6T6R5T5R4T4R3T3R2T2R1T1R0T0Write Reset

40.2.9UART Control Register 4 (UART x _C4)

Address: Base address + h offset

Bit

Read Write Reset

40.3Functional description

The UART allows full-duplex, asynchronous, NRZ serial communication among the MCU and remote devices, including other MCUs. The UART comprises a baud rate generator, transmitter, and receiver block. The transmitter and receiver operate independently, although they use the same baud rate generator. During normal operation, the MCU monitors the status of the UART, writes the data to be transmitted, and processes received data. The following describes each of the blocks of the UART.

40.3.1Baud rate generation

As shown in the following figure, the clock source for the UART baud rate generator is the bus-rate clock.

SBR[12:0]

Divide By

Tx Baud Rate

Rx Sampling Clock

(16 × Baud Rate)

Baud Rate Generator Off If [SBR12:SBR0] =0

Baud Rate =

SBR[12:0] × 16

16

Modulo Divide By

(1 through 8191)

UART Module Clock UART Module Clock Figure 40-30. UART baud rate generation

UART communications require the transmitter and receiver, which typically derive baud rates from independent clock sources, to use the same baud rate. Allowed tolerance on this baud frequency depends on the details of how the receiver synchronizes to the leading edge of the start bit and how bit sampling is performed.

The MCU resynchronizes to bit boundaries on every high-to-low transition. In the worst case, there are no such transitions in the full 10- or 11-bit or 12-bittime character frame so any mismatch in baud rate is accumulated for the whole character time. For a

Freescale UART system whose bus frequency is driven by a crystal, the allowed baud rate mismatch is about ±4.5 percent for 8-bit data format and about ±4 percent for 9-bit data format. Although baud rate modulo divider settings do not always produce baud rates that exactly match standard rates, it is normally possible to get within a few percent,which is acceptable for reliable communications.

40.3.2Transmitter functional description

This section describes the overall block diagram for the UART transmitter, as well as specialized functions for sending break and idle characters.

The transmitter output (TxD) idle state defaults to logic high, UART_C3[TXINV] is

cleared following reset. The transmitter output is inverted by setting UART_C3[TXINV].The transmitter is enabled by setting the TE bit in UARTxC2. This queues a preamble character that is one full character frame of the idle state. The transmitter then remains idle until data is available in the transmit data buffer. Programs store data into the transmit data buffer by writing to the UART data register (UART_D).

The central element of the UART transmitter is the transmit shift register that is 10 or 11or 12 bits long depending on the setting in the UART_C1[M] control bit and

UART_BDH[SBNS] bit. For the remainder of this section, assume UART_C1[M] is

cleared, UART_BDH[SBNS] is also cleared, selecting the normal 8-bit data mode. In 8-bit data mode, the shift register holds a start bit, eight data bits, and a stop bit. When the transmit shift register is available for a new UART character, the value waiting in the transmit data register is transferred to the shift register, synchronized with the baud rate clock, and the transmit data register empty (UART_S1[TDRE]) status flag is set to indicate another character may be written to the transmit data buffer at UART_D.

If no new character is waiting in the transmit data buffer after a stop bit is shifted out the TxD pin, the transmitter sets the transmit complete flag and enters an idle mode, with TxD high, waiting for more characters to transmit.

Writing 0 to UART_C2[TE] does not immediately release the pin to be a general-purpose I/O pin. Any transmit activity in progress must first be completed. This includes data characters in progress, queued idle characters, and queued break characters.

40.3.2.1Send break and queued idle

The UART_C2[SBK] bit sends break characters originally used to gain the attention of old teletype receivers. Break characters are a full character time of logic 0, 10 bit times including the start and stop bits. A longer break of 13 bit times can be enabled by setting UART_S2[BRK13]. Normally, a program would wait for UART_S1[TDRE] to become set to indicate the last character of a message has moved to the transmit shifter, write 1, and then write 0 to the UART_C2[SBK] bit. This action queues a break character to be sent as soon as the shifter is available. If UART_C2[SBK] remains 1 when the queued break moves into the shifter, synchronized to the baud rate clock, an additional break character is queued. If the receiving device is another Freescale Semiconductor UART, the break characters are received as 0s in all eight data bits and a framing error (UART_S1[FE] = 1) occurs.

When idle-line wakeup is used, a full character time of idle (logic 1) is needed between messages to wake up any sleeping receivers. Normally, a program would wait for UART_S1[TDRE] to become set to indicate the last character of a message has moved to the transmit shifter, then write 0 and then write 1 to the UART_C2[TE] bit. This action queues an idle character to be sent as soon as the shifter is available. As long as the character in the shifter does not finish while UART_C2[TE] is cleared, the UART transmitter never actually releases control of the TxD pin. If there is a possibility of the shifter finishing while UART_C2[TE] is cleared, set the general-purpose I/O controls so the pin shared with TxD is an output driving a logic 1. This ensures that the TxD line looks like a normal idle line even if the UART loses control of the port pin between writing 0 and then 1 to UART_C2[TE].

The length of the break character is affected by the UART_S2[BRK13] and

UART_C1[M] bits as shown below.

40.3.3Receiver functional description

In this section, the receiver block diagram is a guide for the overall receiver functional description. Next, the data sampling technique used to reconstruct receiver data is described in more detail. Finally, two variations of the receiver wakeup function are explained.

The receiver input is inverted by setting UART_S2[RXINV]. The receiver is enabled by setting the UART_C2[RE] bit. Character frames consist of a start bit of logic 0, eight (or nine) data bits (lsb first), and one (or two) stop bits of logic 1. For information about 9-bit data mode, refer to 8- and 9-bit data modes. For the remainder of this discussion, assume the UART is configured for normal 8-bit data mode.

After receiving the stop bit into the receive shifter, and provided the receive data register is not already full, the data character is transferred to the receive data register and the receive data register full (UART_S1[RDRF]) status flag is set. If UART_S1[RDRF] was already set indicating the receive data register (buffer) was already full, the overrun (OR) status flag is set and the new data is lost. Because the UART receiver is double-buffered, the program has one full character time after UART_S1[RDRF] is set before the data in the receive data buffer must be read to avoid a receiver overrun.

When a program detects that the receive data register is full (UART_S1[RDRF] = 1), it gets the data from the receive data register by reading UART_D. The UART_S1[RDRF] flag is cleared automatically by a two-step sequence normally satisfied in the course of the user's program that manages receive data. Refer to Interrupts and status flags for more details about flag clearing.

40.3.3.1Data sampling technique

The UART receiver uses a 16× baud rate clock for sampling. The receiver starts by taking logic level samples at 16 times the baud rate to search for a falling edge on the RxD serial data input pin. A falling edge is defined as a logic 0 sample after three consecutive logic 1 samples. The 16× baud rate clock divides the bit time into 16 segments labeled UART_D[[RT1] through UART_D[RT16]. When a falling edge is located, three more samples are taken at UART_D[RT3], UART_D[RT5], and

UART_D[RT7] to make sure this was a real start bit and not merely noise. If at least two of these three samples are 0, the receiver assumes it is synchronized to a receive character.

The receiver then samples each bit time, including the start and stop bits, at

UART_D[RT8], UART_D[RT9], and UART_D[RT10] to determine the logic level for that bit. The logic level is interpreted to be that of the majority of the samples taken during the bit time. In the case of the start bit, the bit is assumed to be 0 if at least two of the samples at UART_D[RT3], UART_D[RT5], and UART_D[RT7] are 0 even if one or all of the samples taken at UART_D[RT8], UART_D[RT9], and UART_D[RT10] are 1s. If any sample in any bit time, including the start and stop bits, in a character frame fails to agree with the logic level for that bit, the noise flag (UART_S1[NF]) is set when the received character is transferred to the receive data buffer.

The falling edge detection logic continuously looks for falling edges. If an edge is detected, the sample clock is resynchronized to bit times. This improves the reliability of the receiver in the presence of noise or mismatched baud rates. It does not improve worst case analysis because some characters do not have any extra falling edges anywhere in the character frame.

In the case of a framing error, provided the received character was not a break character, the sampling logic that searches for a falling edge is filled with three logic 1 samples so that a new start bit can be detected almost immediately.

In the case of a framing error, the receiver is inhibited from receiving any new characters until the framing error flag is cleared. The receive shift register continues to function, but a complete character cannot transfer to the receive data buffer if UART_S1[FE] remains set.

40.3.3.2Receiver wakeup operation

Receiver wakeup is a hardware mechanism that allows an UART receiver to ignore the characters in a message intended for a different UART receiver. In such a system, all receivers evaluate the first character(s) of each message, and as soon as they determine the message is intended for a different receiver, they write logic 1 to the receiver wake up control bit(UART_C2[RWU]). When RWU bit is set, the status flags associated with the receiver, with the exception of the idle bit, IDLE, when UART_S2[RWUID] bit is set, are inhibited from setting, thus eliminating the software overhead for handling the unimportant message characters. At the end of a message, or at the beginning of the next message, all receivers automatically force UART_C2[RWU] to 0 so all receivers wake up in time to look at the first character(s) of the next message.

40.3.3.2.1Idle-line wakeup

When wake is cleared, the receiver is configured for idle-line wakeup. In this mode, UART_C2[RWU] is cleared automatically when the receiver detects a full character time of the idle-line level. The UART_C1[M] control bit selects 8-bit or 9-bit data mode and the UART_BDH[SBNS] bit selects 1-bit or 2-bit stop bit number that determines how many bit times of idle are needed to constitute a full character time, 10 or 11 or 12 bit times because of the start and stop bits.

When UARTI_C2[RWU] is one and UART_S2[RWUID] is zero, the idle condition that wakes up the receiver does not set the UART_S1[IDLE] flag. The receiver wakes up and waits for the first data character of the next message that sets the UART_S1[RDRF] flag and generates an interrupt if enabled. When UART_S2[RWUID] is one, any idle condition sets the UART_S1[IDLE] flag and generates an interrupt if enabled, regardless of whether UART_C2[RWU] is zero or one.

The idle-line type (UART_C1[ILT]) control bit selects one of two ways to detect an idle line. When UART_C1[ILT] is cleared, the idle bit counter starts after the start bit so the stop bit and any logic 1s at the end of a character count toward the full character time of idle. When UART_C1[ILT] is set, the idle bit counter does not start until after a stop bit time, so the idle detection is not affected by the data in the last character of the previous message.

40.3.3.2.2Address-mark wakeup

When wake is set, the receiver is configured for address-mark wakeup. In this mode, UART_C2[RWU] is cleared automatically when the receiver detects a, or two, if UART_BDH[SBNS] = 1, logic 1 in the most significant bits of a received character, eighth bit when UART_C1[M] is cleared and ninth bit when UART_C1[M] is set.

经典的串口调试工具源代码(一)

经典的串口调试助手源代码(一) Dim OutputAscii As Boolean Dim InputString As String Dim OutputString As String '============================================================================== ======= ' 变量定义 '============================================================================== ======= Option Explicit ' 强制显式声明 Dim ComSwitch As Boolean ' 串口开关状态判断 Dim FileData As String ' 要发送的文件暂存Dim SendCount As Long ' 发送数据字节计数器 Dim ReceiveCount As Long ' 接收数据字节计数器Dim InputSignal As String ' 接收缓冲暂存 Dim OutputSignal As String ' 发送数据暂存 Dim DisplaySwitch As Boolean ' 显示开关 Dim ModeSend As Boolean ' 发送方式判断

Dim Savetime As Single ' 时间数据暂存延时用Dim SaveTextPath As String ' 保存文本路径 ' 网页超链接申明 Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long Private Sub CloseCom() '关闭串口 On Error GoTo Err If MSComm.PortOpen = True Then MSComm.PortOpen = False ' 先判断串口是否打 开,如果打开则先关闭 txtstatus.Text = "STATUS:COM Port Cloced" ' 串口状态显示 mnuconnect.Caption = "断开串口" cmdswitch.Caption = "打开串口" 'ImgSwitch.Picture = LoadPicture("f:\我的VB\串口调试软件\图片\guan.jpg") ' 显示串口已经关闭 的图标 ImgSwitchoff.Visible = True ImgSwitchon.Visible = False Err: End Sub Private Sub UpdateStatus() If MSComm.PortOpen Then StatusBar1.Panels(1).Text = "Connected" mnuautosend.Caption = "自动发送" mnuconnect.Caption = "断开串口" Else StatusBar1.Panels(1).Text = "断开串口" mnuautosend.Caption = "disautosend" mnuconnect.Caption = "打开串口" End If StatusBar1.Panels(2).Text = "COM" & https://www.sodocs.net/doc/1814756937.html,mPort StatusBar1.Panels(3).Text = MSComm.Settings If (OutputAscii) Then StatusBar1.Panels(4) = "ASCII" Else StatusBar1.Panels(4) = "HEX" End If ' On Error GoTo Err If ChkAutoSend.Value = 1 Then ' 如果有效则,自动发送

51串口通信程序(带详细注释)

51串口通信程序(带详细注释) #include#include //后面有一个比较函数#define uchar unsigned char#define uint unsigned intbit UART_Flag=0; //定义串口接收标志位 uchar str[50]; //定义一数组uchar length=0; //数组长度从0 开始void init() //初 始化uart{ TMOD=0X20; //定时器1 定时器方式工作模式2,可自动重载的8 位计数器常把定时/计数器1 以模式2 作为串行口波特率发生器 SCON=0X50; //选择工作模式1 使能接收,允许发送,允许接收 EA=1; //开总中断 ES=1; //打开串口中断ET1=0; //打开定时器中断 PCON=0X80; //8 位自动重载,波特率加倍 TH1=0XFF; //用22.1184 mhz 波特率 TL1=0XFF;TR1=1; //打开中时器 }void UART_Putch(uchar dat) //输出一个字符{SBUF=dat; //把数据送给sbuf 缓 存器中 while(TI!=1);//发送标志位TI 如果发送了为1,没发送为0,没发送等待,到 了退出循环 TI=0; //到了,TI 清为0 }void init1() interrupt 4 //uart 中断,4 为串口中断{ if(RI==1) //收到数据{ uchar m=SBUF; //m 为计算机发送给串口的数据,例,open //总体思想是,计算 机通知串口,我要发数据了RI=0; //收到清0 if(m==) //判断m 这位数据有无{ UART_Putch(); //回车UART_Putch(); // 换行str[length]=; //数据最后位加0 标 志位表示发完了数据UART_Flag=1; // 传完标志位} else if(m==) { } else if(m==)//b表退格//下面几句表删锄{ UART_Putch();

PS2键盘编码Verilog源程序

PS2键盘编码Verilog源程序 之前探讨过PS/2键盘编解码以及数据传输协议,这次自己动手实现了利用FPGA接收键盘编码,然后通过串口传输到PC。做的比较简单,只是通过FPGA把大写字母A-Z转换成相应的ASCII码,只要字母按键被按下,就能在串口调试助手里显示相应大写字母。下面就共享代码吧! 除了顶层模块,三个底层模块分别为PS/2传输处理模块、串口传输模块以及串口波特率选择模块(下面只给出顶层模块和PS/2传输处理模块的verilog代码)。 module ps2_key(clk,rst_n,ps2k_clk,ps2k_data,rs232_tx); input clk; //50M时钟信号 input rst_n; //复位信号 input ps2k_clk; //PS2接口时钟信号 input ps2k_data; //PS2接口数据信号 output rs232_tx; // RS232发送数据信号 wire[7:0] ps2_byte; // 1byte键值 wire ps2_state; //按键状态标志位 wire bps_start; //接收到数据后,波特率时钟启动信号置位

wire clk_bps; // clk_bps的高电平为接收或者发送数据位的中间采样点 ps2scan ps2scan( .clk(clk), //按键扫描模块 .rst_n(rst_n), .ps2k_clk(ps2k_clk), .ps2k_data(ps2k_data), .ps2_byte(ps2_byte), .ps2_state(ps2_state) ); speed_select speed_select( .clk(clk), .rst_n(rst_n), .bps_start(bps_start), .clk_bps(clk_bps) ); my_uart_tx my_uart_tx( .clk(clk), .rst_n(rst_n), .clk_bps(clk_bps), .rx_data(ps2_byte), .rx_int(ps2_state), .rs232_tx(rs232_tx), .bps_start(bps_start) );

51单片机串口通信,232通信,485通信,程序

51单片机串口通信,232通信,485通信,程序代码1:232通信 #include #define uchar unsigned char #define uint unsigned int uchar flag,a,i; uchar code table[]="i get"; void init() { TMOD=0X20; TH1=0XFD; TH0=0XFD; TR1=1; REN=1; SM0=0; SM1=1; EA=1; ES=1; } void main() { init();

while(1) { if(flag==1) { ES=0; for(i=0;i<6;i++) { SBUF=table[i]; while(!TI); TI=0; } SBUF=a; while(!TI); TI=0; ES=1; flag=0; } } } void ser() interrupt 4 {

RI=0; a=SBUF; flag=1; } 代码2:485通信 #include #include"1602.h" #define uchar unsigned char #define uint unsigned int unsigned char flag,a,i; uchar code table[]="i get "; void init() { TMOD=0X20; TH1=0Xfd; TL1=0Xfd; TR1=1; REN=1; SM0=0; SM1=1; EA=1; ES=1;

} void main() { init_1602(); init(); while(1) { if(flag==1) { display(0,a); } } } void ser() interrupt 4 { RI=0; a=SBUF; flag=1; } Love is not a maybe thing. You know when you love someone.

串口调试助手c开发

1.建立项目: 打开VC+ + 6.0,建立一个基于对话框的MFC应用程序SCommTest(与我 源代码一致,等会你会方便一点); 2.在项目中插入MSComm控件 选择Project菜单下Add To Project子菜单中的Componentsand Controls,选项,在弹出的对话框中双击Registered ActiveXControls项(稍等一会,这个过程较慢),则所有注册过的ActiveX控件出现在列表框中。选择Microsoft Communications Control,version6.0,,单击Insert 按钮将它插入到我们的Project 中来,接受缺省的选项。(如果你在控件列表中看不到Microsoft Communications Control, version 6.0,那可能是你在安装VC6时没有把ActiveX 一项选上,重新安装VC6,选上ActiveX就可以了),这时在ClassView 视窗中就可以看到CMSComm类了,(注意:此类在ClassWizard中看不到,重构clw文件也一样),并且在控件工具栏Controls中出现了电话图标(如图1所示),现在要做的是用鼠标将此图标拖到对话框中,程序运行后,这个图标是看不到的。3.利用ClassWizard定义CMSComm类控制对象 打开ClassWizard- >Member Viariables 选项卡,选择CSCommTestDlg^,为IDC_MSCOMM1添加控制变量:m_ctrlCom m,这时你可以看一看,在对话框头文件中自动加入了//{{AFX_INCLUDES()#include "mscomm.h" //}}AFX_INCLUDES (这时运行程序,如果有错,那就再从头开始)。 4 .在对话框中添加控件 向主对话框中添加两个编辑框,一个用于接收显示数据ID为 IDC_EDIT_RXDATA另一个用于输入发送数据,ID为IDC_EDIT_TXDAT A再添加一个按钮,功能是按一次就把发送编辑框中的内容发送一次,将其ID设为 IDC_BUTTON_MANUALSEND别忘记了将接收编辑框的Prop erties->Styles 中把Miltiline和Vertical Scroll属性选上,发送编辑框若你想输入多行文字,也可选上Miltiline。

C#的串口通信源程序

基于单片机串口通信的上位机和下位机 首先亮出C#的源程序吧。 主要界面: 只是作为简单的运用,可以扩展的。 源代码: using System; using System.Collections.Generic; using https://www.sodocs.net/doc/1814756937.html,ponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO.Ports; using System.Timers; namespace 单片机功能控制 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } SerialPort sp = new SerialPort(); private void button1_Click(object sender, EventArgs e) {

String str1 = comboBox1.Text;//串口号 String str2 = comboBox2.Text;//波特率 String str3 = comboBox3.Text;//校验位 String str4 = comboBox5.Text;//停止位 String str5 = comboBox4.Text;//数据位 Int32 int2 = Convert.ToInt32(str2);//将字符串转为整型 Int32 int5 = Convert.ToInt32(str5);//将字符串转为整型 groupBox3.Enabled = true;//LED控制界面变可选 try { if (button1.Text == "打开串口") { if (str1 == null) { MessageBox.Show("请先选择串口!", "Error"); return; } sp.Close(); sp = new SerialPort(); sp.PortName = comboBox1.Text;//串口编号 sp.BaudRate = int2;//波特率 switch (str4)//停止位 { case "1": sp.StopBits = StopBits.One; break; case "1.5": sp.StopBits = StopBits.OnePointFive; break; case "2": sp.StopBits = StopBits.Two; break; default: MessageBox.Show("Error:参数不正确", "Error"); break; } switch (str3) { case "NONE": sp.Parity = Parity.None; break; case "ODD":

单片机串口通信C程序及应用实例

一、程序代码 #include//该头文件可到https://www.sodocs.net/doc/1814756937.html,网站下载#define uint unsigned int #define uchar unsigned char uchar indata[4]; uchar outdata[4]; uchar flag; static uchar temp1,temp2,temp3,temp; static uchar R_counter,T_counter; void system_initial(void); void initial_comm(void); void delay(uchar x); void uart_send(void); void read_Instatus(void); serial_contral(void); void main() { system_initial(); initial_comm(); while(1) { if(flag==1) { ES = 0; serial_contral(); ES = 1; flag = 0; } else read_Instatus(); } } void uart_send(void) { for(T_counter=0;T_counter<4;T_counter++) { SBUF = outdata[T_counter]; while(TI == 0);

TI = 0; } T_counter = 0; } uart_receive(void) interrupt 4 { if(RI) { RI = 0; indata[R_counter] = SBUF; R_counter++; if(R_counter>=4) { R_counter = 0; flag = 1; } } } void system_initial(void) { P1M1 = 0x00; P1M0 = 0xff; P1 = 0xff; //初始化为全部关闭 temp3 = 0x3f;//初始化temp3的值与六路输出的初始值保持一致 temp = 0xf0; R_counter = 0; T_counter = 0; } void initial_comm(void) { SCON = 0x50; //设定串行口工作方式:mode 1 ; 8-bit UART,enable ucvr TMOD = 0x21; //TIMER 1;mode 2 ;8-Bit Reload PCON = 0x80; //波特率不加倍SMOD = 1 TH1 = 0xfa; //baud: 9600;fosc = 11.0596 IE = 0x90; // enable serial interrupt TR1 = 1; // timer 1 RI = 0; TI = 0; ES = 1; EA = 1; }

串口调试助手源代码

串口调试助手预源代码 using System; using System.Collections.Generic; using https://www.sodocs.net/doc/1814756937.html,ponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.IO.Ports; using System.Threading; using DevExpress.XtraEditors; using System.Text.RegularExpressions; namespace WindowsFormsApplication3 { public partial class Form1 : XtraForm { SerialPort sp1 = new SerialPort(); int Flag = 0; int StateChanged = 0;

int StateChanged_Ascii = 1; int StateChanged_16 = 0; string Temp = null; string Temp_memoSend = null; private void memoSend_EditValueChanged(object sender, EventArgs e) { } public Form1() { InitializeComponent(); sp1.DataReceived += sp1_DataReceived; } private void Form1_Load(object sender, EventArgs e) { this.MaximizeBox = false; //检查是否有串口 string[] str = SerialPort.GetPortNames(); if (str == null) { MessageBox.Show("本机没有串口!", "error"); return; } //添加串口项目 foreach (string port in System.IO.Ports.SerialPort.GetPortNames()) { cbSerial.Properties.Items.Add(port); } //串口设置默认选择项 cbSerial.SelectedIndex = 0; Control.CheckForIllegalCrossThreadCalls = false; sp1.DataReceived += new SerialDataReceivedEventHandler(sp1_DataReceived); //订阅委托 } private void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgs

51串口通信协议(新型篇)

51串口通信协议(新型篇) C51编程:这是网友牛毅编的一个C51串口通讯程序! //PC读MCU指令结构:(中断方式,ASCII码表示) //帧:帧头标志|帧类型|器件地址|启始地址|长度n|效验和|帧尾标志 //值: 'n' 'y'| 'r' | 0x01 | x | x | x |0x13 0x10 //字节数: 2 | 1 | 1 | 1 | 1 | 1 | 2 //求和: ///////////////////////////////////////////////////////////////////// //公司名称:*** //模块名:protocol.c //创建者:牛毅 //修改者: //功能描述:中断方式:本程序为mcu的串口通讯提供(贞结构)函数接口,包括具体协议部分 //其他说明:只提供对A T89c51具体硬件的可靠访问接口 //版本:1.0 //信息:QQ 75011221 ///////////////////////////////////////////////////////////////////// #include #include //预定义 //帧 #define F_ST1 0x6e //帧头标志n #define F_ST2 0x79 //帧头标志y #define F_R 0x72 //帧类型读r #define F_W 0x77 //帧类型写w #define F_D 0x64 //帧类型数据帧d #define F_B 0x62 //帧类型写回应帧b #define F_C 0x63 //帧类型重发命令帧c #define F_Q 0x71 //帧类型放弃帧q #define F_ADDR 0x31 //器件地址0-9 #define F_END 0x7a //帧尾标志z #define F_SPACE 0x30 //空标志0 #define F_ERR1 0x31 //错误标志1,flagerr 1 #define F_ERR2 0x32 //错误标志2 2 //常数 #define S_MAXBUF 16 //接收/发送数据的最大缓存量 #define FIELD_MAXBUF 48 //最小场缓存,可以大于48字节,因为协议是以20字节为

串口调试助手代码分析42

第5章串口调试助手代码分析 1、建立基于对话框的工程SCOMM 2、绘制界面,如下图: 接收区 串口组合框:IDC_COMBO_COMSELECT,m_Com 波特率组合框:IDC_COMBO_SPEED,m_Speed 停止位组合框:IDC_COMBO_STOPBITS,m_StopBits 数据位组合框:IDC_COMBO_DATABITS,m_DataBits 校验位组合框:IDC_COMBO_PARITY,m_Parity 十六进制显示(接收):IDC_CHECK_HEXRECIEVE,m_ctrlHexReceieve 接收编辑框:IDC_EDIT_RECIVE ,m_ReceiveData m_ctrlReceiveData Style:Vertical Scroll MultiLine 打开串口IDC_BUTTON_OPENPORT,m_ctrlOpenPort 串口开关标志图标IDC _STATIC_OPENOFF,m_ctrlIconOpenoff 数据文件保存路径IDC _EDIT_SA VEPATH,m_strCurPath 保存显示数据文件路径IDC _EDIT_SA VEPATH, m_ctrlSavePath 接收计数IDC_STATIC_RXCOUNT ,m_ctrlRXCOUNT 发送区 …。。。。。。。。。。。。。。 3、添加CSeraiPort类文件 将类文件SerialPort.h SerialPort.cpp 复制到工程所在文件夹中(选择改进

后的类),然后单击VC 6.0菜单Projrct -> Add to Projrct ->Files… ,再在打开的文件选择对话框中选择SerialPort.h 和SerialPort.cpp ,点击OK,就把类文件加入当前工程,并在SCOMMDlg.h 中加入头文件,#include "SerialPort.h",通过上述步骤就在当前工程中加入了CSeraiPort类。 4、完成串口消息处理函数OnCommunicatiom 在CserailPort 类中有多个串口事件可以响应。在一般串口编程中,只需要处理WM_COMM_RXCHAR消息就可以了,该类所有的消息均需要人工添加消息处理函数。我们将处理函数名定义为OnComm()。首先在SCOMMDlg.h 中添加串口字符接收消息WM_COMM_RXCHAR(串口接收缓冲区内有一个字符)响应函数的声明:如下图 然后,在SCOMMDlg.cpp文件中进行WM_COMM_RXCHAR消息映射: 如下图; 接着,在SCOMMDlg.cpp 文件中加入函数OnCommunication(WPARAM ch, LPARAM port)的实现,暂不添加代码。 LONG CSCOMMDlg::OnCommunication(WPARAM ch, LPARAM port) { return 0; } 以上步骤需要手工完成。 至此完成了程序的对话框模板,在工程中插入了串口操作类CserailPort类。5、添加串口初始化及关闭 程序中有两种方法大开串口,一是程序启动,调用OnInitDialog()函数,就可以打开串口,缺省的串口号为COM1,如果COM1不存在或占用,就会给出提示;另外,单击“打开串口”按钮也可以打开串口。 //在初始化中打开串口 BOOL CSCOMMDlg::OnInitDialog() { m_nBaud=9600;//波特率 m_nCom=1;//串口号 m_cParity='N';//奇偶校验

串口通信测试方法

串口通信测试方法 1 关于串口通信的一些知识: RS-232C是目前最常用的串行接口标准,用来实现计算机和计算机之间、计算机和外设之间的数据通信。 在PC机系统中都装有异步通信适配器,利用它可以实现异步串行通信。而且MCS-51单片机本身具有一个全双工的串行接口,因此只要配以电平转换的驱动电路、隔离电路就可以组成一个简单可行的通信接口。 由于MCS-51单片机的输入和输出电平为TTL电平,而PC机配置的是RS-232C 标准串行接口,二者电气规范不一致,因此要完成PC机与单片机的数据通信,必须进行电平转换。 注明:3)RS-232C上传送的数字量采用负逻辑,且与地对称 逻辑1:-3 ~-15V 逻辑0:+3~+15V 所以与单片机连接时常常需要加入电平转换芯片: 2 实现串口通信的三个步骤: (1)硬件连接 51单片机有一个全双工的串行通讯口,所以单片机和计算机之间可以方便地进行串口通讯。进行串行通讯时要满足一定的条件,比如计算机的串口是RS232电平的,而单片机的串口是TTL电平的,两者之间必须有一个电平转换电路,我们采用了专用芯片MAX232进行转换。我们采用了三线制连接串口,也就是说和计算机的9针串口只连接其中的3根线:第5脚的GND、第2脚的RXD、第3脚的TXD。电路如下图所示,MAX232的第10脚和单片机的11脚连接,第9脚和单片机的10脚连接,第15脚和单片机的20脚连接。 使用MAX232串口通信电路图(9孔串口接头) (2)串行通信程序设计 ①通信协议的使用 通信协议是通信设备在通信前的约定。单片机、计算机有了协议这种

约定,通信双方才能明白对方的意图,以进行下一步动作。假定我们需要在PC 机与单片机之间进行通信,在设计过程中,有如下约定:

VB串口调试助手源代码

VB串口调试助手源代码 Dim OutputAscii As Boolean Dim InputString As String Dim OutputString As String '============================================================================== ======= ' 变量定义 '============================================================================== ======= Option Explicit ’强制显式声明 Dim ComSwitch As Boolean ’串口开关状态判断 Dim FileData As String ’要发送的文件暂存 Dim SendCount As Long ’发送数据字节计数器 Dim ReceiveCount As Long ’接收数据字节计数器 Dim InputSignal As String ’接收缓冲暂存 Dim OutputSignal As String ’发送数据暂存 Dim DisplaySwitch As Boolean ’显示开关 Dim ModeSend As Boolean ’发送方式判断 Dim Savetime As Single ’时间数据暂存延时用 Dim SaveTextPath As String ’保存文本路径 ' 网页超链接申明 Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long Private Sub CloseCom() '关闭串口 On Error GoTo Err If MSComm.PortOpen = True Then MSComm.PortOpen = False’先判断串口是否打开,如果打开则先关闭

经典的串口调试助手源代码

https://www.sodocs.net/doc/1814756937.html,/article/446.html https://www.sodocs.net/doc/1814756937.html,/hinzn/blog/item/4e81b4459b390a2ecffca3bb.html https://www.sodocs.net/doc/1814756937.html,/modeng_2005/blog/static/265611200981142011329/https://www.sodocs.net/doc/1814756937.html,/mod eng_2005/blog/static/265611200981142011329/ Dim OutputAscii As Boolean Dim InputString As String Dim OutputString As String '============================================================================== ======= ' 变量定义 '============================================================================== ======= Option Explicit ' 强制显式声明 Dim ComSwitch As Boolean ' 串口开关状态判断 Dim FileData As String ' 要发送的文件暂存 Dim SendCount As Long ' 发送数据字节计数器 Dim ReceiveCount As Long ' 接收数据字节计数器 Dim InputSignal As String ' 接收缓冲暂存 Dim OutputSignal As String ' 发送数据暂存 Dim DisplaySwitch As Boolean ' 显示开关

串口调试助手源程序编程详细过程

目录: 1.建立项目 2.在项目中插入MSComm控件 3.利用ClassWizard定义CMSComm类控制变量 4.在对话框中添加控件 5.添加串口事件消息处理函数OnComm() 6.打开和设置串口参数 7.发送数据 8.发送十六进制字符 9.在接收框中以十六进制显示 10.如何设置自动发送 11.什么是VARIANT数据类型?如何使用VARIANT数据类型? 在众多网友的支持下,串口调试助手从2001年5月21日发布至今,短短一个月,在全国各地累计下载量近5000人次,在近200多个电子邮件中,20多人提供了使用测试意见,更有50多位朋友提出要串口调试助手的源代码,为了答谢谢朋友们的支持,公开推出我最初用VC控件MSComm编写串口通信程序的源代码,并写出详细的编程过程,姑且叫串口调试助手源程序V1.0或VC串口通讯源程序吧,我相信,如果你用VC编程,那么有了这个代码,就可以轻而易举地完成串口编程任务了。(也许本文过于详细,高手就不用看) 开始吧: 1.建立项目:打开VC++6.0,建立一个基于对话框的MFC应用程序SCommTest (与我源代码一致,等会你会方便一点); 2.在项目中插入MSComm控件选择Project菜单下Add To Project子菜单中的Components and Controls…选项,在弹出的对话框中双击Registered ActiveX Controls项(稍等一会,这个过程较慢),则所有注册过的ActiveX 控件出现在列表框中。选择Microsoft Communications Control, version 6.0,,单击Insert按钮将它插入到我们的Project中来,接受缺省的选项。(如果你在控件列表中看不到Microsoft Communications Control, version 6.0,那可能是你在安装VC6时没有把ActiveX一项选上,重新安装VC6,选上ActiveX就可以了),

51单片机与蓝牙串口通信程序

#include #include #include #include "LCD1602.h" #include "matrix_key.h" #define uint unsigned int #define uchar unsigned char #define Nop() _nop_() sbit P10 = P1^0; /*定义独立对地按键端口*/ sbit P11 = P1^1; /*定义独立对地按键端口*/ sbit P12 = P1^2; /*定义独立对地按键端口*/ sbit P13 = P1^3; /*定义独立对地按键端口*/ //shift键 bit shift_flag; bit call_flag ; bit CallIn_flag=0; bit reci_flag; bit reci_flag1; sbit sled_en_port = P3^6; /*定义数码管数据锁存器控制端口*/ sbit led_en_port = P2^5; /*定义发光二极管数据锁存器控制端口*/ sbit ds1302_en_port = P2^2; /*定义时钟的选片脚*/ uchar CallIn_Num[15];//={"00000000000"}; uchar CallOut_Num[15]={" "}; uchar m=0; //拨号指针 uchar temp='?'; uchar code clr[16]={" "}; uchar code lcd_table[16] = {"Ky: Cm: Re: "}; //uchar send_buff[15]; uchar reci_buff[15]={" "}; uchar z; //接收缓冲区指针 uchar time;//定时器中断次数 uchar code mun_to_char[]={"0123456789ABCDEF"}; /*1MS为单位的延时程序*/ void init(); void send(uchar cc); void send_f(uchar ccc); void interrupt_pro(); void key_pro(); void call_out();

经典的串口调试助手源代码.

Dim OutputAscii As Boolean Dim InputString As String Dim OutputString As String '=========================================================== =================== ======= ' 变量定义 '=========================================================== =================== ======= Option Explicit ' 强制显式声明 Dim ComSwitch As Boolean ' 串口开关状态判断

Dim FileData As String ' 要发送的文件暂存 Dim SendCount As Long ' 发送数据字节计数器 Dim ReceiveCount As Long ' 接收数据字节计数器 Dim InputSignal As String ' 接收缓冲暂存 Dim OutputSignal As String ' 发送数据暂存 Dim DisplaySwitch As Boolean ' 显示开关 Dim ModeSend As Boolean ' 发送方式判断 Dim Savetime As Single ' 时间数据暂存延时用 Dim SaveTextPath As String ' 保存文本路径 ' 网页超链接申明 Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long As Long Private Sub CloseCom( ' 关闭串口 On Error GoTo Err If MSComm.PortOpen = True Then MSComm.PortOpen = False ' 先判断串口是否打开,如果打开则先关闭 txtstatus.Text = "STATUS:COM Port Cloced" ' 串口状态显示 mnuconnect.Caption = "断开串口 "

51单片机串口通信

一、串口通信原理 串口通讯对单片机而言意义重大,不但可以实现将单片机的数据传输到计算机端,而且也能实现计算机对单片机的控制。由于其所需电缆线少,接线简单,所以在较远距离传输中,得到了广泛的运用。串口通信的工作原理请同学们参看教科书。 以下对串口通信中一些需要同学们注意的地方作一点说明: 1、波特率选择 波特率(Boud Rate)就是在串口通信中每秒能够发送的位数(bits/second)。MSC-51串行端口在四种工作模式下有不同的波特率计算方法。其中,模式0和模式2波特率计算很简单,请同学们参看教科书;模式1和模式3的波特率选择相同,故在此仅以工作模式1为例来说明串口通信波特率的选择。 在串行端口工作于模式1,其波特率将由计时/计数器1来产生,通常设置定时器工作于模式2(自动再加模式)。在此模式下波特率计算公式为:波特率=(1+SMOD)*晶振频率/(384*(256-TH1)) 其中,SMOD——寄存器PCON的第7位,称为波特率倍增位; TH1——定时器的重载值。 在选择波特率的时候需要考虑两点:首先,系统需要的通信速率。这要根据系统的运作特点,确定通信的频率范围。然后考虑通信时钟误差。使用同一晶振频率在选择不同的通信速率时通信时钟误差会有很大差别。为了通信的稳定,我们应该尽量选择时钟误差最小的频率进行通信。 下面举例说明波特率选择过程:假设系统要求的通信频率在20000bit/s以下,晶振频率为12MHz,设置SMOD=1(即波特率倍增)。则TH1=256-62500/波特率 根据波特率取值表,我们知道可以选取的波特率有:1200,2400,4800,9600,19200。列计数器重载值,通信误差如下表: 因此,在通信中,最好选用波特率为1200,2400,4800中的一个。 2、通信协议的使用 通信协议是通信设备在通信前的约定。单片机、计算机有了协议这种约定,通信双方才能明白对方的意图,以进行下一步动作。假定我们需要在PC机与单片机之间进行通信,在双方程式设计过程中,有如下约定:0xA1:单片机读取P0端口数据,并将读取数据返回PC机;0xA2:单片机从PC机接收一段控制数据;0xA3:单片机操作成功信息。 在系统工作过程中,单片机接收到PC机数据信息后,便查找协议,完成相应的操作。当单片机接收到0xA1时,读取P0端口数据,并将读取数据返回PC机;当单片机接收到0xA2时,单片机等待从PC机接收一段控制数据;当PC机接收到0xA3时,就表明单片机操作已经成功。 3、硬件连接 51单片机有一个全双工的串行通讯口,所以单片机和计算机之间可以方便地进行串口通讯。进行串行通讯时要满足一定的条件,比如计算机的串口是RS232电平的,而单片机的串口是TTL电平的,两者之间必须有一个电平转换电路,我们采用了专用芯片MAX232进行转换,虽然也可以用几个三极管进行模拟转换,但是还是用专用芯片更简单可靠。我们采用了三线制连接串口,也就是说和计算机的9针串口只连接其中的3根线:第5脚的GND、第2脚的RXD、第3脚的TXD。这是最简单的连接方法,但是对我们来说已经足够使用了,电路如下图所示,MAX232的第10脚和单片机的11脚连接,第9脚和单片机的10脚连接,第15脚和单片机的20脚连接。

相关主题