用C语言实现通过SecrueCRT向开发板发送on,按下回车后LED灯亮并返回字符”led on”;输入off按下回车后LED灯灭并返回字符”led off”,其他返回”command error”。
时间: 2023-06-03 19:06:42 浏览: 95
好的,此问题属于技术问题。以下给出通过C语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Windows.h>
int main() {
HANDLE hSerial = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); //打开串口
if (hSerial == INVALID_HANDLE_VALUE) {
printf("无法打开串口\n");
return 1;
}
DCB dcbSerialParams = { 0 };
dcbSerialParams.DCBlength = sizeof(dcbSerialParams); //取得当前串口的配置参数
if (!GetCommState(hSerial, &dcbSerialParams)) {
printf("获取串口配置参数失败\n");
CloseHandle(hSerial);
return 1;
}
dcbSerialParams.BaudRate = CBR_9600; //设置波特率为9600
dcbSerialParams.ByteSize = 8; //设置数据位为8
dcbSerialParams.StopBits = ONESTOPBIT; //设置停止位为1
dcbSerialParams.Parity = NOPARITY; //设置无奇偶校验
if (!SetCommState(hSerial, &dcbSerialParams)) { //应用新的配置参数
printf("设置串口配置参数失败\n");
CloseHandle(hSerial);
return 1;
}
char buffer[256];
memset(buffer, 0, sizeof(buffer));
while (1) {
printf("请输入命令(on/off):");
fgets(buffer, sizeof(buffer), stdin); //从控制台读取输入命令
buffer[strlen(buffer) - 1] = '\0'; //去掉换行符
if (strcmp(buffer, "on") == 0 || strcmp(buffer, "off") == 0) { //判断命令是否为on或off
DWORD dwBytesWritten = 0;
WriteFile(hSerial, buffer, strlen(buffer), &dwBytesWritten, NULL); //将命令发送给开发板
char receiveBuffer[256];
memset(receiveBuffer, 0, sizeof(receiveBuffer));
DWORD dwBytesRead = 0;
ReadFile(hSerial, receiveBuffer, sizeof(receiveBuffer), &dwBytesRead, NULL); //接收从开发板返回的数据
printf("%s\n", receiveBuffer);
}
else {
printf("command error\n");
}
}
CloseHandle(hSerial); //关闭串口
return 0;
}
```
需要注意的是,COM1是开发板所连接的串口号,如果不是COM1,请修改该参数。
阅读全文