Serial communication (for Arduino) using Visual Studio 2008 and C

淺唱寂寞╮ 提交于 2020-01-04 06:01:29

问题


I want to send data to my Arduino board using Visual Studio and C. I specifically need to use C since I am using ARToolKit to get markers and sending the data accordingly.

I was trying the code

#include<stdio.h>
#include<stdlib.h>
void main()
{
    system( "MODE COM9: BAUD=9600 PARITY=n DATA=8 STOP=1" ) ;
    FILE port = fopen( "COM9:", "wb" ) ;
    printf("hello");
    fprintf( port, "s" ) ;
    fclose( port ) ;
}

but it is not getting compiled.

I just need to send data.


回答1:


I understood from your post that you need to send data using visual studio not to write a program to flash or any other stuff. Here is an example i made for you on my machine it works sending the text test.

#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>
#include <conio.h>


int _tmain(int argc, _TCHAR* argv[])
{
    char test[] = "Hello";

    HANDLE hDevice = CreateFile(L"COM2",GENERIC_READ | GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,NULL,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;
        lpTest.Parity = NOPARITY;
        lpTest.StopBits = ONESTOPBIT;
        SetCommState(hDevice,&lpTest);

        DWORD btsIO;

        WriteFile(hDevice,test,strlen(test),&btsIO,NULL);

        CloseHandle(hDevice);
    }
    _getch();


    return 0;
}



回答2:


First thing to check is can you communicate to the arduino serial port at all. If you have XP or earlier it comes with hyperterm, windows vista+7 don't so you need something like http://ttssh2.sourceforge.jp/

ps - I'm not sure that the mode parameters created in a system call 'stick' to the calling environment or are reset when the shell exits. See example of windows serial port programming on how to do it properly




回答3:


CPPWindows works but it is also in C++. For all of you who want to send serial data with OPENCV/ARTOOLKIT or something which is written in C (and not C++). The code i posted is working now. It required some changes. The final code is: (Not the change in the COM port)

#include<stdio.h>
#include<stdlib.h>
void main()
{
    FILE* port;
    system( "MODE COM1: BAUD=9600 PARITY=n DATA=8 STOP=1" ) ;
    port = fopen( "COM1:", "wb" ) ;
    printf("s");
    fprintf( port, "s" ) ;
    fclose( port ) ;
}


来源:https://stackoverflow.com/questions/8123057/serial-communication-for-arduino-using-visual-studio-2008-and-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!