想通过vc来点亮二极管灯,思路为:
1、在arduino IDE编写好用于控制二极管灯程序,然后将其烧录到板子上
2、在vc中编写串口程序,用于向串口发送指令,实现vc与arduino串口通信;
在arduino中编写的程序:
int buf; //定义串口发送的内容 int pin=4; //二极管输出控制管脚 void setup() { // put your setup code here, to run once: Serial.begin(9600); //设置比特率 pinMode(pin,OUTPUT); //定义4号管脚为输出控制 } void loop() { // put your main code here, to run repeatedly: buf=Serial.read(); digitalWrite(pin,HIGH); //4号管脚置为高电平 if(buf=='R') { digitalWrite(pin,LOW); //4号管脚为低电平 delay(1000); //延迟1s } }
在vc中编写的程序为:
// comtest.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "windows.h" #include <stdio.h> #include <conio.h> int _tmain(int argc, _TCHAR* argv[]) { char test[]="R"; //点亮 //创建串口 HANDLE hDevice=CreateFile(L"\\\\.\\COM11", //注意COM1~COM10与COM10以上的窗口的命名规则 GENERIC_READ|GENERIC_WRITE, //使用读写方式 0, 0, OPEN_EXISTING, 0, 0); if (hDevice!=INVALID_HANDLE_VALUE) { printf("Port opened!\n"); DCB lpTest; GetCommState(hDevice,&lpTest); //获取当前的参数设置 lpTest.BaudRate=CBR_9600; //设置波特率 lpTest.ByteSize=8; //数据位数为8 lpTest.Parity=NOPARITY; //无校验 lpTest.StopBits = ONESTOPBIT; //1位停止位 SetCommState(hDevice,&lpTest); //设置通信参数 DWORD btsIO; while(true) { WriteFile(hDevice,test,strlen(test),&btsIO,NULL); //发送数据 Sleep(2000); //让程序暂停2s中,让二极管处在低电平维持一段时间 } CloseHandle(hDevice); //关闭串口 } return 0; }