📄 rs232.c
字号:
#define _X86_
#include <windef.h>
#include <stdarg.h>
#include <winbase.h>
#include <malloc.h>
#include <winnt.h>
#define RX_BUF_SIZE 1024
#define TX_BUF_SIZE 1024
DCB dcb;
HANDLE hCom1;
int open_com(void)
{
int dwSize;
LPCOMMPROP lpCom1Prop = (LPCOMMPROP)malloc(sizeof(COMMPROP));
hCom1 = CreateFile("COM1",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL);
SetupComm(hCom1,RX_BUF_SIZE,TX_BUF_SIZE);
lpCom1Prop->wPacketLength = sizeof(COMMPROP);
GetCommProperties(hCom1,lpCom1Prop);
dwSize = lpCom1Prop->wPacketLength;
free(lpCom1Prop);
lpCom1Prop = (LPCOMMPROP)malloc(dwSize);
GetCommProperties(hCom1,lpCom1Prop);
if(GetCommState(hCom1,&dcb) == 0)
return -1;
/*
typedef struct _DCB { // dcb
DWORD DCBlength; // sizeof(DCB)
DWORD BaudRate; // current baud rate
DWORD fBinary: 1; // binary mode, no EOF check
DWORD fParity: 1; // enable parity checking
DWORD fOutxCtsFlow:1; // CTS output flow control
DWORD fOutxDsrFlow:1; // DSR output flow control
DWORD fDtrControl:2; // DTR flow control type
DWORD fDsrSensitivity:1; // DSR sensitivity
DWORD fTXContinueOnXoff:1; // XOFF continues Tx
DWORD fOutX: 1; // XON/XOFF out flow control
DWORD fInX: 1; // XON/XOFF in flow control
DWORD fErrorChar: 1; // enable error replacement
DWORD fNull: 1; // enable null stripping
DWORD fRtsControl:2; // RTS flow control
DWORD fAbortOnError:1; // abort reads/writes on error
DWORD fDummy2:17; // reserved
WORD wReserved; // not currently used
WORD XonLim; // transmit XON threshold
WORD XoffLim; // transmit XOFF threshold
BYTE ByteSize; // number of bits/byte, 4-8
BYTE Parity; // 0-4=no,odd,even,mark,space
BYTE StopBits; // 0,1,2 = 1, 1.5, 2
char XonChar; // Tx and Rx XON character
char XoffChar; // Tx and Rx XOFF character
char ErrorChar; // error replacement character
char EofChar; // end of input character
char EvtChar; // received event character
WORD wReserved1; // reserved; do not use
} DCB;
*/
dcb.BaudRate = CBR_9600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
SetCommState(hCom1,&dcb);
dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fRtsControl = RTS_CONTROL_ENABLE;
return 0;
}
OVERLAPPED OverLapped;
void wait(int time)
{
Sleep(time);
}
int send_one_byte(char byte)
{
int nBytesWrite;
// int i;
Sleep(1);
WriteFile(hCom1,&byte,1,&nBytesWrite,&OverLapped);
return 0;
}
int send_bytes(char* pIn, int size)
{
int nBytesWrite;
// Sleep(1);
WriteFile(hCom1,pIn,size,&nBytesWrite,&OverLapped);
return 0;
}
int receive_one_byte(char* byte)
{
int nBytesRead;
Sleep(10);
ReadFile(hCom1,byte,1,&nBytesRead,&OverLapped);
if(nBytesRead == 1)
return 0;
else
return -1;
}
//free(lpCom1Prop);
void set_baud_rate(int baud)
{
dcb.BaudRate = baud;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
SetCommState(hCom1,&dcb);
}
void close_com(void)
{
CloseHandle(hCom1);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -