Click here to Skip to main content
15,892,059 members
Articles / Desktop Programming / MFC

How to use serial port to communicate between two computers

Rate me:
Please Sign up or sign in to vote.
4.65/5 (16 votes)
30 Sep 20056 min read 231.9K   9K   67  
Using the serial port and cable to send a file from one computer to another.
/* serrecv.c */
/* Receives and saves a file over a serial port */
/* Last modified: Septemeber 21, 2005 */
/* http://www.gomorgan89.com */

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

/* Function to print out usage information */
void usage(void);

/* Function to set up the serial port settings with the specified baud rate,
   no parity, and one stop bit */
void set_up_serial_port(HANDLE h, long baud);

/* Function to receive and save file from serial port */
void get_file_from_serial_port(HANDLE h, char *file_name, unsigned long file_length);

int main(int argc, char **argv)
{
	HANDLE serial_port;					/* Handle to the serial port */
	long baud_rate = 9600;				/* Baud rate */
	char port_name[] = "COM1:";			/* Name of serial port */
	unsigned long file_size;			/* Size of file to receive in bytes */
	unsigned long bytes_received;		/* Bytes received from serial port */
	unsigned long file_name_size;		/* Size of file name in bytes */
	char file_name[256];				/* Name of file to receive */

	/* Check command line */
	if (argc == 3)
	{
		/* Read in baud rate */
		if (argv[1][1] != 'b' || sscanf(argv[2], "%ld", &baud_rate) != 1)
		{
			usage();
			exit(0);
		}
	}
	else if (argc != 1)
	{
		usage();
		exit(0);
	}

	/* Open up a handle to the serial port */
	serial_port = CreateFile(port_name, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

	/* Make sure port was opened */
	if (serial_port == INVALID_HANDLE_VALUE)
	{
		fprintf(stderr, "Error opening port\n");
		CloseHandle(serial_port);
		exit(0);
	}

	/* Set up the serial port */
	set_up_serial_port(serial_port, baud_rate);

	/* Receive file name size from serial port */
	ReadFile(serial_port, (void *)&file_name_size, sizeof(unsigned long), &bytes_received, NULL);
	if (bytes_received != sizeof(unsigned long))
	{
		fprintf(stderr, "Error getting file name size.\n");
		CloseHandle(serial_port);
		exit(0);
	}

	/* Receive file name from serial port */
	ReadFile(serial_port, (void *)file_name, file_name_size, &bytes_received, NULL);
	if (bytes_received != file_name_size)
	{
		fprintf(stderr, "Error retrieving file name.\n");
		CloseHandle(serial_port);
		exit(0);
	}

	/* Append NULL terminator to end of string */
	file_name[bytes_received] = '\0';
	
	/* Receive file size from serial port */
	ReadFile(serial_port, (void *)&file_size, sizeof(unsigned long), &bytes_received, NULL);
	if (bytes_received != sizeof(unsigned long))
	{
		fprintf(stderr, "Error getting file size.\n");
		CloseHandle(serial_port);
		exit(0);
	}

	/* Get the file from the serial port */
	get_file_from_serial_port(serial_port, file_name, file_size);

	/* Print out success information */
	printf("\n%lu bytes successfully received and saved as %s\n", file_size, file_name);

	/* Close handle */
	CloseHandle(serial_port);

	return 0;
}

void usage(void)
{
	fprintf(stderr, "Usage:\n");
	fprintf(stderr, "\tserrecv [-b baud rate]\n");
	fprintf(stderr, "\tDefault baud rate is 9600\n");
	fprintf(stderr, "tSupported baud rates: 1200, 2400, 4800, 9600, 14400, 19200\n");
	return;
}

void set_up_serial_port(HANDLE h, long baud)
{
	DCB properties;			/* Properties of serial port */

	/* Get the properties */
	GetCommState(h, &properties);

	/* Set the baud rate */
	switch(baud)
	{
	case 1200:
		properties.BaudRate = CBR_1200;
		break;
	case 2400:
		properties.BaudRate = CBR_2400;
		break;
	case 4800:
		properties.BaudRate = CBR_4800;
		break;
	case 9600:
		properties.BaudRate = CBR_9600;
		break;
	case 14400:
		properties.BaudRate = CBR_14400;
		break;
	case 19200:
		properties.BaudRate = CBR_19200;
		break;
	case 38400:
		properties.BaudRate = CBR_38400;
		break;
	default:
		fprintf(stderr, "Invalid baud rate: %ld\n", baud);
		usage();
		exit(0);
		break;
	}
	
	/* Set the other properties */
	properties.Parity = NOPARITY;
	properties.ByteSize = 8;
	properties.StopBits = ONESTOPBIT;

	SetCommState(h, &properties);

	return;
}

void get_file_from_serial_port(HANDLE h, char *file_name, unsigned long file_length)
{
	FILE *data_file;						/* File to create */
	unsigned long bytes_left = file_length;	/* Bytes left to receive */
	unsigned long bytes_received_total = 0;	/* Total bytes received */
	unsigned long bytes_to_receive;			/* Number of bytes to receive */
	unsigned long bytes_received;			/* Number of bytes receive */
	char buffer[200];						/* Buffer to store data */

	/* Open the file */
	data_file = fopen(file_name, "wb");

	/* Quit if file couldn't be opened */
	if (data_file == NULL)
	{
		fprintf(stderr, "Could not create file %s\n", file_name);
		CloseHandle(h);
		exit(0);
	}

	while (1)
	{
		/* Determine how many bytes to read */
		if (bytes_left == 0)
		{
			break;
		}
		else if (bytes_left < 200)
		{
			bytes_to_receive = bytes_left;
		}
		else
		{
			bytes_to_receive = 200;
		}

		/* Receive data over serial cable */
		ReadFile(h, (void *)buffer, bytes_to_receive, &bytes_received, NULL);
		if (bytes_received != bytes_to_receive)
		{
			fprintf(stderr, "Error reading file.\n");
			CloseHandle(h);
			exit(0);
		}

		/* Save buffer to file */
		fwrite((void *)buffer, 1, bytes_received, data_file);
		
		/* Decrement number of bytes left */
		bytes_left -= bytes_received;

		/* Increment number of bytes received */
		bytes_received_total += bytes_received;

		/* Print out progress */
		printf("\r%5lu bytes received.", bytes_received_total);
	}

	fclose(data_file);

	return;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions