c串口編程實例
A. 如何用c語言寫一個讀、寫串口的程序
大致過程就是
配置串口通信,包括串口號、波特率、校驗位、停止位這些信息;
打開串口,和打開文件一樣,在Linux下是這樣,Windows下沒試過,估計也差不多;
發送數據,即寫串口,就跟寫文件類似;
讀取串口,用read就行。
具體的函數和配置參數可以參考一些別人的代碼。
B. 求c++串口通信實例源代碼
推薦看書
Visual C++_Turbo C串口通信編程實踐
需要 pdf 文檔 可以聯系
希望能解決您的問題。
C. 怎麼使用C編寫一個串口文件傳輸程序
#include
#include
int main(void)
{
FILE *fp;
char temp;
char buf[100];
if((fp = fopen("com3","r")) == NULL)
puts("this way doesn't work!\n");
else
puts("this way works!\n");
while(1)
{
temp = 0;
fscanf(fp,"%c",&temp);
if(temp != 0)
putchar(temp);
else
Sleep(100);
}
fclose(fp);
return 0;
}
:CONCATENATE(Text,Text……) 參數說明:T
D. 51單片機串口通信c語言編程
#include <REG52.H>
#define uchar unsigned char
#define uint unsigned int
sbit ring=P3^7;
sbit CASE1=P2^0;
sbit CASE2=P2^1;
sbit CASE3=P2^2;
sbit CASE4=P2^3;
uchar se=0,re=0;
uchar temp=0;
void wait(uint cnt)
{
while(--cnt);
}
//串口發送程序
void send(uchar se)
{
SBUF=se; //發送數據
while(TI == 0);
TI = 0;
}
//串口接收程序
uchar receive(void)
{
re=SBUF; //接收數據
while(RI==0);
RI=0;
return re;
}
//串口初始化
void sinti(void)
{
SCON = 0x50;
TMOD |= 0x20;
TH1 = 0xFD;
TR1 = 1;
EA = 1;
ES = 1;
}
void delay(int cnt)
{
while(--cnt);
}
//主程序
int main (void)
{
int i;
sinti(); //串口初始化程序
ring=1;
while(1)
{
while (1)
{
if(CASE1==0)
{
send('a');
ring=0;
break;
}
if(CASE2==0)
{
send('b');
ring=0;
break;
}
if(CASE3==0)
{
send('c');
ring=0;
break;
}
if(CASE4==0)
{
send('d');
ring=0;
break;
}
}
if(ring==0)
{
wait(60000);
ring=1;
}
for(i=0;i<10000;i++);
}
}
//串口中斷程序
void UART_SER (void) interrupt 4 //串列中斷服務程序
{
if(RI) //判斷是接收中斷產生
{
RI=0; //標志位清零
temp=SBUF;
}
if(TI) //如果是發送標志位,清零
TI=0;
}
E. c語言怎麼實現串口通信
編程原理 程序1為查詢通信方式介面程序,為一典型的數據採集常式。其中bioscom()函數初始化COM1(此函數實際調用BIOS INT 14H中斷0號功能)。這樣在程序中就避免了具體設置波特率因子等繁瑣工作,只需直接訪問發送/接收寄存器(3F8H)和線路狀態寄存
F. 誰能給我一個上位機控制下位機的串口通信程序(C語言編寫吧)
#include "stdafx.h"
#include "CommWizard.h"
#include "CommWizardDlg.h"
#include "SettingDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CCommWizardDlg dialog
CCommWizardDlg::CCommWizardDlg(CWnd* pParent /*=NULL*/)
: CDialog(CCommWizardDlg::IDD, pParent)
{
bSend = FALSE;
bReceive = FALSE;
m_nPort = 1;
m_strSettings = _T("9600,n,8,1");
m_strSendString = _T("");
m_nTime = 1000;
m_nInputMode = 1;
//{{AFX_DATA_INIT(CCommWizardDlg)
m_strReceive = _T("");
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CCommWizardDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CCommWizardDlg)
DDX_Control(pDX, IDC_RECEIVE, m_ctrlReceive);
DDX_Control(pDX, IDC_SEND, m_ctrlSend);
DDX_Control(pDX, IDC_TYPE, m_ctrlDataType);
DDX_Text(pDX, IDC_EDIT_RECEIVE, m_strReceive);
DDX_Control(pDX, IDC_COMMCTRL, m_Com);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CCommWizardDlg, CDialog)
//{{AFX_MSG_MAP(CCommWizardDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_RECEIVE, OnReceive)
ON_BN_CLICKED(IDC_SEND, OnSend)
ON_BN_CLICKED(IDC_SETTINGS, OnSettings)
ON_CBN_SELCHANGE(IDC_TYPE, OnSelchangeType)
ON_BN_CLICKED(IDC_CLEAR, OnClear)
ON_BN_CLICKED(IDC_MANUALSEND, OnManualsend)
ON_WM_TIMER()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CCommWizardDlg message handlers
BOOL CCommWizardDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
m_ctrlDataType.AddString(_T("按ASCII碼"));
m_ctrlDataType.AddString(_T("按2進制"));
m_ctrlDataType.AddString(_T("按16進制"));
m_ctrlDataType.SetCurSel(m_nInputMode);
return TRUE; // return TRUE unless you set the focus to a control
}
void CCommWizardDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CCommWizardDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CCommWizardDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CCommWizardDlg::OnReceive()
{
// TODO: Add your control notification handler code here
m_Com.GetInput();//先預讀緩沖區以清除殘留數據
bReceive = !bReceive;
if(bReceive)
m_ctrlReceive.SetWindowText(_T("停止接收"));
else
m_ctrlReceive.SetWindowText(_T("開始接收"));
}
void CCommWizardDlg::OnSend()
{
// TODO: Add your control notification handler code here
bSend = !bSend;
if(bSend)
{
m_ctrlSend.SetWindowText(_T("停止發送"));
SetTimer(1,m_nTime,NULL);//時間為1000毫秒
}
else
{
m_ctrlSend.SetWindowText(_T("自動發送"));
KillTimer(1); //取消定時
}
}
void CCommWizardDlg::OnSettings()
{
// TODO: Add your control notification handler code here
CSettingDlg setDlg;
setDlg.nPort = m_nPort;
setDlg.nTime = m_nTime;
setDlg.strSettings = m_strSettings;
setDlg.strSendString = m_strSendString;
if(setDlg.DoModal() == IDOK)
{
m_nPort = setDlg.nPort;
m_nTime = setDlg.nTime;
m_strSettings = setDlg.strSettings;
m_strSendString = setDlg.strSendString;
}
OpenPort();
}
void CCommWizardDlg::OnSelchangeType()
{
// TODO: Add your control notification handler code here
m_nInputMode = m_ctrlDataType.GetCurSel();
}
void CCommWizardDlg::OnClear()
{
// TODO: Add your control notification handler code here
m_strReceive = _T("");
}
BEGIN_EVENTSINK_MAP(CCommWizardDlg, CDialog)
//{{AFX_EVENTSINK_MAP(CCommWizardDlg)
ON_EVENT(CCommWizardDlg, IDC_COMMCTRL, 1 /* OnComm */, OnOnCommCommctrl, VTS_NONE)
//}}AFX_EVENTSINK_MAP
END_EVENTSINK_MAP()
void CCommWizardDlg::OnOnCommCommctrl()
{
// TODO: Add your control notification handler code here
VARIANT variant_inp;
COleSafeArray safearray_inp;
LONG len,k;
BYTE rxdata[2048]; //設置BYTE數組 An 8-bit integerthat is not signed.
CString strtemp;
if(bReceive)
{
if(m_Com.GetCommEvent()==2) //事件值為2表示接收緩沖區內有字元
{
variant_inp = m_Com.GetInput(); //讀緩沖區
safearray_inp = variant_inp; //VARIANT型變數轉換為ColeSafeArray型變數
len=safearray_inp.GetOneDimSize(); //得到有效數據長度
for(k=0;k<len;k++)
safearray_inp.GetElement(&k,rxdata+k);//轉換為BYTE型數組
for(k=0;k<len;k++) //將數組轉換為Cstring型變數
{
BYTE bt=*(char*)(rxdata+k); //字元型
if(m_nInputMode == 2)
strtemp.Format("%02X ",bt); //將字元以十六進制方式送入臨時變數strtemp存放,注意這里加入一個空隔
else
strtemp.Format("%c",bt); //將字元送入臨時變數strtemp存放
m_strReceive = m_strReceive + strtemp; //加入接收編輯框對應字元串
}
m_strReceive += "\r\n";
}
}
UpdateData(FALSE); //更新編輯框內容
}
void CCommWizardDlg::OpenPort()
{
if(m_Com.GetPortOpen())
m_Com.SetPortOpen(FALSE);
m_Com.SetCommPort(m_nPort); //選擇com1
if( !m_Com.GetPortOpen())
m_Com.SetPortOpen(TRUE);//打開串口
else
AfxMessageBox("cannot open serial port");
m_Com.SetSettings(m_strSettings); //波特率9600,無校驗,8個數據位,1個停止位
m_Com.SetRThreshold(1);
//參數1表示每當串口接收緩沖區中有多於或等於1個字元時將引發一個接收數據的OnComm事件
m_Com.SetInputMode(1);
m_Com.SetInputLen(0); //設置當前接收區數據長度為0
m_Com.GetInput();//先預讀緩沖區以清除殘留數據
}
void CCommWizardDlg::OnManualsend()
{
// TODO: Add your control notification handler code here
CString strSend;
if(m_nInputMode > 1)
{
CByteArray hexdata;
int len=String2Hex(m_strSendString ,hexdata);
m_Com.SetOutput(COleVariant(hexdata));
}
else
m_Com.SetOutput(COleVariant(m_strSendString));//發送數據
}
void CCommWizardDlg::OnTimer(UINT nIDEvent)
{
// TODO: Add your message handler code here and/or call default
OnManualsend();
CDialog::OnTimer(nIDEvent);
}
int CCommWizardDlg::String2Hex(CString str, CByteArray &senddata)
{
int hexdata,lowhexdata;
int hexdatalen=0;
int len=str.GetLength();
senddata.SetSize(len/2);
for(int i=0;i<len;)
{
char lstr,hstr=str[i];
if(hstr==' ')
{
i++;
continue;
}
i++;
if(i>=len)
break;
lstr=str[i];
hexdata=ConvertHexChar(hstr);
lowhexdata=ConvertHexChar(lstr);
if((hexdata==16)||(lowhexdata==16))
break;
else
hexdata=hexdata*16+lowhexdata;
i++;
senddata[hexdatalen]=(char)hexdata;
hexdatalen++;
}
senddata.SetSize(hexdatalen);
return hexdatalen;
}
//這是一個將字元轉換為相應的十六進制值的函數
//功能:若是在0-F之間的字元,則轉換為相應的十六進制字元,否則返回-1
char CCommWizardDlg::ConvertHexChar(char ch)
{
if((ch>='0')&&(ch<='9'))
return ch-0x30;
else if((ch>='A')&&(ch<='F'))
return ch-'A'+10;
else if((ch>='a')&&(ch<='f'))
return ch-'a'+10;
else return (-1);
}
G. 急!!!單片機C語言實現串口通信編程
如果在字元數字發送框發0X00蜂鈴器就會叫,如果發0xff蜂鈴器就停叫。
#include <REG52.H>
#include <stdio.h>
sbit BEEP = P1^4;
unsigned char b;
void main (void) {
SCON = 0x50; //REN=1允許串列接受狀態,串口工作模式1
TMOD|= 0x20; //定時器工作方式2
PCON|= 0x80;
//TH1 = 0xFD; //baud*2 /* reload value 19200、數據位8、停止位1。效驗位無 (11.0592)
TH1 = 0xF3; // //baud*2 /* 波特率4800、數據位8、停止位1。效驗位無 (12M)
TL1 = 0xF3;
TR1 = 1;
ES = 1; //開串口中斷
EA = 1; // 開總中斷
BEEP=1;
// IE = 0x0;
while(1)
{
if (RI) //RI接受中斷標志
{ RI=0; //清除RI接受中斷標志
b=SBUF; //SUBF接受/發送緩沖器
}
BEEP=b;
}
}
這個是個發送程序,接收程序類似,不懂可繼續追問,一般人都是在別人程序基礎上改改稱為自己的,希望樓主能夠自己研究出自己的一套編程理論
H. 編寫單片機串口收發數據的完整程序(C語言編寫)
我用的新唐晶元,8051內核,跟51差不多,望採納
void UART_Initial (void)
{
P02_Quasi_Mode; //Setting UART pin as Quasi mode for transmit
P16_Quasi_Mode; //Setting UART pin as Quasi mode for transmit
SCON_1 = 0x50; //UART1 Mode1,REN_1=1,TI_1=1
T3CON = 0x08; //T3PS2=0,T3PS1=0,T3PS0=0(Prescale=1), UART1 in MODE 1
clr_BRCK;
RH3 = HIBYTE(65536 - (1000000/u32Baudrate)-1); /*16 MHz */
RL3 = LOBYTE(65536 - (1000000/u32Baudrate)-1); /*16 MHz */
set_TR3; //Trigger Timer3
}
以上是初始化的
void Send_Data_To_UART1(UINT8 c)
{
TI_1 = 0;
SBUF_1 = c;
while(TI_1==0);
}
這個是發送
void UART_isr (void) interrupt 4 //串列中斷服務程序
{
if (RI_1==1)
{ /* if reception occur */
clr_RI_1; /* clear reception flag for next reception */
Receive_Date[c] = SBUF_1;
if (Receive_Date[0] == First_Date)
{
c++;
}
else if(Receive_Date_Size > 0 && Receive_Date_Size < 4)
{
c++;
}
else if(Receive_Date[c] == Last_Date && Receive_Date_Size ==4)
{
c = 0;
Flag_Receive_One = 1;
}
else
{
c = 0;
}
}
}
接收
I. 求一個C語言編程的簡單串口接收數據程序,能讓我參考一下
你好!!
給你一個完整的串口通訊常式,已經調試通過的!
J. Windows下的C語言串口編程
大概說下思路,串口在編程里相當於一個文件,因此要創建句柄來操作,還要給DCB結構休賦值進行串口配置等,你可以查下DCB結構體,記得在DOS下編程時,使用#include
<windows.h>。藏的深是為了更簡單的使用。還有就是由於接受要一直進行檢測,所以一般都專門開一線程進行監聽。