Click here to Skip to main content
15,892,480 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
Basically I want to make LED ON and OFF continuously.The LED is connected at the output of the serial port of the PC.Please give me suitable method to fulfill my requirement.I want to implement it using .NET or C or C++. Please give me suitable solution with explanation.As I don't know much more about these languages please specify solution clearly.

Thanks and regards,
Tushar
Posted

What do you have the LED connected through? Do you just have pins stuck in the port? :S

Serial ports aren't meant to be a way to cycle power on and off directly. They are an interface, usually to a piece of hardware that expects certain signals.

You open a connection to a serial port, send the signals (commands) the device knows how to interpret, and you get the result you're looking for.

If you have a device with an LED on it, and it's configured with commands that are addressable via the serial port, you'll need the instructions from the manufacturer to find out what codes/commands/signals it is expecting to cycle power. From there, you have some work to do with the SerialPort[^] class.

Hth.

Cheers.
 
Share this answer
 
There are a lot of resources on serial communications, from dedicated web sites to forum posts to decades-old books. In .NET, it is really easy to build a simple application using System.IO.Ports.SerialPort.

In RS232, transmissions between host and device are (partially) defined by voltage on the given wire (Tx / Rx) relative to the ground wire. So, you technically could connect an LED to the Tx and Gnd lines and turn it on and off by writing / not-writing data.

This is not the purpose behind such a connection. If you need to understand serial-port programming, explore System.IO.Ports.SerialPort in MSDN. If you simply want to control an output line, you really want to use a digital I/O board. Amplicon and Measurement Computing (among others) offer a multitude of analog and digital I/O boards of various prices.
 
Share this answer
 
v2
Comments
[no name] 7-Dec-16 22:21pm    
That is indeed an interesting way to do it. The Nusbio board offers 8 gpio pins, SPI, I2C and more for any .NET languages for $18.
You can use the DTR (pin4) and/or RTS (pin7) to control a LED. You need to use a resistor and a LED in series connected between DTR (and/or RTS) and GND.
These signals are in fact often used to power RS422 to RS232 converters so should have enough power for a LED or two :)
 
Share this answer
 
Comments
tush_CBR 12-Nov-11 9:47am    
Thx :)
// Description : Encpasulates a driver for modem control lines of a serial comms port
//
// Please note we are not using serial communications
// here at all, but port still needs to be opened and correctly initialized.
//
#pragma once

//
// Encapsulates functionality required to drive I/O lines on serial comms port
//
class CComPortDriver
{
public:
	//
	// Ctor
	//
	CComPortDriver();

	//
	// Dtor
	//
	~CComPortDriver();

public:
	// Open comms port
	BOOL	Open(const int port_no, DWORD &err);

	// Close comms port
	BOOL	Close(DWORD &err);

	// Set DTR line
	BOOL	SetDtr();

	// Clear DTR line
	BOOL	ClearDtr();

	// Set RTS line
	BOOL	SetRts();

	// Clear RTS line
	BOOL	ClearRts();

	// get the status of 4 input lines
	BOOL	GetStatus(DWORD &status);

	// check if port is open
	BOOL	IsOpen();

	// get port number
	int		GetPortNumber();

protected:
	int		m_PortNumber;		// port number
	BOOL	m_IsOpen;			// is comms port open
	HANDLE	m_hCom;				// a handle to the comms port
};
// Description : Com port driver that allows to control an output directly
// from the PC's RS232 serial comms port
//
// This works both on "real" RS232 comms ports and USB to comms port adapters, which is important
// since not many PCs these days have a native RS232 port.
//
// We do not use comm port TX and RX line as we are not doing any communications through it.

#include "stdafx.h"
#include "ComPortDriver.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

//
// Ctor
//
CComPortDriver::CComPortDriver()
{
	m_PortNumber = 0;
	m_IsOpen = FALSE;
	m_hCom = NULL;
}

//
// Dtor. Closes the port automatically if the CComPortDriver object goes out of scope
//
CComPortDriver::~CComPortDriver()
{
	DWORD err;
	if (m_IsOpen)
	{
		Close(err);
	}
}

//
// Description  : Open a comms port given port number (1-100).
//					Returns an error number by reference.
//					Returns TRUE if successful, or FALSE otherwise
//
BOOL CComPortDriver::Open(const int port_no, DWORD &dwError)
{
	DCB dcb;
	dwError = ERROR_SUCCESS;
	BOOL fSuccess;
	CString port = "", str;
	HANDLE hCom;	// temp handle

	//
	// Allow port number in 1 - 100 range
	//
	if ((port_no < 1) || (port_no > 100))
	{
		return FALSE;
	}

	//
	// If already open, return FALSE
	//
	if (m_IsOpen)
	{
		return FALSE;
	}

	// sanity check
	ASSERT (m_hCom == NULL);

	// simple port.Format("COM%d",m_CommPort); works only up to port 9
	// see http://support.microsoft.com/default.aspx?scid=kb;EN-US;q115831
	port.Format("\\\\.\\COM%d", port_no);
	
	//
	// Open port using CreateFile function
	//
	hCom = CreateFile(port,
		GENERIC_READ | GENERIC_WRITE,
		0,    /* comm devices must be opened w/exclusive-access */
		NULL, /* no security attrs */
		OPEN_EXISTING, /* comm devices must use OPEN_EXISTING */
		0,    /* not overlapped I/O */
		NULL  /* hTemplate must be NULL for comm devices */
		);

	//
	// Get last error
	//
	if (hCom == INVALID_HANDLE_VALUE)
	{
		dwError = GetLastError();
		return FALSE;
	}

	//
	// Get the current configuration.
	//
	fSuccess = GetCommState(hCom, &dcb);
	if (!fSuccess)
	{
		dwError = GetLastError();
		return FALSE;
	}

	//
	// use some common settings to call set Comms State. Otherwise modem control line
	// will not work
	//
	dcb.fOutxCtsFlow = TRUE;
	dcb.fOutxDsrFlow = TRUE;
	dcb.fDsrSensitivity = TRUE;
	dcb.fDtrControl = DTR_CONTROL_ENABLE;	// important
	dcb.fRtsControl = RTS_CONTROL_ENABLE;	// important

	//
	// these setting that control serial communications mode hardly matter, 
	// but still set to some reasonable values
	//
	dcb.BaudRate = 9600;
	dcb.ByteSize = 8;
	dcb.Parity = NOPARITY;
	dcb.StopBits = ONESTOPBIT;

	// set comm port settings here
	fSuccess = SetCommState(hCom, &dcb);

	//
	// Check if failed
	//
	if (!fSuccess) 
	{
		dwError = GetLastError();
		return FALSE;
	}

	//
	// This is probably unnecessary but copied from working example just in case
	//
	if (!PurgeComm(hCom, PURGE_TXCLEAR | PURGE_RXCLEAR | PURGE_TXABORT | PURGE_RXABORT ))
	{
		dwError = GetLastError();
		return FALSE;
	}

	//
	// Set comms timeouts, again, probably not necessary but doesn't hurt
	//
	BOOL result;
	COMMTIMEOUTS ctmo;
	ctmo.ReadIntervalTimeout=1000;
	ctmo.ReadTotalTimeoutMultiplier=0;
	ctmo.ReadTotalTimeoutConstant= 10000;
	ctmo.WriteTotalTimeoutMultiplier=0;
	ctmo.WriteTotalTimeoutConstant = 10000;
	result = SetCommTimeouts(hCom, &ctmo);
	
	//
	// Check if failed
	//
	if (!result)
	{
		dwError = GetLastError();
		return FALSE;
	}
	
	//
	// Now set member variables to correct values
	//
	m_IsOpen = TRUE;
	m_hCom = hCom;
	m_PortNumber = port_no;

	return TRUE;
}

