Pages: [1]   Go Down
Author Topic: arduino input in my C++ tutorial  (Read 691 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 3
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi,
I am somewhat fluent in STD C++ coding, but I have little experience with the windows.h library.

I am currently working on a project that involve using my arduino as an input device, and I would need to get serial input in my program.

I've been messing with that almost all day long, and I can't get anything to work. So i figured out, maybe someone else areally figured this stuff out before me, and could give me a hand on some examples script? I found some on google, but I'm not much expert with Windows C++ & serial communication.

Could anyone give me a hand here?

Thank You,
-Vincent
Logged

0
Offline Offline
Newbie
*
Karma: 1
Posts: 13
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

This is a simple little library i put together to talk to my arduino.
It's C, so you can use it w/ C++, or make it into a class or whatever.

Code:
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

HANDLE hSerial;

int serialOpen(char *name);
BOOL serialRead(unsigned char *byte);
int serialWrite(unsigned char *data, int size);

//open Serial port; pass "COM1"/"COM2"/... for file name
int serialOpen(char *name)
{
      DCB dSerial;

      hSerial = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
      if(hSerial == INVALID_HANDLE_VALUE)
            return -1;
  
    if(!GetCommState(hSerial, &dSerial))
            return -2;

    dSerial.BaudRate=CBR_9600;
    dSerial.ByteSize=8;
    dSerial.StopBits=ONESTOPBIT;
    dSerial.Parity=NOPARITY;

    if(!SetCommState(hSerial, &dSerial))
            return -3;
      
      return 0;
}

//read a single byte from the serial port
BOOL serialRead(unsigned char *byte)
{
      int readSize;

      if(ReadFile(hSerial, byte, 1, &readSize, NULL))
            if(readSize)
                  return TRUE;

      return FALSE;
}

//write size bytes from data array
int serialWrite(unsigned char *data, int size)
{
      unsigned int wrote;

      WriteFile(hSerial, data, size, &wrote, NULL);
      return wrote;
}
Logged

Pages: [1]   Go Up
Jump to: