Invalid values COM PORT

Hello, I’m getting problem by serial read in C.

Arduino Code:

int joystickEstadoAtual;
int aux = 0;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

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

  if(aux == 0){
    joystickEstadoAtual = 20;
    aux = 1;
  }
  else{
    joystickEstadoAtual = 10;
    aux = 0;
    
    }
  //Serial.print(joystickEstadoAtual);
Serial.write((const uint8_t *)&joystickEstadoAtual, sizeof(joystickEstadoAtual));
    
}

C Code:

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


void openPort(HANDLE* hComm);
BOOL settings(HANDLE hComm);
void closePort(HANDLE hComm);



void main(void)
{
	HANDLE hComm;                          // Handle to the Serial port  // Name of the Serial port(May Change) to be opened,
	BOOL  Status;                          // Status of the various operations           
	byte n;
	DWORD NoBytesRead;                     // Bytes read by ReadFile()
	DWORD dwEventMask;                     // Event mask to trigger



	openPort(&hComm); // Open Port

	Status = settings(hComm);  //Set configuration Port
	if (Status == FALSE) {
		printf("ERRO!");
	}

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


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

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

		if (Status == FALSE)
		{
		}
		else //If  WaitCommEvent()==True Read the RXed data using ReadFile();
		{
			while (1) {
				Status = ReadFile(hComm, &n, sizeof(n), &NoBytesRead, NULL);
				printf("%d\n", n);
				Sleep(1000);
			}

		}
	}



	closePort(hComm);
	system("exit");



}//End of Main()

void openPort(HANDLE* hComm) {

	char  ComPortName[] = "\\\\.\\COM3";

	*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

	if (*hComm == INVALID_HANDLE_VALUE) {
		printf("\n    Error! - Port %s can't be opened\n", ComPortName);
		system("exit");
	}
	else {
		printf("\n    Port %s Opened\n ", ComPortName);
	}
}


BOOL settings(HANDLE hComm) {

	BOOL Status = TRUE;
	/*------------------------------- 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()");
		return Status;
	}

	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");
		return Status;
	}
	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");
		return Status;
	}
	else
		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");
		return Status;
	}
	else {
		printf("\n\n    Setting CommMask successfull");
	}

	return TRUE;



}




void closePort(HANDLE hComm) {
	CloseHandle(hComm);//Closing the Serial Port

}

And what I’m getting is 20, 10 and 0 value. But I just want to get 20 and 10 values. Another situtation that I don’t want is that sometimes when I run the C program, it get always 0 value. It’s like the COM PORT is not wite with the value.
Please help me fix this!!!
Thank you!

An int in Arduino land is usually 2 bytes. So you're sending two bytes.

The receiver side will see the two bytes and display them.

One solution is to change the type of joystickEstadoAtual to byte; this will however limit the values to the range 0..255

Yeah, this solution works to the first problem. Thanks!
But how can I solve the second problem? When I run the arduino code and run the c program faster I can, it get zero value and does not change to 20 or 10 value.

Your problem with the leading zero (rather leading data) is probably caused by the fact that your PC program doesn't take into account that the Arduino needs some time for the bootloader to do its job. This takes a few seconds. I added a Sleep(5000) before the while-loop where you read the data and the leading data disappeared.

You should not sleep in the while-loop; this might eventually result in a buffer overflow at the Arduino side. Rather delay the output of the Arduino after every write.

You should also check if you have actually received data; useless to print if you haven't received anything. On my system I got lots of zeroes in between the data.

And lastly you should check the status of the read action and take action based on what it says.

Except for the last point, be low the updated main()

void main(void)
{
 HANDLE hComm;                          // Handle to the Serial port  // Name of the Serial port(May Change) to be opened,
 BOOL  Status;                          // Status of the various operations           
 byte n;
 DWORD NoBytesRead;                     // Bytes read by ReadFile()
 DWORD dwEventMask;                     // Event mask to trigger



 openPort(&hComm); // Open Port

 Status = settings(hComm);  //Set configuration Port
 if (Status == FALSE) {
 printf("ERRO!");
 }

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


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

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

 if (Status == FALSE)
 {
 }
 else //If  WaitCommEvent()==True Read the RXed data using ReadFile();
 {
 printf("give arduino time to start\n");
 Sleep(5000);
 while (1) {
 Status = ReadFile(hComm, &n, sizeof(n), &NoBytesRead, NULL);
 if(NoBytesRead !=0)
 {
 printf("%d\n", n);
 }
 //Sleep(1000);
 }

 }
 }

 closePort(hComm);
 system("exit");

}//End of Main()

void openPort(HANDLE* hComm) {

 char  ComPortName[] = "\\\\.\\COM3";

 *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

 if (*hComm == INVALID_HANDLE_VALUE) {
 printf("\n    Error! - Port %s can't be opened\n", ComPortName);
 system("exit");
 }
 else {
 printf("\n    Port %s Opened\n ", ComPortName);
 }
}

Lastly (and I explained that in your other thread), you should collect the data before working with it. If you know that you send 2 bytes, read two bytes before processing it. See the example in the linked thread.

I did changes about the second problem, but I get error:

Arduino code:

byte joystickEstadoAtual;
int aux = 2;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  
  while(!Serial.available()){}
  aux = Serial.read();
  Serial.write('.');
}

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

  Serial.print(aux);
  if(aux > 0 ){
    joystickEstadoAtual = B10000000;
    aux = 1;
  }
  else{
    joystickEstadoAtual = B11111111;
    aux = 0;
    
    }
  //Serial.print(joystickEstadoAtual);
Serial.write((const uint8_t *)&joystickEstadoAtual, sizeof(joystickEstadoAtual));
    
}

C code:

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


void openPort(HANDLE* hComm, char ComPortName[]);
void readPort(HANDLE hComm);
void writePort(HANDLE hComm, byte aux);
BOOL settings(HANDLE hComm);
void closePort(HANDLE hComm);


byte n;

void main(void)
{
	HANDLE hComm;                          // Handle to the Serial port  // Name of the Serial port(May Change) to be opened,
	BOOL  Status;                          // Status of the various operations    

	int aux = 1;

	char  ComPortName[] = "\\\\.\\COM3";


	openPort(&hComm, ComPortName); // Open Port

	Status = settings(hComm);  //Set configuration Port
	if (Status == FALSE) {
		printf("ERRO!");
	}

	else {
		writePort(hComm, aux);
		readPort(hComm);
	}



	closePort(hComm);
	system("exit");



}//End of Main()




void readPort(HANDLE hComm) {

	DWORD NoBytesRead;                     // Bytes read by ReadFile()
	DWORD dwEventMask;                     // Event mask to trigger
	BOOL Status;
	/*------------------------------------ Setting WaitComm() Event   ----------------------------------------*/

	printf("Aguardando leitura inicial\n");


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


	if (Status == TRUE) {


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

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

		if (Status == FALSE)
		{
		}
		else //If  WaitCommEvent()==True Read the RXed data using ReadFile();
		{
			while (1) {
				Status = ReadFile(hComm, &n, sizeof(n), &NoBytesRead, NULL);
				printf("%d\n", n);
				Sleep(1000);
			}

		}
	}
	else {

		printf("ERRO\n");
		Sleep(5000);
		system("exit");
	}


}

void writePort(HANDLE hComm, byte aux) {


	DWORD NoBytesWrite;                     // Bytes read by ReadFile()
	DWORD dwEventMask;                     // Event mask to trigger
	BOOL Status;

	Status = WriteFile(hComm, aux, sizeof(aux), &NoBytesWrite, NULL);
	if (Status == FALSE) {
		printf("ERRO\n");
		Sleep(5000);
		system("exit");
	}

}



void openPort(HANDLE* hComm, char ComPortName[]) {

	*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

	if (*hComm == INVALID_HANDLE_VALUE) {
		printf("\n    Error! - Port %s can't be opened\n", ComPortName);
		system("exit");
	}
	else {
		printf("\n    Port %s Opened\n ", ComPortName);
	}
}


BOOL settings(HANDLE hComm) {

	BOOL Status = TRUE;

	/*------------------------------- 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()");
		return Status;
	}

	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");
		return Status;
	}
	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");
		return Status;
	}
	else
		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");
		return Status;
	}
	else {
		printf("\n\n    Setting CommMask successfull");
	}

	return TRUE;



}




void closePort(HANDLE hComm) {
	CloseHandle(hComm);//Closing the Serial Port

}

It’s like I cant write on COMM port by C program.

You should be able to figure out the error with WriteFile; the function expects a pointer, not a value. You need to do the same as you did in the Arduino code with Serial.write().

For the problem with the WaitCommEvent, the second argument needs to be a pointer to an event mask, not just a value. So I think that you need to put the EV_RXCHAR in dwEventMask and pass that to the function as you did further down the code; please note that I also have to (re)learn this; not tested, give it a shot.

Note
This is not a forum for Windows programming questions :wink:
Further, question regarding communication with the PC fit better in the Interfacing w/ Software on the Computer section. You can report your thread using the 'report to moderator' link under your opening post of this thread and ask it to be moved.

Thank you a lot!
All problems are fix now!
Thank you!

Please post your code for the PC; can be useful in the future.