当前位置: 首页>>代码示例>>C#>>正文


C# SerialPort.ReadByte方法代码示例

本文整理汇总了C#中System.IO.Ports.SerialPort.ReadByte方法的典型用法代码示例。如果您正苦于以下问题:C# SerialPort.ReadByte方法的具体用法?C# SerialPort.ReadByte怎么用?C# SerialPort.ReadByte使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.Ports.SerialPort的用法示例。


在下文中一共展示了SerialPort.ReadByte方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: IsPVC

		bool IsPVC(SerialPort port)
		{
			string returnMessage = "";
			try {
				if (port.IsOpen)
					port.Close ();

				port.Open ();

				Thread.Sleep (1500); // Fails if this delay is any shorter

				port.Write ("#");
				port.Write (port.NewLine);

				Thread.Sleep (500); // Fails if this delay is any shorter

				int count = port.BytesToRead;
				int intReturnASCII = 0;
				while (count > 0) {
					intReturnASCII = port.ReadByte ();
					returnMessage = returnMessage + Convert.ToChar (intReturnASCII);
					count--;
				}
			} catch {
			} finally {
				port.Close ();
			}
			if (returnMessage.Contains (Identifier)) {
				return true;
			} else {
				return false;
			}
		}
开发者ID:abrankhalid,项目名称:PVCharacterization,代码行数:33,代码来源:DuinoPortDetector.cs

示例2: GetTemperature

 public XmlElement GetTemperature(string port, string baudRate)
 {
     try
     {
         _serialPort = new SerialPort(port,Convert.ToInt32(baudRate));
         _serialPort.Open();
         if (!_serialPort.IsOpen)
         {
             throw new Exception("Cannot Open Serial Port...");
         }
         count = _serialPort.BytesToRead;
         if (count < 1)
         {
             throw new Exception("No Data to Read...");
         }
         else
         {
             while (count > 0)
             {
                 int byteData = _serialPort.ReadByte();
                 data = data + Convert.ToChar(byteData);
             }
         }
         _result = GetXML(data.ToString());
     }
     catch (Exception ex)
     {
         _result = GetExceptionXML(ex.ToString());
     }
     return _result;
 }
开发者ID:stellant,项目名称:LaserPoint,代码行数:31,代码来源:Temperature.svc.cs

示例3: Identify

        public string Identify(SerialPort port)
        {
            string returnMessage = "";
            try {
                if (port.IsOpen)
                    port.Close ();

                port.Open ();

                Thread.Sleep (1500); // Fails sometimes if this delay is any shorter

                port.Write (IdentifyRequest);
                port.Write (port.NewLine);

                Thread.Sleep (500); // Fails sometimes if this delay is any shorter

                int count = port.BytesToRead;
                int intReturnASCII = 0;
                while (count > 0) {
                    intReturnASCII = port.ReadByte ();
                    returnMessage = returnMessage + Convert.ToChar (intReturnASCII);
                    count--;
                }
            } catch {
            } finally {
                port.Close ();
            }

            return returnMessage.Trim();
        }
开发者ID:CompulsiveCoder,项目名称:duinocom,代码行数:30,代码来源:DuinoIdentifier.cs

示例4: Main

        static void Main(string[] args)
        {
            SerialPort comm;

            string portName;
            long portNum;
            long block;
            string input;
            string filename;

            long page;
            byte checksum;

            Console.Write("COM Port ? ");
            input = Console.ReadLine();
            portNum = long.Parse(input);

            Console.Write("Block ? ");
            input = Console.ReadLine();
            block = long.Parse(input);

            Console.Write("Filename ? ");
            filename = Console.ReadLine();

            portName = "COM" + portNum.ToString();

            block = 0;

            comm = new SerialPort(portName, 115200, Parity.None, 8, StopBits.One);
            comm.Open();

            BinaryWriter bw = new BinaryWriter(File.Open(filename, FileMode.Create));
            byte data;

            byte[] buf = new byte[1];
            buf[0] = (byte) block;
            comm.Write(buf, 0, 1);

            checksum = 0;

            for (page = 0; page < 256; page++)
            {
                Console.WriteLine("Reading page " + page.ToString());
                for (int i = 0; i < 128; i++)
                {
                    data = (byte)comm.ReadByte();
                    bw.Write(data);
                    if (i != 5)
                        checksum += data;
                }
            }

            comm.Close();

            Console.WriteLine("Checksum : " + checksum.ToString());
            Console.WriteLine("Complete");
        }
开发者ID:lanrat,项目名称:DC_20_badge,代码行数:57,代码来源:Program.cs

示例5: Main

        //    Use included loader.bin for the Pi
        //    run this program, put a breakpoint at the end and use the debugger to see what data is returned.
        // NOTE - this should compile with any C# compiler, but the serial port stuff is Windows specific.
        // I use an FT232-based USB adapter with the Ground/Tx/Rx pins hooked up to the Pi, and the port set to COM7.
        // Please feel free to write something easier to use!!
        static void Main(string[] args)
        {
            var sp = new SerialPort("COM7", 115200, Parity.None, 8);
            sp.Open();

            byte[] data;
            using (var sr = new BinaryReader(new FileStream(PATH, FileMode.Open, FileAccess.Read)))
            {
                int length = (int)sr.BaseStream.Length;
                sr.BaseStream.Position = 0;

                data = new byte[length + 5];
                // 0x7C indicates start of data to send
                data[0] = 0x7C;
                // size of data to send, 32-bit, big endian
                data[4] = (byte)(length & 0xFF);
                data[3] = (byte)((length >> 8) & 0xFF);
                data[2] = (byte)((length >> 16) & 0xFF);
                data[1] = (byte)((length >> 24) & 0xFF);

                // data to send
                sr.Read(data, 5, length);
            }

            sp.Write(data, 0, data.Length);

            // size of data to receive, 32-bit, big endian
            int recvLength = 0;
            for (int i = 0; i < 4; i++)
            {
                recvLength = (recvLength << 8) | (byte)sp.ReadByte();
            }

            // data to receive
            byte[] recvData = new byte[recvLength];
            for (int i = 0; i < recvData.Length; i++)
            {
                recvData[i] = (byte)sp.ReadByte();
            }

            // PUT BREAKPOINT HERE
        }
开发者ID:thubble,项目名称:vcdevtools,代码行数:47,代码来源:TestSerialPort.cs

示例6: Main

        static void Main(string[] args)
        {
            SerialPort comm;

            string portName;
            long portNum;
            long block;
            string input;
            string filename;
            long pageIndex;

            byte inData;

            byte checksum;
            byte[] buf = new byte[1];

            if (args.Length < 1)
                return;

            Console.Write("COM Port ? ");
            input = Console.ReadLine();
            portNum = long.Parse(input);

            portName = "COM" + portNum.ToString();

            //filename = args[0];
            filename = "C:\\badge\\out.eeprom";

            comm = new SerialPort(portName, 115200, Parity.None, 8, StopBits.One);
            comm.Open();

            BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open));
            byte data;

            // Send the 100 code to start things off
            buf[0] = (byte)100;
            comm.Write(buf, 0, 1);

            for (pageIndex = 0; pageIndex < 256; pageIndex++)
            {
                inData = (byte)comm.ReadByte();
                Console.WriteLine("Writing page " + inData.ToString());

                for (int i = 0; i < 128; i++)
                {
                    data = br.ReadByte();
                    buf[0] = data;
                    comm.Write(buf, 0, 1);
                }
            }
            comm.Close();

            Console.WriteLine("Complete");
        }
开发者ID:lanrat,项目名称:DC_20_badge,代码行数:54,代码来源:Program.cs

示例7: waitForSequence

        /// <summary>
        /// Waitforsequence with option for verbosity
        /// </summary>
        /// <param name="str">String to look for</param>
        /// <param name="altStr">String to look for but don't want</param>
        /// <param name="sp">SerialPort object.</param>
        /// <param name="verbose">Boolean to indicate verbosity.</param>
        /// <returns>Boolean to indicate if str or altStr was found.</returns>
        public static Boolean waitForSequence(String str, String altStr, SerialPort sp, Boolean verbose)
        {
            Boolean strFound = false, altStrFound = false;
            Byte[] input = new Byte[256];
            String inputStr;
            Int32 i;

            while ((!strFound) && (!altStrFound))
            {

            i = 0;
            do
            {
                input[i++] = (Byte)sp.ReadByte();
                //Console.Write(input[i - 1] + " ");
            } while ( (input[i - 1] != 0) &&
                      (i < (input.Length - 1)) &&
                      (input[i - 1] != 0x0A) &&
                      (input[i - 1] != 0x0D) );

            // Convert to string for comparison
            if ((input[i-1] == 0x0A) || (input[i-1] == 0x0D))
                inputStr = (new ASCIIEncoding()).GetString(input, 0, i-1);
            else
                inputStr = (new ASCIIEncoding()).GetString(input, 0, i);

            if (inputStr.Length == 0)
            {
                continue;
            }

            // Compare Strings to see what came back
            if (verbose)
                Console.WriteLine("\tTarget:\t{0}", inputStr);
            if (inputStr.Contains(altStr))
            {
                altStrFound = true;
                if (String.Equals(str, altStr))
                {
                    strFound = altStrFound;
                }
            }
            else if (inputStr.Contains(str))
            {
                strFound = true;
            }
            else
            {
                strFound = false;
            }
            }
            return strFound;
        }
