pc 串口发送 c语言,【求助】51单片机串口发送接收问题(PC向单片机发送1位字符,单片机接收后发回PC)...
时间: 2023-07-30 11:10:17 浏览: 89
51单片机串口通信的发送与接收 字符串
5星 · 资源好评率100%
你可以参考下面这段代码实现PC向单片机发送一个字符,单片机接收后再回传给PC:
PC端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
HANDLE hComm;
BOOL fSuccess;
DWORD dwBytesRead, dwBytesWritten;
char ch = 'A';
char szBuff[100];
hComm = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hComm == INVALID_HANDLE_VALUE)
{
printf("Error in opening serial port\n");
return 0;
}
DCB dcb;
dcb.DCBlength = sizeof(DCB);
fSuccess = GetCommState(hComm, &dcb);
if (!fSuccess)
{
printf("Error in GetCommState\n");
CloseHandle(hComm);
return 0;
}
dcb.BaudRate = CBR_9600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
fSuccess = SetCommState(hComm, &dcb);
if (!fSuccess)
{
printf("Error in SetCommState\n");
CloseHandle(hComm);
return 0;
}
fSuccess = WriteFile(hComm, &ch, 1, &dwBytesWritten, NULL);
if (!fSuccess)
{
printf("Error in WriteFile\n");
CloseHandle(hComm);
return 0;
}
fSuccess = ReadFile(hComm, szBuff, sizeof(szBuff), &dwBytesRead, NULL);
if (!fSuccess)
{
printf("Error in ReadFile\n");
CloseHandle(hComm);
return 0;
}
szBuff[dwBytesRead] = 0;
printf("Received: %s\n", szBuff);
CloseHandle(hComm);
return 0;
}
```
单片机端代码:
```c
#include <reg51.h>
#include <stdio.h>
#define uchar unsigned char
#define uint unsigned int
sbit TX = P3^1;
sbit RX = P3^0;
void InitUART()
{
TMOD |= 0x20;
TH1 = 0xFD;
TL1 = 0xFD;
SCON = 0x50;
TR1 = 1;
}
void SendData(uchar ch)
{
SBUF = ch;
while (!TI);
TI = 0;
}
uchar ReceiveData()
{
while (!RI);
RI = 0;
return SBUF;
}
void main()
{
uchar ch;
InitUART();
while (1)
{
ch = ReceiveData();
SendData(ch);
}
}
```
这段代码实现了PC向单片机发送一个字符,单片机接收后再回传给PC。注意,单片机端代码使用了51单片机,如果你使用的是其他单片机,需要相应地修改代码。同时,需要在PC端的代码中修改串口号和波特率。
阅读全文