本文整理汇总了C#中System.IO.Ports.SerialPort.Read方法的典型用法代码示例。如果您正苦于以下问题:C# SerialPort.Read方法的具体用法?C# SerialPort.Read怎么用?C# SerialPort.Read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.Ports.SerialPort
的用法示例。
在下文中一共展示了SerialPort.Read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
SerialPort ser = new SerialPort( "COM1", (int)BaudRate.Baudrate115200 );
byte[] buf = new byte[26];
byte[] ret = new byte[26];
ser.Handshake = Handshake.XOnXOff;
ser.DataReceived += new SerialDataReceivedEventHandler(ser_DataReceived);
ser.Open();
Debug.Print("Initializing Serial Test");
for (int i = 0;i < buf.Length;i++)
{
buf[i] = (byte)('a' + i);
}
ser.Write(buf, 0, buf.Length);
ser.Flush();
Thread.Sleep(1000);
ser.DataReceived -= new SerialDataReceivedEventHandler(ser_DataReceived);
ser.Write(buf, 0, buf.Length);
Thread.Sleep(1000);
ser.DataReceived += new SerialDataReceivedEventHandler(ser_DataReceived);
ser.ErrorReceived += new SerialErrorReceivedEventHandler(ser_ErrorReceived);
ser.Write(buf, 0, buf.Length);
Thread.Sleep(3000);
ser.Read(ret, 0, ret.Length);
Thread.Sleep(10000);
}
示例2: findUID
private string findUID(SerialPort port, int position, string bufferString)
{
char[] buffer = new char[1];
while(!bufferString.Contains("Card UID: ")){
port.Read(buffer, position, 1);
bufferString += new string(buffer);
return findUID(port, position++, bufferString);
}
char[] uid = new char[11];
port.Read(uid, position, 11);
return new string(uid);
}
示例3: Main
public static void Main()
{
// A program to set the baud rate on a new HC-06 to
// 115200
//
SerialPort blueComms = new SerialPort(SerialPorts.COM1, 9600, Parity.None, 8, StopBits.One);
blueComms.Open();
//
// Rename the device
//
byte[] outBuffer = System.Text.Encoding.UTF8.GetBytes("AT+NAMEHC_A");
blueComms.Write(outBuffer, 0, outBuffer.Length);
Thread.Sleep(2000);
while (blueComms.BytesToRead > 0)
{
byte[] a = new byte[1] { 0 };
blueComms.Read(a, 0, 1);
char[] cc = System.Text.Encoding.UTF8.GetChars(a, 0, a.Length);
Debug.Print(cc.ToString());
Thread.Sleep(10);
}
//
// Set the baud rate.
//
outBuffer = System.Text.Encoding.UTF8.GetBytes("AT+BAUD8");
blueComms.Write(outBuffer, 0, outBuffer.Length);
Thread.Sleep(2000);
blueComms.Close();
SerialPort blueFast = new SerialPort(SerialPorts.COM1, 115200, Parity.None, 8, StopBits.One);
blueFast.Open();
outBuffer = System.Text.Encoding.UTF8.GetBytes("AT");
blueComms.Write(outBuffer, 0, outBuffer.Length);
Debug.Print("After Baud rate set");
while (blueComms.BytesToRead > 0)
{
byte[] a = new byte[1] { 0 };
blueComms.Read(a, 0, 1);
char[] cc = System.Text.Encoding.UTF8.GetChars(a, 0, a.Length);
Debug.Print(cc.ToString());
Thread.Sleep(10);
}
}
示例4: Main
public static void Main()
{
int count = 0;
SerialPort SPort = new SerialPort(SerialPorts.COM2, 9600, Parity.None,8,StopBits.One);
SPort.ReadTimeout = 1000;
SPort.WriteTimeout = 1000;
byte[] buf = new byte[5];
string CardId = "";
SPort.Open();
byte[] readCommand = { 0x21, 0x52, 0x57, 0x01, 0x03 };
int numCodes = 0;
while (true)
{
//SPort.Write(new byte[] { 0xFF, 0xFF, 0X39, 0x44 }, 0, 4);
SPort.Write(readCommand, 0, 5);
SPort.Flush();
int readcnt = SPort.Read(buf, 0, SPort.BytesToRead);
SPort.Flush();
string s = "";
if (buf[0] == 0x01 && numCodes < 10)
{
foreach (byte b in buf)
{
s = s + b.ToString() + ",";
}
if (s[0] == '1')
{
count++;
Debug.Print(count.ToString() + ":" + s + "\n");
numCodes++;
}
}
}
}
示例5: Main
public static void Main()
{
SerialPort serialPort = new SerialPort("COM1", 115200, Parity.None);
serialPort.ReadTimeout = 5000; // milliseconds
serialPort.Open();
byte[] outBuffer = Encoding.UTF8.GetBytes("All right?\r\n");
byte[] inBuffer = new byte[2];
while (true)
{
Debug.Print("Request data");
serialPort.Write(outBuffer, 0, outBuffer.Length);
int count = serialPort.Read(inBuffer, 0, 2);
if (count == 2)
{
Debug.Print("Received expected two bytes!");
}
else
{
if (count == 0)
Debug.Print("No response!");
if (count == 1)
Debug.Print("Not enough bytes received!");
}
Debug.Print(string.Empty);
}
}
示例6: Main
static void Main(string[] args)
{
// initialize the sensor port, mine was registered as COM8, you may check yours
// through the hardware devices from control panel
SerialPort sensor = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
int bytesToRead = 0;
string message;
sensor.Open();
try
{
while (true)
{
// check if there are bytes incoming
bytesToRead = sensor.BytesToRead;
if (bytesToRead > 0)
{
byte[] input = new byte[bytesToRead];
// read the Xbee's input
sensor.Read(input, 0, bytesToRead);
// convert the bytes into string
message = System.Text.Encoding.UTF8.GetString(input);
Console.WriteLine(message);
}
}
}
finally
{
// again always close the serial ports!
sensor.Close();
}
}
示例7: Main
static void Main(string[] args)
{
SerialPort device = new SerialPort("COM8", 9600);
device.Open();
while (true)
{
string command = "0";
try
{
switch (Console.ReadKey().Key)
{
case ConsoleKey.LeftArrow:
{
command = "4";
break;
}
case ConsoleKey.RightArrow:
{
command = "3";
break;
}
case ConsoleKey.UpArrow:
{
command = "1";
break;
}
case ConsoleKey.DownArrow:
{
command = "2";
break;
}
default:
{
command = "0";
break;
}
}
}
catch (Exception ex)
{
break;
}
device.Write(command);
char[] buffer = {'a'};
device.Read(buffer, 0, 1);
Console.WriteLine(buffer);
}
device.Close();
}
示例8: ReadBytes
static byte[] ReadBytes(SerialPort serialPort, CancellationToken token)
{
var buffer = new byte[_sampleCount];
WaitForBytesReady(serialPort, buffer.Length, token);
var count = serialPort.Read(buffer, 0, buffer.Length);
Debug.Assert(count == buffer.Length);
return buffer;
}
示例9: Main
static void Main(string[] args)
{
// initialize the sensor port, mine was registered as COM8, you may check yours
// through the hardware devices from control panel
SerialPort sensor = new SerialPort("COM8", 9600, Parity.None, 8, StopBits.One);
int bytesToRead = 0;
bool isPlaying = false;
string message;
sensor.Open();
try
{
while (true)
{
// check if there are bytes incoming
bytesToRead = sensor.BytesToRead;
if (bytesToRead > 0)
{
byte[] input = new byte[bytesToRead];
// read the Xbee's input
sensor.Read(input, 0, bytesToRead);
// convert the bytes into string
message = System.Text.Encoding.UTF8.GetString(input);
// in our case "MOVE" is what we will expect
if ("MOVE".Equals(message))
{
if (!isPlaying)
{
// this is where the wmplayer through process.start
System.Diagnostics.Process pr;
System.Diagnostics.ProcessStartInfo ps;
// this is much like doing Start > Run > wmplayer <file> command
ps = new System.Diagnostics.ProcessStartInfo("wmplayer", "\"C:\\Alarm.mp3\"");
pr = new System.Diagnostics.Process();
pr.StartInfo = ps;
pr.Start(); // start it finally
isPlaying = true; // will not open another wmplayer anymore
}
// write something to the console
Console.WriteLine("Something moved!");
}
}
}
}
finally
{
// again always close the serial ports!
sensor.Close();
}
}
示例10: Program
public Program(string port)
{
serial = new SerialPort(port, 9600, Parity.None, 8, StopBits.One)
{
Handshake = Handshake.RequestToSend,
NewLine = "\r",
};
serial.DataReceived +=(o,e)=>
{
var num = serial.BytesToRead;
if (num == 0)
return;
var data = new byte[num];
serial.Read(data, 0, num);
foreach (var b in data)
{
switch (phase)
{
case 0:
if (b == 0x0A)
phase = 1;
else
message.Append((char) b);
break;
case 1:
phase = (b == 0x30) ? 2 : 0;
break;
case 2:
phase = (b == 0x30) ? 3 : 0;
break;
case 3:
if (b == 0x0D)
{
if (message.Length > 0 && verbose)
Console.WriteLine(message);
lastMessage = message.ToString();
message.Clear();
syncEvent.Set();
}
phase = 0;
break;
}
}
};
serial.Open();
//serial.RtsEnable = true;
serial.DiscardOutBuffer();
serial.DiscardInBuffer();
}
示例11: SerialPortThread
public SerialPortThread(ToEcuBuffer toEcu, FromEcuBuffer fromEcu, SerialPort port)
{
_port = port;
_toEcu = toEcu;
_fromEcu = fromEcu;
_port.DataReceived += (object sender, SerialDataReceivedEventArgs e) =>
{
try
{
int count = _port.BytesToRead;
while (count != 0)
{
count = Math.Min(count, _readBuff.Length);
_port.Read(_readBuff, 0, count);
_fromEcu.Write(_readBuff, 0, count);
count = _port.BytesToRead;
}
}
catch
{
}
};
_writeTask = Task.Factory.StartNew(() =>
{
while (_port.IsOpen)
{
try
{
int count = _toEcu.BytesToRead;
while (count != 0)
{
count = Math.Min(count, _writeBuff.Length);
_toEcu.Read(_writeBuff, 0, count);
_port.Write(_writeBuff, 0, count);
count = _toEcu.BytesToRead;
}
Thread.Sleep(1);
Thread.Yield();
}
catch
{
}
}
});
}
示例12: Main
public static void Main()
{
// initialize the serial port which Xbee will use
// COM1 is what i always use, it just works hehe
SerialPort serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
serialPort.ReadTimneout = 0;
serialPort.Open();
try
{
while (true)
{
// check for incoming bytes
int bytesToRead = serialPort.BytesToRead;
// dim the LED
pin13.Write(false);
if (bytesToRead > 0)
{
// get the waiting data
byte[] buffer = new byte[bytesToRead];
// READ any data received, this is necessary to consume the buffer
// why? the Xbee buffer will be filled up and something weird will happen to Xbee
serialPort.Read(buffer, 0, buffer.Length);
// we can ignore the message anyway
}
// if there is motion detected
if (pin8.Read())
{
// then we will prepare sending the message
byte[] buffer = new byte[MOVEMESSAGE.Length];
// convert the string to bytes
buffer = System.Text.Encoding.UTF8.GetBytes(MOVEMESSAGE);
// write it to Xbee through serial
serialPort.Write(buffer, 0, buffer.Length);
// turn the LED on
pin13.Write(true);
}
// wait 500 seconds
Thread.Sleep(500);
}
}
finally
{
// always close the serial ports!
serialPort.Close();
}
}
示例13: Main
public static void Main()
{
SerialPort serialPort = new SerialPort("COM1", 115200, Parity.None);
serialPort.ReadTimeout = 0;
serialPort.Open();
byte[] inBuffer = new byte[32];
while (true)
{
int count = serialPort.Read(inBuffer, 0, inBuffer.Length);
if (count > 0) // Minimum one byte read
{
char[] chars = Encoding.UTF8.GetChars(inBuffer);
string str = new string(chars, 0, count);
Debug.Print(str);
}
Thread.Sleep(25); // Give device time to sleep
}
}
示例14: Main
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Usage: reconnect port");
return;
}
var serial = new SerialPort(args[0], 576000);
var startCommand = new byte[] { 0xAA, 0xAA };
var stopCommand = new byte[] { 0xBB, 0xBB };
var getVerCommand = new byte[] { 0xCC, 0xCC };
var version = new byte[3];
while (true)
{
try
{
if (!serial.IsOpen)
{
serial.Open();
}
else
{
serial.Write(getVerCommand, 0, 2);
// *** Comment out/Uncomment this line, and see how the behaviour of
// this program changes.
//Thread.Sleep(200);
if (serial.Read(version, 0, 3) == 3 && version[0] == 0x50)
{
Console.WriteLine("{0:x} {1:x} {2:x}", version[0], version[1], version[2]);
}
}
}
catch
{
Console.WriteLine("Oops!");
}
Thread.Sleep(200);
}
}
示例15: Connect
void Connect()
{
string[] names = SerialPort.GetPortNames();
List<string> Ports = new List<string>();
foreach (string name in names)
{
if (name != "COM1" && name != "COM2" && name != "COM3" && name != "COM4")
Ports.Add(name);
}
for (int i = 0; i < Ports.Count && connected == false; i++)
{
port = new SerialPort(Ports[i], 115200, Parity.None, 8, StopBits.One);
port.Open();
System.Threading.Thread.Sleep(50);
int bytesAvail = port.BytesToRead;
if (bytesAvail > 0)
{
while (bytesAvail > 0)
{
int toRead = Math.Min(bytesAvail, rxBuf.Length);
int bytesRead = port.Read(rxBuf, 0, toRead );
if (bytesRead == 0) {
bytesAvail = 0;
break;
}
for (int j = 0; j < bytesRead; j++)
{
if (rxBuf[j] == '$')
{
connected = true;
bytesAvail = 0;
break;
}
}
}
}
}
}