开发者ID:shenbokeji,项目名称:SinoMT,代码行数:61,代码来源:SerialIO.cs

示例8: GetTemperature

 public XmlElement GetTemperature(string port, string baudRate)
 {
     try
     {
         _serialPort = new SerialPort(port);
         _serialPort.BaudRate = Convert.ToInt32(baudRate);
         _serialPort.Parity = Parity.None;
         _serialPort.StopBits = StopBits.One;
         _serialPort.DataBits = 8;
         _serialPort.Handshake = Handshake.None;
         _serialPort.RtsEnable = true;
         _serialPort.ReadTimeout = 1000;
         if (_serialPort.IsOpen)
         {
             _serialPort.Close();
             _serialPort.Open();
         }
         else
         {
             _serialPort.Open();
         }
         Thread.Sleep(1000);
         count = _serialPort.BytesToRead;
         if (count < 1)
         {
             throw new Exception("No Data to Read..."+count);
         }
         else
         {
             while (count > 0)
             {
                 int byteData = _serialPort.ReadByte();
                 data = data + Convert.ToChar(byteData);
                 count--;
             }
         }
         _serialPort.DiscardOutBuffer();
         _serialPort.Close();
         _result = GetXML(data.Trim());
     }
     catch (Exception ex)
     {
         if (_serialPort.IsOpen)
             _serialPort.Close();
         _result = GetExceptionXML(ex.ToString());
     }
     return _result;
 }
开发者ID:stellant,项目名称:LaserpointFinal,代码行数:48,代码来源:Temperature.svc.cs

示例9: Init

		internal void Init()
		{
			comPort = new SerialPort(ApplicationConfig.Port, 9600, Parity.None, 8, StopBits.One);
			comPort.Handshake = Handshake.None;
			comPort.Open();

			while (!_stop)
			{
				while (comPort.BytesToRead != 0)
					recievedData.Enqueue((byte)comPort.ReadByte());

				ProcessReceivedData();

				Thread.Sleep(20);
			}
		}
开发者ID:vaclavek,项目名称:PocketHome.Net,代码行数:16,代码来源:Communicator.cs

示例10: ReadPacket

        /// <summary>
        /// Reads the packet from the com port
        /// </summary>
        /// <param name="serialPort"></param>
        /// <returns></returns>
        public bool ReadPacket(SerialPort pPort)
        {
            bool vShortContent = false;

            if (pPort.BytesToRead == 0) {
                return false;
            }

            while ((char)pPort.ReadByte() != '$') { }
            while ((char)pPort.ReadByte() != '*') { }

            this.mID = (byte)pPort.ReadByte();
            this.mType = (byte)pPort.ReadByte();
            this.mSubType = (byte)pPort.ReadByte();
            this.mExpectAcknowledge = ((byte)pPort.ReadByte() == 0 ? false : true);

            for (int i = 0; i < CONTENT_LENGTH; ) {
                this.mContent[i++] = (char)pPort.ReadByte();
                if (i < CONTENT_LENGTH - 1 && this.mContent[i-1] == '*')
                {
                    this.mContent[i++] = (char)pPort.ReadByte();
                    if (this.mContent[i-1] == '$')
                    {
                        vShortContent = true;
                        break;
                    }
                }
            }
            if (!vShortContent)
            {
                while ((char)pPort.ReadByte() != '*') { }
                while ((char)pPort.ReadByte() != '$') { }
            }

            //remove trailing *$
            if (this.mContent != null) {
                for (int i = 0; i < CONTENT_LENGTH-1; i++) {
                    if (this.mContent[i] == '*' && this.mContent[i + 1] == '$') {
                        this.mContent[i] = (char)0;
                        break;
                    }
                }
            }
            return true;
        }
开发者ID:Lords08,项目名称:alanarduinotools,代码行数:50,代码来源:ARCPO_Packet.cs

示例11: ReadLine

 private static string ReadLine(SerialPort port, int timeout) {
   int i = 0;
   StringBuilder builder = new StringBuilder();
   while (i < timeout) {
     while (port.BytesToRead > 0) {
       byte b = (byte)port.ReadByte();
       switch (b) {
         case 0xAA: return ((char)b).ToString();
         case 0x0D: return builder.ToString();
         default: builder.Append((char)b); break;
       }
     }
     i++;
     Thread.Sleep(1);
   }
   throw new TimeoutException();
 }
开发者ID:jwolfm98,项目名称:HardwareMonitor,代码行数:17,代码来源:HeatmasterGroup.cs

示例12: readSequence

        public static string readSequence(SerialPort sp, Boolean verbose)
        {
            Boolean strFound = false, altStrFound = false;
            Byte[] input = new Byte[256];
            String inputStr;
            Int32 i;
            sp.ReadTimeout=300000;
            while ((!strFound) && (!altStrFound))
            {

            i = 0;
            do
            {
                try
                {
                    input[i++] = (Byte)sp.ReadByte();
                }
                catch
                {
                    //Console.Write(".");
                }
                //Console.Write(input[i - 1] + " ");
            } while ( (input[i - 1] != 0) &&
                      (i < (input.Length - 1)) &&
                      (input[i - 1] != 0x0A) &&
                      (input[i - 1] != 0x0D) );

            // Convert to string for comparison
            if ((input[i-1] == 0x0A) || (input[i-1] == 0x0D))
                inputStr = (new ASCIIEncoding()).GetString(input, 0, i-1);
            else
                inputStr = (new ASCIIEncoding()).GetString(input, 0, i);

            if (inputStr.Length == 0)
            {
                continue;
            }

            // Compare Strings to see what came back
            if (verbose)
                Console.WriteLine("\tTarget:\t{0}", inputStr);
                        return inputStr;
               }
            return "FAIL";
        }
开发者ID:hummingbird2012,项目名称:flashUtils,代码行数:45,代码来源:SerialIO.cs

示例13: read

        //Lectura en el puerto para esperar mensaje del arduino
        public String read()
        {
            using (SerialPort sp = new SerialPort("COM4", 9600)) // Pasarlos por parámetro
            {
                try
                {
                    //Abre el puerto especifico
                    sp.Open();

                    //Preparamos variables
                    string returnMessage = "";
                    int intReturnASCII = 0;

                    /* Enciclamos el sp.ReadByte(); para obtener los bytes desde el arduino
                     * cada byte se pega a la linea de caracteres de retorno.
                     *  ## Esto deberia ser una tarea asyncrona ·##
                    */
                    while (true)
                    {
                        //Lee un byte
                        intReturnASCII = sp.ReadByte();

                        //Cuando lee un byte asigna a la cadena de retorno toda la cadena + el byte
                        returnMessage = returnMessage + Convert.ToChar(intReturnASCII);

                        //La cantidad de caracteres que queremos leer del codigo de la tarjeta
                        if (returnMessage.Length == 26) // Pasarlo por parámetro
                        {
                            sp.Close();
                            return returnMessage;

                        }
                    }
                }
                //Si encuentra un error en el proceso
                catch(Exception e){
                    sp.Close();
                    return "";
                }

                }
        }
开发者ID:devaallanrd,项目名称:XNBA-Master,代码行数:43,代码来源:Read.cs

示例14: RunTests

        private static void RunTests()
        {
            SerialPort port = new SerialPort("COM6", 9600);
            port.Open();

            const int count = 2;

            port.ErrorReceived += (s, e) => {
                Console.WriteLine("Error: " + e.EventType);
            };

            while (true) {
                Random random = new Random();
                byte[] buffer = new byte[count];

                buffer[0] = (byte)random.Next(255);
                buffer[1] = (byte)random.Next(255);

                port.Write(buffer, 0, count);
                tx_bytes += 1;

                byte[] input = new byte[count];

                int readed = 0;
                for (int i = 0; i < count; i++) {
                    input[i] = (byte)port.ReadByte();
                    rx_bytes++;
                }

                rx_bytes += readed;

                Console.WriteLine("{0} - expected: {1}, received: {2}", rx_bytes, buffer, input);

                for (int i = 0; i < count; i++) {
                    if (buffer[i] != input[i]) {
                        Console.WriteLine("miss: {0} != {1}", buffer[i], input[i]);
                    }
                }
            }
        }
开发者ID:pepyakin,项目名称:msp430-beeper-host,代码行数:40,代码来源:Program.cs

示例15: Main

        static void Main(string[] args)
        {
            receiverPort = new SerialPort();
            receiverPort.BaudRate = 9600;
            receiverPort.PortName = "COM18";
            receiverPort.Open();

            senderPort = new SerialPort();
            senderPort.BaudRate = 4800;
            senderPort.PortName = "COM19";
            senderPort.Open();

            while (true)
            {
                int val = senderPort.ReadByte();
                byte b = (byte)val;
                byte[] bytes = new byte[1];
                bytes[0] = b;
                receiverPort.Write(bytes, 0, 1);
                Console.Write(bytes[0].ToString());
            }
        }
开发者ID:Osceus,项目名称:Kinect,代码行数:22,代码来源:Program.cs


注:本文中的System.IO.Ports.SerialPort.ReadByte方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。