Projet

Général

Profil

Feature #13630 » main.c

programme principal - Anonyme, 20/11/2021 13:14

 
/*---------------------------------------------------------------------------------------------
-----------------------------------CODE TAKEN FROM : ------------------------------------------
https://www.codeproject.com/Questions/1116584/Reading-from-serial-port-using-C-in-visual-studio
-----------------------------------------------------------------------------------------------
---------------------------Corrected and adapted by :------------------------------------------
--------------------------------Mathis Morales-------------------------------------------------
---------------------------------------------------------------------------------------------*/


#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#define BUFFERLENGTH 256

const char scilabCSV[] = "csvData.csv";// Scilab csv file name

int main(int argc, char *argv[])
{
HANDLE hComm;
DWORD MORO;
char *pcCommPort = "COM8";
BOOL Write_Status;
DCB dcbSerialParams; // Initializing DCB structure
COMMTIMEOUTS timeouts = { 0 };
BOOL Read_Status; // Status of the various operations
DWORD dwEventMask; // Event mask to trigger
char TempChar = ""; // Temperory Character
char SerialBuffer[BUFFERLENGTH+1]; // Buffer Containing Rxed Data
DWORD NoBytesRead; // Bytes read by ReadFile()


printf("\n\n +==========================================+");
printf("\n | OPENING .CSV FILE |");
printf("\n +==========================================+\n");
/* opening file for reading */
printf("\n\n opening file...");

FILE *fp = fopen(scilabCSV, "r");

if(fp == NULL)
{
perror("\n\nError opening file");
return 1;
}
rewind(fp);
if (fp!=NULL)
{
printf("\n\n File opening successfull");
}


printf("\n\n +==========================================+");
printf("\n | Serial Transmission (Win32 API) |");
printf("\n +==========================================+\n");

hComm = CreateFileA(pcCommPort,
GENERIC_READ | GENERIC_WRITE,
0, // must be opened with exclusive-access
NULL, // no security attributes
OPEN_EXISTING, // must use OPEN_EXISTING
0, // not overlapped I/O
NULL // hTemplate must be NULL for comm devices
);

if (hComm == INVALID_HANDLE_VALUE)
{

if (GetLastError() == ERROR_FILE_NOT_FOUND)
{
puts("cannot open port!");
return;
}

puts("invalid handle value!");
return;
}
else
printf("opening serial port successful");

dcbSerialParams.DCBlength = sizeof(dcbSerialParams);

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

if (Write_Status == FALSE) {
printf("\n Error! in GetCommState()");
CloseHandle(hComm);
return 1;
}


dcbSerialParams.BaudRate = CBR_115200; // Setting BaudRate = 115200
dcbSerialParams.ByteSize = 8; // Setting ByteSize = 8
//dcbSerialParams.
dcbSerialParams.StopBits = ONESTOPBIT; // Setting StopBits = 1
dcbSerialParams.Parity = NOPARITY; // Setting Parity = None

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

if (Write_Status == FALSE)
{
printf("\n Error! in Setting DCB Structure");
CloseHandle(hComm);
return 1;
}
else
{
printf("\n Setting DCB Structure Successful\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);
}

// Set COM port timeout settings
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if (SetCommTimeouts(hComm, &timeouts) == 0)
{
printf("Error setting timeouts\n");
CloseHandle(hComm);
return 1;
}

char buff1 [1024];

while (fgets(buff1, sizeof(buff1), fp))
{
/*----------------------------- Writing a Character to Serial Port----------------------------------------*/
char lp [strlen(buff1)]; // lpBuffer should be char or byte array, otherwise write will fail
strcpy(lp,buff1); //copy buff1 into lp


DWORD NumWritten;
DWORD dNoOFBytestoWrite; // No of bytes to write into the port
DWORD dNoOfBytesWritten = 0; // No of bytes written to the port

dNoOFBytestoWrite = sizeof(lp); // Calculating the no of bytes to write into the port


if (!WriteFile(hComm, lp, dNoOFBytestoWrite,
&dNoOfBytesWritten, NULL))
{
printf("Error writing text to %s\n", pcCommPort);
}
else
{
printf("\n %d bytes written to %s\n",
dNoOfBytesWritten, pcCommPort);
}

if (Write_Status == TRUE)
printf("\n\n %s - Written to %s", lp, pcCommPort);
else
printf("\n\n Error %d in Writing to Serial Port", GetLastError());

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

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

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


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


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

Sleep(1000);

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

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

printf ("\n\n");
//system("PAUSE");

if (Read_Status == FALSE)
{
printf("\n Error! in Setting WaitCommEvent()");
}
else //If WaitCommEvent()==True Read the RXed data using ReadFile();
{
printf("\n\n Characters Received: \t");


//Read_Status = ReadFile(hComm, &TempChar, sizeof(TempChar), &NoBytesRead, NULL);
if (!ReadFile(hComm, SerialBuffer, BUFFERLENGTH, &NoBytesRead, NULL))
{
printf("\n Reading error");
}
printf("%s", SerialBuffer);



/*------------resetting values----------------------*/

memset(lp,0,sizeof(lp));
memset(buff1,0,sizeof(buff1));
memset(SerialBuffer,0,sizeof(SerialBuffer));

//system("PAUSE");
Sleep(1000);
}

}
//Closing the Serial Port
fprintf(stderr, "Closing serial port...\n");

if(CloseHandle(hComm))
{
printf("File closed.\n");
}
else
{
printf("Error file not closed.\n");
exit(EXIT_FAILURE);
}
fclose(fp);
printf("\n ==========================================\n");


return 0;
}
(3-3/5)