您的位置:首页 > 其它

communicating-with-serial-port-in-C-Sharp

2014-02-20 21:42 302 查看
转载:http://www.c-sharpcorner.com/uploadfile/eclipsed4utoo/communicating-with-serial-port-in-C-Sharp/

ThisarticlewilldemonstratehowtowriteandreceivedatafromadeviceconnectedtoaserialportinC#and.NET.WewillbewritingthereceiveddatatoaTextBoxonaform,sothiswillalsodealwiththreading.

Inthepast,tocommunicatewithaSerialPortusing.Net1.1,youhadtoeitherusetheWindowsAPI,oruseathird-partycontrol.With.Net2.0,MicrosoftaddedthissupportwiththeinclusionoftheSerialPortclassaspartoftheSystem.IO.Portsnamespace.
ImplementationoftheSerialPortclassisverystraight-forward.TocreateaninstanceoftheSerialPortclass,yousimplypasstheSerialPortoptionstotheconstructoroftheclass:

//alloftheoptionsforaserialdevice

//----canbesentthroughtheconstructoroftheSerialPortclass

//----PortName="COM1",BaudRate=19200,Parity=None,

//----DataBits=8,StopBits=One,Handshake=None

SerialPort_serialPort=newSerialPort("COM1",19200,Parity.None,8,StopBits.One);

_serialPort.Handshake=Handshake.None;

Toreceivedata,wewillneedtocreateanEventHandlerforthe"SerialDataReceivedEventHandler":

//"sp_DataReceived"isacustommethodthatIhavecreated

_serialPort.DataReceived+=newSerialDataReceivedEventHandler(sp_DataReceived);

Youcanalsosetotheroptions,suchastheReadTimeoutandWriteTimeout:

//milliseconds_serialPort.ReadTimeout=500;

_serialPort.WriteTimeout=500;

OnceyouarereadytousetheSerialPort,youwillneedtoopenit:

//Opensserialport

_serialPort.Open();

Nowwearereadytoreceivedata.However,towritethisdatatotheTextBoxonaform,weneedtocreateadelegate..Netdoesnotallowcross-threadaction,soweneedtouseadelegate.ThedelegateisusedtowritetotheUIthreadfromanon-UIthread.

//delegateisusedtowritetoaUIcontrolfromanon-UIthread

privatedelegatevoidSetTextDeleg(stringtext);

Wewillnowcreatethe"sp_DataReceived"methodthatwillbeexecutedwhendataisreceivedthroughtheserialport:
voidsp_DataReceived(objectsender,SerialDataReceivedEventArgse)

{

Thread.Sleep(500);

stringdata=_serialPort.ReadLine();

//InvokesthedelegateontheUIthread,andsendsthedatathatwasreceivedtotheinvokedmethod.

//----The"si_DataReceived"methodwillbeexecutedontheUIthreadwhichallowspopulatingofthetextbox.

this.BeginInvoke(newSetTextDeleg(si_DataReceived),newobject[]{data});

}

Nowwecreateour"si_DataReceived"method:

privatevoidsi_DataReceived(stringdata)
{textBox1.Text=data.Trim();}

Wecannowreceivedatafromaserialportdeviceanddisplayitonaform.Somedeviceswillsenddatawithoutbeingprompted.However,somedevicesneedtobesendcertaincommands,anditwillreplywiththedatathatthecommandcallsfor.Forthese
devices,youwillwritedatatotheserialport,andusethepreviouscodetogetthedatathatwillbesentback.Inmyexample,Iwillbecommunicatingwithascale.Forthisparticularscale,sendingthecommand"SI\r\n"willforceittoreturntheweight
ofwhateverisonthescale.Thiscommandisspecificforthisscale.Youwillneedtoreadthedocumentationofyourserialdevicetofindcommandsthatitwillreceive.Towritetotheserialport,Ihavecreateda"Start"buttonontheform.Ihaveadded
codetoit'sClick_Event:

privatevoidbtnStart_Click(objectsender,EventArgse)

{

//Makessureserialportisopenbeforetryingtowrite

try

{

if(!(_serialPort.IsOpen))

_serialPort.Open();

_serialPort.Write("SI\r\n");

}

catch(Exceptionex)

{

MessageBox.Show("Erroropening/writingtoserialport::"+ex.Message,"Error!");

}

}

Andthatisallyouneedtodo.IhaveattachedtheVisualStudio2005solution.

ArticleExtensions
ContentsaddedbyArjunWalmikionDec
04,2012
thisismycodebutnotreceivedatafromcomport:

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.IO.Ports;
usingSystem.Threading;
usingSystem.IO;

namespacePortChat
{
publicclassPortChat
{
//privatestaticStreamWritersw=newStreamWriter("filename.txt");
staticbool_continue;
staticSerialPort_serialPort;

publicstaticvoidMain(string[]args)
{
stringname;
stringmessage;
//stringpath="";
////Write
//stringpath="example.txt";
//string[]myMenu={"A","B","C"};
//File.WriteAllLines(path,myMenu);

////Read
//string[]readMenu=File.ReadAllLines(path);
StringComparerstringComparer=StringComparer.OrdinalIgnoreCase;
ThreadreadThread=newThread(Read);

//CreateanewSerialPortobjectwithdefaultsettings.
_serialPort=newSerialPort();

//Allowtheusertosettheappropriateproperties.
_serialPort.PortName=SetPortName(_serialPort.PortName);
_serialPort.BaudRate=SetPortBaudRate(_serialPort.BaudRate);
_serialPort.Parity=SetPortParity(_serialPort.Parity);
_serialPort.DataBits=SetPortDataBits(_serialPort.DataBits);
_serialPort.StopBits=SetPortStopBits(_serialPort.StopBits);
_serialPort.Handshake=SetPortHandshake(_serialPort.Handshake);

//Settheread/writetimeouts
_serialPort.ReadTimeout=500;
_serialPort.WriteTimeout=500;
_serialPort.Open();
_continue=true;
readThread.Start();
_serialPort.DataReceived+=newSerialDataReceivedEventHandler(_serialPort_DataReceived);

//_serialPort.WriteLine("$");//CommandtostartDataStream
////Waitfordataoruserinputtocontinue.
//Console.ReadLine();
//Console.WriteLine("FILEPATH");
//path=Console.ReadLine();
Console.Write("Name:");
name=Console.ReadLine();
Console.WriteLine("TypeQUITtoexit");
while(_continue)
{
message=Console.ReadLine();

if(stringComparer.Equals("quit",message))
{
_continue=false;
}
else
{
_serialPort.WriteLine(String.Format("<{0}>:{1}",name,message));
}
}

readThread.Join();
_serialPort.Close();
}
staticvoid_serialPort_DataReceived(objectsender,SerialDataReceivedEventArgse)
{
SerialPort_serialPort=(SerialPort)sender;
Console.WriteLine(_serialPort.ReadExisting());
}

publicstaticvoidRead()
{
while(_continue)
{
try
{

stringmessage=_serialPort.ReadLine();
Console.WriteLine(message);
}
catch(TimeoutException){}
}
}
publicstaticstringSetPortName(stringdefaultPortName)
{
stringportName="";

Console.WriteLine("AvailablePorts:");
foreach(stringsinSerialPort.GetPortNames())
{
Console.WriteLine("{0}",s);
portName=s;
}
//mycode
_serialPort.PortName=portName;
defaultPortName=portName;
Console.Write("COMport({0}):",defaultPortName);
portName=Console.ReadLine();

if(portName=="")
{
portName=defaultPortName;
}
returnportName;
}
publicstaticintSetPortBaudRate(intdefaultPortBaudRate)
{
stringbaudRate;

Console.Write("BaudRate({0}):",defaultPortBaudRate);
baudRate=Console.ReadLine();

if(baudRate=="")
{
baudRate=defaultPortBaudRate.ToString();
}

returnint.Parse(baudRate);
}
publicstaticParitySetPortParity(ParitydefaultPortParity)
{
stringparity;

Console.WriteLine("AvailableParityoptions:");
foreach(stringsinEnum.GetNames(typeof(Parity)))
{
Console.WriteLine("{0}",s);
}

Console.Write("Parity({0}):",defaultPortParity.ToString());
parity=Console.ReadLine();

if(parity=="")
{
parity=defaultPortParity.ToString();
}

return(Parity)Enum.Parse(typeof(Parity),parity);
}

publicstaticintSetPortDataBits(intdefaultPortDataBits)
{
stringdataBits;

Console.Write("DataBits({0}):",defaultPortDataBits);
dataBits=Console.ReadLine();

if(dataBits=="")
{
dataBits=defaultPortDataBits.ToString();
}

returnint.Parse(dataBits);
}
publicstaticStopBitsSetPortStopBits(StopBitsdefaultPortStopBits)
{
stringstopBits;

Console.WriteLine("AvailableStopBitsoptions:");
foreach(stringsinEnum.GetNames(typeof(StopBits)))
{
Console.WriteLine("{0}",s);
}

Console.Write("StopBits({0}):",defaultPortStopBits.ToString());
stopBits=Console.ReadLine();

if(stopBits=="")
{
stopBits=defaultPortStopBits.ToString();
}

return(StopBits)Enum.Parse(typeof(StopBits),stopBits);
}
publicstaticHandshakeSetPortHandshake(HandshakedefaultPortHandshake)
{
stringhandshake;

Console.WriteLine("AvailableHandshakeoptions:");
foreach(stringsinEnum.GetNames(typeof(Handshake)))
{
Console.WriteLine("{0}",s);
}

Console.Write("Handshake({0}):",defaultPortHandshake.ToString());
handshake=Console.ReadLine();

if(handshake=="")
{
handshake=defaultPortHandshake.ToString();
}

return(Handshake)Enum.Parse(typeof(Handshake),handshake);
}
}
}

ContentsaddedbyMaheshChandonAug
03,2010
HereiscompletecodesamplefromMSDN.

usingSystem;
usingSystem.IO.Ports;
usingSystem.Threading;

publicclassPortChat
{
staticbool_continue;
staticSerialPort_serialPort;

publicstaticvoidMain()
{
stringname;
stringmessage;
StringComparerstringComparer=StringComparer.OrdinalIgnoreCase;
ThreadreadThread=newThread(Read);

//CreateanewSerialPortobjectwithdefaultsettings.
_serialPort=newSerialPort();

//Allowtheusertosettheappropriateproperties.
_serialPort.PortName=SetPortName(_serialPort.PortName);
_serialPort.BaudRate=SetPortBaudRate(_serialPort.BaudRate);
_serialPort.Parity=SetPortParity(_serialPort.Parity);
_serialPort.DataBits=SetPortDataBits(_serialPort.DataBits);
_serialPort.StopBits=SetPortStopBits(_serialPort.StopBits);
_serialPort.Handshake=SetPortHandshake(_serialPort.Handshake);

//Settheread/writetimeouts
_serialPort.ReadTimeout=500;
_serialPort.WriteTimeout=500;

_serialPort.Open();
_continue=true;
readThread.Start();

Console.Write("Name:");
name=Console.ReadLine();

Console.WriteLine("TypeQUITtoexit");

while(_continue)
{
message=Console.ReadLine();

if(stringComparer.Equals("quit",message))
{
_continue=false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>:{1}",name,message));
}
}

readThread.Join();
_serialPort.Close();
}

publicstaticvoidRead()
{
while(_continue)
{
try
{
stringmessage=_serialPort.ReadLine();
Console.WriteLine(message);
}
catch(TimeoutException){}
}
}

publicstaticstringSetPortName(stringdefaultPortName)
{
stringportName;

Console.WriteLine("AvailablePorts:");
foreach(stringsinSerialPort.GetPortNames())
{
Console.WriteLine("{0}",s);
}

Console.Write("COMport({0}):",defaultPortName);
portName=Console.ReadLine();

if(portName=="")
{
portName=defaultPortName;
}
returnportName;
}

publicstaticintSetPortBaudRate(intdefaultPortBaudRate)
{
stringbaudRate;

Console.Write("BaudRate({0}):",defaultPortBaudRate);
baudRate=Console.ReadLine();

if(baudRate=="")
{
baudRate=defaultPortBaudRate.ToString();
}

returnint.Parse(baudRate);
}

publicstaticParitySetPortParity(ParitydefaultPortParity)
{
stringparity;

Console.WriteLine("AvailableParityoptions:");
foreach(stringsinEnum.GetNames(typeof(Parity)))
{
Console.WriteLine("{0}",s);
}

Console.Write("Parity({0}):",defaultPortParity.ToString());
parity=Console.ReadLine();

if(parity=="")
{
parity=defaultPortParity.ToString();
}

return(Parity)Enum.Parse(typeof(Parity),parity);
}

publicstaticintSetPortDataBits(intdefaultPortDataBits)
{
stringdataBits;

Console.Write("DataBits({0}):",defaultPortDataBits);
dataBits=Console.ReadLine();

if(dataBits=="")
{
dataBits=defaultPortDataBits.ToString();
}

returnint.Parse(dataBits);
}

publicstaticStopBitsSetPortStopBits(StopBitsdefaultPortStopBits)
{
stringstopBits;

Console.WriteLine("AvailableStopBitsoptions:");
foreach(stringsinEnum.GetNames(typeof(StopBits)))
{
Console.WriteLine("{0}",s);
}

Console.Write("StopBits({0}):",defaultPortStopBits.ToString());
stopBits=Console.ReadLine();

if(stopBits=="")
{
stopBits=defaultPortStopBits.ToString();
}

return(StopBits)Enum.Parse(typeof(StopBits),stopBits);
}

publicstaticHandshakeSetPortHandshake(HandshakedefaultPortHandshake)
{
stringhandshake;

Console.WriteLine("AvailableHandshakeoptions:");
foreach(stringsinEnum.GetNames(typeof(Handshake)))
{
Console.WriteLine("{0}",s);
}

Console.Write("Handshake({0}):",defaultPortHandshake.ToString());
handshake=Console.ReadLine();

if(handshake=="")
{
handshake=defaultPortHandshake.ToString();
}

return(Handshake)Enum.Parse(typeof(Handshake),handshake);
}
}[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: