编程原理
创新互联建站是一家专注于成都网站设计、成都网站建设与策划设计,黄南州网站建设哪家好?创新互联建站做网站,专注于网站建设十多年,网设计领域的专业建站公司;建站业务涵盖:黄南州等地区。黄南州做网站价格咨询:18982081108
程序1为查询通信方式接口程序,为一典型的数据采集例程。其中bioscom()函数初始化COM1(此函数实际调用BIOS
INT
14H中断0号功能)。这样在程序中就避免了具体设置波特率因子等繁琐工作,只需直接访问发送/接收寄存器(3F8H)和线路状态寄存
#include reg51.h
#include intrins.h
unsigned char key_s, key_v, tmp;
char code str[] = "welcome! \n\r";
void send_str();
bit scan_key();
void proc_key();
void delayms(unsigned char ms);
void send_char(unsigned char txd);
sbit K1 = P1^4;
main()
{
TMOD = 0x20; // 定时器1工作于8位自动重载模式, 用于产生波特率
TH1 = 0xFD; // 波特率9600
TL1 = 0xFD;
SCON = 0x50; // 设定串行口工作方式
PCON = 0xef; // 波特率不倍增
TR1 = 1; // 启动定时器1
IE = 0x0; // 禁止任何中断
while(1)
{
if(scan_key()) // 扫描按键
{
delayms(10); // 延时去抖动
if(scan_key()) // 再次扫描
{
key_v = key_s; // 保存键值
proc_key(); // 键处理
}
}
if(RI) // 是否有数据到来
{
RI = 0;
tmp = SBUF; // 暂存接收到的数据
P0 = tmp; // 数据传送到P0口
send_char(tmp); // 回传接收到的数据
}
}
}
bit scan_key()
// 扫描按键
{
key_s = 0x00;
key_s |= K1;
return(key_s ^ key_v);
}
void proc_key()
// 键处理
{
if((key_v 0x01) == 0)
{ // K1按下
send_str(); // 传送字串"welcome!...
}
}
void send_char(unsigned char txd)
// 传送一个字符
{
SBUF = txd;
while(!TI); // 等特数据传送
TI = 0; // 清除数据传送标志
}
void send_str()
// 传送字串
{
unsigned char i = 0;
while(str[i] != '\0')
{
SBUF = str[i];
while(!TI); // 等特数据传送
TI = 0; // 清除数据传送标志
i++; // 下一个字符
}
}
void delayms(unsigned char ms)
// 延时子程序
{
unsigned char i;
while(ms--)
{
for(i = 0; i 120; i++);
}
}
拓展资料
C语言是一门通用计算机编程语言,应用广泛。C语言的设计目标是提供一种能以简易的方式编译、处理低级存储器、产生少量的机器码以及不需要任何运行环境支持便能运行的编程语言。
尽管C语言提供了许多低级处理的功能,但仍然保持着良好跨平台的特性,以一个标准规格写出的C语言程序可在许多电脑平台上进行编译,甚至包含一些嵌入式处理器(单片机或称MCU)以及超级电脑等作业平台。
二十世纪八十年代,为了避免各开发厂商用的C语言语法产生差异,由美国国家标准局为C语言制定了一套完整的美国国家标准语法,称为ANSI C,作为C语言最初的标准。目前2011年12月8日,国际标准化组织(ISO)和国际电工委员会(IEC)发布的C11标准是C语言的第三个官方标准,也是C语言的最新标准,该标准更好的支持了汉字函数名和汉字标识符,一定程度上实现了汉字编程。
我写的串口通信代码比较长,给几个关键函数你吧,可实现PC与单片机的双工通信
/*串口通讯 单片机晶振:11.0592MHz
T1工作于方式2 波特率=2^smod*fosc/32/12/(256-X)*/
#includecommon.h
void do_uart(void); //串口接收执字符时的操作
/*串口发送字符串 */
void sendstr(uchar *p)
{
while(*p!='\0')
{ SBUF=*p; //待发送的数据写入缓冲区
while(!TI); //等待发送完成
TI=0; //清零发送标志位
p++; //指针加1
cnt_s++; //发送计数
}
}
/*串口接收中断函数*/
void int_rec(void) interrupt 4 using 2
{
if(RI) //查询接收标志位(有数据发送过来时置为1)
{
RI = 0; //接收标志位清零
// sendchar(SBUF);//让从电脑上传到单片机的数据,传回的电脑显示
do_uart();//对接受到得字符操作
}
}
/*串口初始化*/
void com_init(uint baud)
{
SCON = 0x50; //串口工作方式为1,串行允许接受
TMOD = 0x21; //定时器1工作在方式2 定时器0工作在方式1
//PCON = 0x80; //SMOD = 1; 波特率加倍
TH1=256-fosc/32/12/baud;
TL1=TH1;
ES = 1; //开串口中断
TR1 = 1; //允许定时器1工作
EA = 1; //开总中断
}
void sendchar(uchar uart_dat) //串口发送字符函数
{
SBUF = uart_dat; //待发送的数据写入缓冲区
while(!TI); //等待发送完成
TI = 0; //清零发送标志位
cnt_s++; //发送计数
}
C语言会有操作串口的库函数的,按照串口库函数标识实现调用就可以了。
基本方法是使用CreateFile来建立一个串口文件,然后用overlap的方式进行读写
#define SERAIL_PORT_BUF_MAX (1024*8)
typedef HRESULT (*PFN_CMD_PARSE_DATA)(HANDLE hParseApp, LPCSTR szRspCmd, int nCmdLen);
class CUsbSrvApp// : public CWinApp
{
public:
CUsbSrvApp();
~CUsbSrvApp();
BOOL OnSendData(const char *szBuf, int nLen);// 发送数据
int ComConnect(CString strPort); // 连接COM口
HANDLE OpenComPort(CString strPort, int nBaudRate, int nDataBits, int nStopBits, int nParity, int nFlowCtrlType); // 打开串口
void Close(); // 关闭串口
HANDLE m_hCom;
BOOL m_bConnected;
OVERLAPPED m_OverlappedRead;
OVERLAPPED m_OverlappedWrite;
CWinThread *m_pThread;
PFN_CMD_PARSE_DATA m_pRspCmdFunc; // 用来处理接受数据的CALLBACK
HANDLE m_hParseApp;
};
CUsbSrvApp::CUsbSrvApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
m_bConnected = false;
m_hCom = NULL;
m_pRspCmdFunc = NULL;
}
CUsbSrvApp::~CUsbSrvApp()
{
}
//打开串口通信,并返回串口句柄
HANDLE CUsbSrvApp::OpenComPort(CString strPortName,
int nBaudRate,
int nDataBits,
int nStopBits,
int nParity,
int nFlowCtrlType)
{
DCB dcb;
COMMTIMEOUTS CommTimeOuts ;
COMMCONFIG ComConfig;
HANDLE hComPort;
CString strPort;
strPort.Format("\\\\.\\%s",strPortName); // COM口的文件名应该是 \\.\COMXX
//打开窗口其实就是创建一个文件
hComPort = CreateFile(strPort,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,
NULL);
if (INVALID_HANDLE_VALUE == hComPort)
return INVALID_HANDLE_VALUE;
// 设置一些COM口通讯参数和OVERLAP
CommTimeOuts.ReadIntervalTimeout = -1;
CommTimeOuts.ReadTotalTimeoutConstant = 0;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0;
CommTimeOuts.WriteTotalTimeoutConstant = 0;
CommTimeOuts.WriteTotalTimeoutMultiplier = 0x1388;
SetCommTimeouts( m_hCom, CommTimeOuts ) ;
SetDefaultCommConfig(strPortName, ComConfig, sizeof(COMMCONFIG));
GetCommState(m_hCom, dcb ) ;
dcb.BaudRate = nBaudRate;
dcb.ByteSize = nDataBits;
dcb.StopBits = nStopBits;
dcb.fParity = (NOPARITY != nParity);
dcb.Parity = nParity;
//set the receive char
dcb.EvtChar = 0x0D;
switch(nFlowCtrlType)
{
case 0: //no flow control
break;
case 1://HARD_FLOW_CTRL:
dcb.fOutxCtsFlow = TRUE;
dcb.fOutxDsrFlow = TRUE;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fDsrSensitivity = TRUE;
dcb.fRtsControl = RTS_CONTROL_TOGGLE;
break;
case 2://SOFT_FLOW_CTRL:
dcb.fOutX = TRUE;
dcb.fInX = TRUE;
break;
}
BuildCommDCB(_T("baud=115200 parity=N data=8 stop=1"),dcb);
SetCommState(hComPort, dcb ) ;
SetCommMask(hComPort, 0);
SetCommMask(hComPort, EV_RXCHAR|EV_CTS|EV_DSR|EV_RLSD|EV_RING);
SetupComm( hComPort, SERAIL_PORT_BUF_MAX,SERAIL_PORT_BUF_MAX) ;
//clear read and write buffer
PurgeComm( hComPort, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR );
return hComPort;
}
void CUsbSrvApp::Close()
{
if(m_bConnected)
{
m_bConnected = false;
CloseHandle(m_hCom);
m_hCom = NULL;
}
}
// 这个线程是监视串口数据,一旦有数据则读取并调用CALLBACK通知客户端
UINT ReceiveComData(LPVOID pParam)
{
CUsbSrvApp *pUsbSrv = (CUsbSrvApp *)pParam;
HANDLE hComPort = pUsbSrv-m_hCom;
DWORD dwEvtMask=0;
DWORD dwErrorFlags;
SetCommMask( hComPort, EV_RXCHAR);
OVERLAPPED osRead;
osRead.hEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
DWORD dwTransfer = 0;
while(pUsbSrv-m_bConnected)
{
if( !WaitCommEvent( hComPort, dwEvtMask,osRead))
{
if( GetLastError()== ERROR_IO_PENDING)
{
WaitForSingleObject(osRead.hEvent, INFINITE);
if(dwEvtMaskEV_RXCHAR==EV_RXCHAR)
{
COMSTAT ComStat={0} ;
DWORD dwReadLen = 0;
DWORD dwBytesRead = 0;
DWORD dwTotalLen = 0;
ClearCommError(hComPort, dwErrorFlags, ComStat );
dwTotalLen = ComStat.cbInQue;
dwReadLen = (SERAIL_PORT_BUF_MAX dwTotalLen)?dwTotalLen:SERAIL_PORT_BUF_MAX;
BYTE *pBuf = new BYTE[dwTotalLen+1];
memset(pBuf, 0 , dwTotalLen+1);
DWORD nReadBufLen=0;
while(dwTotalLen0)
{
if(FALSE == ReadFile( hComPort, pBuf+nReadBufLen,dwReadLen, dwBytesRead,pUsbSrv-m_OverlappedRead))
{
if(GetLastError() == ERROR_IO_PENDING)
{
GetOverlappedResult(hComPort,osRead, dwTransfer, TRUE );
}
break;
}
nReadBufLen +=dwBytesRead;
dwTotalLen -=dwBytesRead;
dwReadLen -= dwBytesRead;
dwReadLen = (SERAIL_PORT_BUF_MAXdwReadLen)?dwReadLen:SERAIL_PORT_BUF_MAX;
}
if(pUsbSrv-m_pRspCmdFunc!=NULLnReadBufLen!=0)
{
pUsbSrv-m_pRspCmdFunc(pUsbSrv-m_hParseApp, (char*)pBuf,nReadBufLen);
}
delete pBuf;
ClearCommError(hComPort, dwErrorFlags, ComStat );
int len =0;//= m_retList.GetSize();
}//endif if(dwEvtMaskEV_RXCHAR==EV_RXCHAR)
}//endif if( GetLastError()== ERROR_IO_PENDING)
}//endif if( !WaitCommEvent( hComPort, dwEvtMask,o))
else
{
if(GetLastError() == ERROR_IO_PENDING) {
GetOverlappedResult(hComPort, osRead, dwTransfer, TRUE ); // sleep thread
}
}
Sleep(1);
} //endwhile while(m_bConnected)
return 0;
}
int CUsbSrvApp::ComConnect(CString strPort)
{
int nBaudRate = 115200;
int nDataBits = 8;
int nStopBits = 1;
int nParity = 0;
int nFlowCtrl = 1;
if (NULL != m_hCom || m_bConnected)
{
return 0;
}
m_hCom = OpenComPort(strPort,nBaudRate,nDataBits,nStopBits,nParity,nFlowCtrl);
if( INVALID_HANDLE_VALUE == m_hCom)
{
m_hCom = NULL;
return 0;
}
memset( m_OverlappedRead, 0, sizeof( OVERLAPPED ) );
memset( m_OverlappedWrite, 0, sizeof( OVERLAPPED ) );
m_OverlappedRead.hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
m_OverlappedWrite.hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
m_pThread = AfxBeginThread( ReceiveComData,(void*)this,THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED ,NULL );
if( NULL == m_pThread )
{
CloseHandle( m_hCom );
m_hCom = NULL;
return FALSE;
}
else
{
m_bConnected = TRUE;
m_pThread-ResumeThread( );
}
return TRUE;
}
int CUsbSrvApp::OnSendData(const char *szBuf, int nLen)
{
BOOL bWriteStat;
BOOL bWrite = TRUE;
DWORD dwBytesWrite = 0;
DWORD dwBytesWritten = 0;
int dwByteswrittenTotal = 0;
if (NULL == m_hCom)
return 0;
int nSentTimes=0;
while(dwByteswrittenTotalnLennSentTimes10)
{
nSentTimes++;
dwBytesWrite = nLen-dwByteswrittenTotal;
bWriteStat = WriteFile( m_hCom, szBuf+dwByteswrittenTotal, dwBytesWrite, dwBytesWritten, m_OverlappedWrite );
if( !bWriteStat)
{
if ( GetLastError() == ERROR_IO_PENDING )
{
dwBytesWritten = 0;
bWrite = FALSE;
}
}
if (!bWrite)
{
bWrite = TRUE;
bWriteStat = GetOverlappedResult(m_hCom, // Handle to COMM port
m_OverlappedWrite, // Overlapped structure
dwBytesWritten, // Stores number of bytes sent
TRUE); // Wait flag
//deal with the error code
}
dwByteswrittenTotal += dwBytesWritten;
}
if(dwByteswrittenTotalnLen)
return 0;
else
return 1;
}
贴上来的程序部分,修改如下:
#includereg52.h
#includestdio.h //打印到串口函数
#define uchar unsigned char
#define uint unsigned int
uchar date_zi[4][11]; //存放接收到的数据
uint i_index=0; //接收到的字符个数
uint i=0; //i字符用于循环
unsigned int xia = 0; //用于保存到数据的下标
void fh_zi(uchar a) //返回字符到串口
{
ES=0;
SBUF=a;
while(!TI);
TI=0;
ES=1;
}
void init()
{
TMOD=0x20;
TH1=0xfd;
TL1=0Xfd;
//TH0=(65536-45872)/256;
//TL0=(65536-45872)%256;
TR1=1;
SM0=0;
SM1=1;
REN=1;
EA=1;
ES=1;
}
void main()
{
i_index=0;
xia=2;
init();
while(1);
}
void ser() interrupt 4 //串口
{
if(RI == 1)
{
RI=0;
date_zi[xia][i_index] = SBUF;
i_index++;
if(i_index10) //接受完10个字符后显示数组所有内容
{
i_index=0;
for(i=0;i11;i++) //显示数组中所有内容
fh_zi(date_zi[0][i]);
for(i=0;i11;i++)
fh_zi(date_zi[1][i]);
for(i=0;i11;i++)
fh_zi(date_zi[2][i]);
for(i=0;i11;i++)
fh_zi(date_zi[3][i]);
}
}
}