使用win32 API函数实现vc与arduino串口通信,通过vc发出指令,在arduino中点亮二极管灯...

想通过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;
}

 

转载于:https://www.cnblogs.com/gzy-zju-edu/articles/4484944.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值