Serial Port

Hi! I want to know how to make arduino write in a usb port and how to read this to a c program at the same time. What I've got is:
Acess denied.

Post your code and explain what is connected to the Arduino and how it is connected

C code

#include <Windows.h>
#include <stdio.h>

void main(void)
	HANDLE hComm;                          // Handle to the Serial port
	char  ComPortName[] = "\\\\.\\COM3";  // Name of the Serial port(May Change) to be opened,
	BOOL  Status;                          // Status of the various operations 
	DWORD dwEventMask;                     // Event mask to trigger
	byte  SerialBuffer[4];               // Buffer Containing Rxed Data
	DWORD NoBytesRead;                     // Bytes read by ReadFile()
	int i = 0;

	printf("\n\n +==========================================+");
	printf("\n |    Serial Port  Reception (Win32 API)    |");
	printf("\n +==========================================+\n");
	/*---------------------------------- Opening the Serial Port -------------------------------------------*/

	hComm = CreateFile(ComPortName,                  // Name of the Port to be Opened
		GENERIC_READ | GENERIC_WRITE, // Read/Write Access
		0,                            // No Sharing, ports cant be shared
		NULL,                         // No Security
		OPEN_EXISTING,                // Open existing port only
		0,                            // Non Overlapped I/O
		NULL);                        // Null for Comm Devices

		printf("\n    Error! - Port %s can't be opened\n", ComPortName);
		printf("\n    Port %s Opened\n ", ComPortName);

	/*------------------------------- Setting the Parameters for the SerialPort ------------------------------*/

	DCB dcbSerialParams = { 0 };                         // Initializing DCB structure
	dcbSerialParams.DCBlength = sizeof(dcbSerialParams);

	Status = GetCommState(hComm, &dcbSerialParams);      //retreives  the current settings

	if (Status == FALSE)
		printf("\n    Error! in GetCommState()");

	dcbSerialParams.BaudRate = CBR_9600;      // Setting BaudRate = 9600
	dcbSerialParams.ByteSize = 8;             // Setting ByteSize = 8
	dcbSerialParams.StopBits = ONESTOPBIT;    // Setting StopBits = 1
	dcbSerialParams.Parity = NOPARITY;        // Setting Parity = None 

	Status = SetCommState(hComm, &dcbSerialParams);  //Configuring the port according to settings in DCB 

	if (Status == FALSE)
		printf("\n    Error! in Setting DCB Structure");
	else //If Successfull display the contents of the DCB Structure
		printf("\n\n    Setting DCB Structure Successfull\n");
		printf("\n       Baudrate = %d", dcbSerialParams.BaudRate);
		printf("\n       ByteSize = %d", dcbSerialParams.ByteSize);
		printf("\n       StopBits = %d", dcbSerialParams.StopBits);
		printf("\n       Parity   = %d", dcbSerialParams.Parity);

	/*------------------------------------ Setting Timeouts --------------------------------------------------*/

	COMMTIMEOUTS timeouts = { 0 };
	timeouts.ReadIntervalTimeout = 50;
	timeouts.ReadTotalTimeoutConstant = 50;
	timeouts.ReadTotalTimeoutMultiplier = 10;
	timeouts.WriteTotalTimeoutConstant = 50;
	timeouts.WriteTotalTimeoutMultiplier = 10;

	if (SetCommTimeouts(hComm, &timeouts) == FALSE)
		printf("\n\n    Error! in Setting Time Outs");
		printf("\n\n    Setting Serial Port Timeouts Successfull");

	/*------------------------------------ Setting Receive Mask ----------------------------------------------*/

	Status = SetCommMask(hComm, EV_RXCHAR); //Configure Windows to Monitor the serial device for Character Reception

	if (Status == FALSE)
		printf("\n\n    Error! in Setting CommMask");
		printf("\n\n    Setting CommMask successfull");

	/*------------------------------------ Setting WaitComm() Event   ----------------------------------------*/

	printf("\n\n    Waiting for Data Reception");

	Status = WaitCommEvent(hComm, &dwEventMask, NULL); //Wait for the character to be received

	/*-------------------------- Program will Wait here till a Character is received ------------------------*/

	if (Status == FALSE)
		printf("\n    Error! in Setting WaitCommEvent()");
	else //If  WaitCommEvent()==True Read the RXed data using ReadFile();
		printf("\n\n    Characters Received\n");
		Status = ReadFile(hComm, &SerialBuffer, sizeof(SerialBuffer), &NoBytesRead, NULL);

		printf("%d\n", SerialBuffer[0]);
		printf("%d\n", SerialBuffer[1]);
		printf("%d\n", SerialBuffer[2]);
		printf("%d\n", SerialBuffer[3]);

		/*------------Printing the RXed String to Console----------------------*/


	CloseHandle(hComm);//Closing the Serial Port
	printf("\n +==========================================+\n");
}//End of Main()

Arduino Code

void setup() {
  // put your setup code here, to run once:

void loop() {
  // put your main code here, to run repeatedly:

  int serialArrayOne[]  = {1,2,3,0};

 Serial.write( (uint8_t*)serialArrayOne, sizeof(serialArrayOne) );

What I want is recieve always 1, 2, 3, 0 in c program

What I want is recieve always 1, 2, 3, 0 in c program

What do you actually get ?
What do you see in the Serial monitor ?
What do you see on a terminal emulator running on the PC ?
Do you realise that the Arduino uses pins 0 and 1 when uploading code to the board ?

In the c program, sometimes I get 0, 1, 2, 3, sometimes I get 3,0, 1, 2…
It’s something like it write 1, then 2, then 3, … and not the whole array.

Send a linefeed after writing the array so that you can differentiate the separate lines of data. Now what do you get ?

Add a delay after sending the array. Does that improve things ?

What happens if you iterate through the array rather than sending it all at once ?

Other way around. The writer is writing in the correct order, just as fast as it can.

But the receiver might start receiving halfway along a message. So you get 2,3,0,1 which is the tail of one packet and the head of the next.

Your receiver needs to identify which character (or sequence of characters) is the start of each message packet. It should discard everything recieved before that.

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.

The technique in the 3rd example will be the most reliable. It is what I use for Arduino to Arduino and Arduino to PC communication.

You can send data in a compatible format with code like this (or the equivalent in any other programming language)

Serial.print('<'); // start marker
Serial.print(','); // comma separator
Serial.println('>'); // end marker


There is no way to synchronized? Because the last parameter in ReadFile function in c program is something about synchronized but I don't know how to use it.

What I’m trying to do is:
I have a Joystick, and I want to control the movements in games with Joystick.
So I’m trying to send the vector for C program. There is another to do that?
Thanks !

I have a Joystick, and I want to control the movements in games with Joystick.
So I'm trying to send the vector for C program. There is another to do that?
Thanks !

The example in Reply #7 should work fine for that - have you tried it? And it includes synchronization to make sure the receiving program knows when the message starts.


Or you could use an Arduino with native USB and make it appear as a joystick plugged in to USB. The Teensy series probably has the best support for this.

As an added bonus, it can be both a joystick and Serial at the same time. USB allows that.

Or a free solution is to make the C program send a 'READ_DATA' command or such, and when the Arduino receives that command it will send the vector. This should give you a synchronized feeling.

Functions to use in Arduino code would be

if (Serial.available())
        byte command = (byte);   // Read current command
        switch (command)                              // Switch on the command
        case READ_DATA:                              // If command was READ_DATA send the vector.
                Serial.write(new byte[]{ 1, 2, 3, 0 }, 4);