//
// Description  : Close comm port. Returns (by reference) an error code returned by
//					GetLastError if failed.
//					Returns TRUE if successful, and FALSE if not (including if port 
//					is not already open).
//
BOOL CComPortDriver::Close(DWORD &dwError)
{
	dwError = ERROR_SUCCESS;

	//
	// Need to be open and have a valid handle before trying to close the port
	//
	if (m_IsOpen && m_hCom)
	{
		if (!CloseHandle(m_hCom))
		{
			dwError = GetLastError();
			return FALSE;
		}
		m_IsOpen = FALSE;
		m_hCom = NULL;
		return TRUE;
	}
	return FALSE;
}

//
// Function		: SetDtr
// Description  : Set DTR line on comm port
//
BOOL CComPortDriver::SetDtr()
{
	if (m_IsOpen)
	{
		ASSERT (m_hCom);
		DWORD status = SETDTR;
		return EscapeCommFunction(m_hCom, status);
	}
	return FALSE;
}

//
// Function		: ClearDtr
// Description  : Clear DTR line on comm port
//
BOOL CComPortDriver::ClearDtr()
{
	if (m_IsOpen)
	{
		ASSERT (m_hCom);
		DWORD status = CLRDTR;
		return EscapeCommFunction(m_hCom, status);
	}
	return FALSE;
}

//
// Function		: SetRTS
// Description  : Set RTS line on comm port
//
BOOL CComPortDriver::SetRts()
{
	if (m_IsOpen)
	{
		ASSERT (m_hCom);
		DWORD status = SETRTS;
		return EscapeCommFunction(m_hCom, status);
	}
	return FALSE;
}

//
// Function		: ClearRts
// Description  : Clear RTS line on comm port
//
BOOL CComPortDriver::ClearRts()
{
	if (m_IsOpen)
	{
		ASSERT (m_hCom);
		DWORD status = CLRRTS;
		return EscapeCommFunction(m_hCom, status);
	}
	return FALSE;
}

//
// Function		: GetStatus
// Description  :  Returns the status of input lines of the comms port.
//					Not used and hence not fully tested.
//
BOOL CComPortDriver::GetStatus(DWORD &status)
{
	if (m_IsOpen)
	{
		ASSERT (m_hCom);
		return GetCommModemStatus(m_hCom, &status);
	}

	return FALSE;
}

//
// Function		: IsOpen
// Description  : A helper function that returns the status of comms port (TRUE for open)
//
BOOL CComPortDriver::IsOpen()
{
	return m_IsOpen;
}

//
// Function		: GetPortNumber
// Description  : Gets the port number of the currently open port
//
int CComPortDriver::GetPortNumber()
{
	return m_PortNumber;
}


We did something very similar in one of projects.

The output can be easily driven using DTR or RTS pins which are basically modem control outputs.

Clearly, port is not used for communications but as a simple output(s). But if you need something really simple, like an LED output, bare bones PCs don't have much else to hook it to.

A slightly non-trivial thing is that you need to use a function called EscapeCommFunction after you open the port.
The other non-trivial thing is that you need to set DTR_CONTROL_ENABLE and/or RTS_CONTROL_ENABLE bits in your DCB structure.

If you want the code (works great), let me know.

Works through USB adapters as well.

You can even use it as an input as well (and read CTS and DSR pins).

One word of caution is check what type of output you will be driving (LED should be fine) as serial port will NOT be able to source a lot of current. With a simple additional circuit it can also be used as a voltage free relay.
 
Share this answer
 
v2
Comments
tush_CBR 14-Nov-11 0:39am    
michaelmel if you can give me the code I can check it,hope that will work great and fulfill my need.I will be very thankful if I can make LED continuously on-off using that code.Thank you.
michaelmel 15-Nov-11 18:29pm    
This code is written in C++. You will not be able to compile it using a plain C compiler.
This code will happily compile using Microsoft Visual Studio C++ at least from version 5 upwards.
To use the code to do something real (like toggle a pin), include an instance of CComPortDriver in your CWinApp-derived class, and then call corresponding methods (e.g. Open, SetDtr, etc). I am sorry I cannot teach you a lot of C or C++ on this thread.
tush_CBR 16-Nov-11 0:42am    
michaelmel can i get ur email id,so that I can learn more things about this?Kindly assist me by giving that.Otherwise please explain this sentence
[ include an instance of CComPortDriver in your CWinApp-derived class, and then call corresponding methods (e.g. Open, SetDtr, etc) ].
tush_CBR 16-Nov-11 0:47am    
OR you can also mail me suitable solution to dilsan17@gmail.com
michaelmel 16-Nov-11 18:46pm    
Tush

1. Get Microsoft Visual Studio
2. Create a new dialog-based project
3. Add code that I posted to your project. Normally you would put the code in 2 files (one *.cpp and one *.h)
4. Add 2 buttons to the dialog template, one called Set, one Clear
5. Add BN_CLICKED event handler for handling single mouse click for each of 2 buttons
6. Add an instance of CComPortDriver to your project. You can make it a member of Application-derived, Dialog-derived class or even leave it global. You need to know a bit of MFC to know what I am saying, sorry.
7. In the function OnInitDialog, open port (call "Open")
8. In the event handler for "Set" button, call SetDtr()
9. In event handler for "Clear" button, call ClrDtr
10. Compile and run your project
11. Observe DTR pin change state every time you click Set or Clear
Port will be closed automatically when application exits.

This is as simple as I can explain it.
Sorry I cannot give you a tutorial nor CodeProject Q&A is this a forum for it. I am not able to spend a lot of time on this at the moment.
You probably have to learn some C/C++ and Visual Studio before you can understand the code and what I am saying.

Best regards & goold luck
VC++ Code:
Use this Code for Laser ON and Off:
BOOL m_bPortReady;
HANDLE m_hCom;
CString m_sComPort;
DCB m_dcb;
COMMTIMEOUTS m_CommTimeouts;
BOOL bWriteRC;
BOOL bReadRC;
DWORD iBytesWritten;
DWORD iBytesRead;
char sBuffer[128];

m_sComPort = "COM6";
m_hCom = CreateFile(m_sComPort,
GENERIC_READ | GENERIC_WRITE,
0, // exclusive access
NULL, // no security
OPEN_EXISTING,
0, // no overlapped I/O
NULL); // null template

m_bPortReady = GetCommState(m_hCom, &m_dcb);
m_dcb.BaudRate = 9600;
m_dcb.ByteSize = 8;
m_dcb.Parity = NOPARITY;
m_dcb.StopBits = ONESTOPBIT;
m_dcb.fAbortOnError = TRUE;


m_bPortReady = SetupComm(m_hCom, 128, 128); // set buffer sizes

m_bPortReady = GetCommTimeouts (m_hCom, &m_CommTimeouts);

m_CommTimeouts.ReadIntervalTimeout = 50;
//m_CommTimeouts.ReadTotalTimeoutConstant = 50;
//m_CommTimeouts.ReadTotalTimeoutMultiplier = 10;
m_CommTimeouts.WriteTotalTimeoutConstant = 50;
//m_CommTimeouts.WriteTotalTimeoutMultiplier = 10;

m_bPortReady = SetCommTimeouts (m_hCom, &m_CommTimeouts);

bWriteRC = WriteFile(m_hCom, "\x1CPA10\x0D",6,&iBytesWritten,NULL);//Laser ON Commande
Sleep(10000);
bWriteRC = WriteFile(m_hCom, "\x1CPA00\x0D",6,&iBytesWritten,NULL);//Laser OFF Command

CloseHandle(m_hCom);
 
Share this answer
 
http://www.fogma.co.uk/foggylog/archive/140.html[^] unbelievable .. 1st link on search term ..
 
Share this answer
 
Comments
michaelmel 14-Nov-11 18:11pm    
I cannot see how is the code in the link has anything to do with the question asked.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900