ReadChar() public méthode

public ReadChar ( ) : int
Résultat int
Exemple #1
1
        public static AsyncSerial SearchPort(string write, char search, int baud=9600)
        {
            foreach (string port in SerialPort.GetPortNames())
            {
                SerialPort temp;
                try
                {
                    temp = new SerialPort(port, baud);
                    try
                    {
                        temp.Open();
                        temp.ReadTimeout = 2500;
                        temp.Write(write);
                        var v = temp.ReadChar();
                        MainForm.Instance.logControl.Add(v.ToString(), LogEntryType.Error);
                        if (v == search)
                        {
                            temp.Close();
                            return new AsyncSerial(port);
                        }
                    }
                    catch (Exception ex)
                    {}
                    finally
                    {
                        temp.Close();
                    }
                }
                catch (Exception ex)
                {}
            }

            throw new Exception("Port not found.");
        }
 public static void WritePage(byte[] pageData, int pageNumber, int pageSize, SerialPort port)
 {
     port.Write(new byte[1]{Convert.ToByte(pageNumber)},0,1);
     port.Write(pageData,pageNumber*pageSize,pageSize);
     if(port.ReadChar()!='A')
         throw new Exception("No acknowledge from target!");
 }
 private bool DetectSerialCom()
 {
     foreach (var portName in SerialPort.GetPortNames())
     {
         _serialPort = new SerialPort(portName, 38400, Parity.None, 8, StopBits.One) { ReadTimeout = 10 };
         try
         {
             _serialPort.Open();
         }
         catch (IOException)
         {
             continue;
         }
         try
         {
             _serialPort.Write("T");
             int read = _serialPort.ReadChar();
             if ((char)read == 'T')
                 return true;
         }
         catch (Exception)
         {
             continue;
         }
     }
     return false;
 }
        private string ReadLineFromGPS()
        {
            string strNMEAString = "";
            //char[]  chMessageBuffer= new char[1024];
            //Array.Clear(chMessageBuffer, 0, chMessageBuffer.Length);

            int iCurrentChar;

            for (int iNumberOfChars = 0; iNumberOfChars < chMessageBuffer.Length;)
            {
                iCurrentChar = m_spGPS.ReadChar();

                chMessageBuffer[iNumberOfChars] = Convert.ToChar(iCurrentChar);


                if (iCurrentChar == 10 ||              //LF
                    iCurrentChar == 11 ||                 //VT
                    iCurrentChar == 12 ||                 //FF
                    iCurrentChar == 13)                    //CR
                {
                    //end of line indicator...
                    if (iNumberOfChars == 0)                                        //have blank line
                    {
                        continue;                                                   // ignore the blank line...
                    }
                    strNMEAString = new string(chMessageBuffer, 0, iNumberOfChars); // ignores the trailing char
                    break;
                }

                iNumberOfChars++;
            }

            return(strNMEAString);
        }
        InternalConditions()
        {
            //verify available ports through printout
            string[] ports = SerialPort.GetPortNames();
            foreach (string s in ports)
            {
                System.Console.WriteLine(s);
            }

            weatherPort = new SerialPort("COM7", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
            weatherPort.ReadTimeout = 500;
            weatherPort.Close();
            weatherPort.Open();
            if (weatherPort.IsOpen)
            {
                System.Console.WriteLine("Port open!");
                char[] readStream = new char[255];
                byte commaCount = 0;
                int availableBytes;

                while (true)
                {
                    /* System.Threading.Thread.Sleep(500);//give the board long enough to poll data
                     availableBytes = Math.Min(255,weatherPort.BytesToRead);
                     weatherPort.Read(readStream, 0, availableBytes);
                     for (int i = 0; i < availableBytes; i++)
                     {
                         System.Console.Write(readStream[i]);
                     }
                     System.Console.WriteLine();*/

                    try
                    {
                        System.Console.Write(weatherPort.ReadChar());
                    }
                    catch (TimeoutException)
                    {
                        System.Console.WriteLine("Timed out.");
                    }

                    //System.Console.WriteLine("Data: " + weatherPort.ReadExisting());
                }

            }
            else
            {
                System.Console.WriteLine("Port not open.");
            }
            System.Console.ReadLine();
        }
Exemple #6
0
        public static void Main(string[] args)
        {
            SerialPort sp = new SerialPort("/dev/ttyACM0", 115200, Parity.None, 8, StopBits.One);
            sp.Open();
            //byte buff[];
            int input;

            for (int index = 0; index < 10; index++)
            {
                //string result = string.Format("{0} Testing", index);
                //sp.Write(result);
                input = sp.ReadChar();
                Console.Write("Recieved: ");
                Console.WriteLine(input);
            }

            sp.Close();
        }
        static bool CatchSkypeArduinoPort(out string Port, out bool NeedsUpdate)
        {
            Port = "COM1"; NeedsUpdate = false;
            string[] portNames = GetSerialPorts();
            foreach (string port in portNames)
            {
                lock (__serialLock)
                {
                    if (_serialPort.IsOpen)
                    {
                        _serialPort.Close();
                    }
                    _serialPort.PortName = port;

                    if (!_serialPort.IsOpen)
                    {
                        _serialPort.Open();
                    }
                    try
                    {
                        _serialPort.Write("X");
                        int arduinoResponse = _serialPort.ReadChar();
                        if (arduinoResponse == 88 || arduinoResponse == 89) // Skype.arduino must return X or Y.
                        {
                            Port        = port;
                            NeedsUpdate = arduinoResponse == 89;
                            return(true);
                        }
                    }
                    catch
                    {
                        Error = true;
                    }
                    finally
                    {
                        _serialPort.Close();
                    }
                }
            }

            return(false);
        }
        public static String SendSerialCommand(SerialCommand cmd)
        {
            System.Diagnostics.Debug.Assert(!String.IsNullOrEmpty(cmd.Command));
            System.Diagnostics.Debug.Assert(cmd.SerialPort != 0);

            using (SerialPort serialPort = new SerialPort(cmd.SerialPortString, cmd.BaudRate, cmd.Parity, cmd.DataBits, cmd.StopBits))
            {
                try
                {
                    serialPort.ReadTimeout = 1000;

                    serialPort.Open();
                    if (cmd.Hex)
                    {
                        byte[] buffer = HexStringToBytes(cmd.Command);
                        serialPort.Write(buffer, 0, buffer.Length);
                    }
                    else
                        serialPort.WriteLine(cmd.Command + "\r");   // Add a carriage return because most devices want one

                    string actualResponse = String.Empty;
                    foreach (char c in cmd.ExpectedResponse)
                    {
                        char rcvdChar = (char)serialPort.ReadChar();
                        actualResponse += rcvdChar;
                        if (rcvdChar != c)
                        {
                            actualResponse += serialPort.ReadExisting();
                            return actualResponse + "!=" + cmd.ExpectedResponse;
                        }
                    }

                    //System.Threading.Thread.Sleep(cmd.SleepTime);
                    return actualResponse;
                }
                finally
                {
                    serialPort.Close();
                }
            }
        }
Exemple #9
0
        public static void Main()
        {
            string[] porte = GetPortNames();
            foreach(string porta in porte)
            {
                Console.WriteLine(porta);
            }
            // initialize the serial port
            serial = new SerialPort(porte[0], 115200, Parity.None, 8, StopBits.One);
            // open the serial-port, so we can send & receive data
            serial.Open();
            // add an event-handler for handling incoming data
            //serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived);

            while(true)
            {
                Console.WriteLine("Stringa da spedire, poi Enter");
                string toSend = Console.ReadLine();
                // send the same byte back
                serial.Write(toSend);

                // create a single byte array
                byte[] bytes = new byte[1];

                string str = "";
                // as long as there is data waiting to be read
                while (serial.BytesToRead > 0)
                {
                    // read a single byte
                    //serial.Read(bytes, 0, bytes.Length);
                    char ch = (char) serial.ReadChar();
                    str += ch;
                }
                Console.Write(str);
            }
        }
        private void StartCounterThread()
        {
            SerialPort ComPort = new SerialPort(selectedPortName);
            ComPort.Open();

            using (System.IO.StreamWriter fs = System.IO.File.AppendText(this.fileName.Text))
            {
                fs.WriteLine(DateTime.Now);
                fs.Close();
            }

            while (durationTimer.Enabled)
            {
                int num = (int)ComPort.ReadChar();
                if ((num==48)|| (num==49))
                    { counts++;}
            }
            ComPort.Close();
        }
		private static bool CommandCompleted(SerialPort serialPort)
		{
			serialPort.Write("Q\r");
			char result = (char)serialPort.ReadChar();
			Console.WriteLine(result);

			if (result == '.')
			{
				return true;
			}
			else
			{
				return false;
			}
		}
Exemple #12
0
        private bool EnsurePortOpen()
        {
            try
            {
                if (m_Port != null && m_Port.IsOpen)
                    return true;

                lock (m_Lock)
                {
                    // Re-check after acquiring lock
                    if (m_Port != null && m_Port.IsOpen)
                        return true;

                    // Get rid of any old closed ports
                    if (m_Port != null)
                        m_Port.Dispose();

                    m_Port = new SerialPort(m_PortName);
                    m_Port.BaudRate = 1200;
                    m_Port.DtrEnable = true;
                    m_Port.Open();

                    // A quick echo test to make sure it exists
                    m_Port.DiscardInBuffer();
                    m_Port.Write(new byte[] { 0x00, 0x04, 0x12 }, 0, 3);
                    int echo = m_Port.ReadChar();
                    if (echo != 0x12)
                        return false; // Something went wrong opening the port - not a WinKey?

                    // Open host mode
                    m_Port.Write(new byte[] { 0x00, 0x02 }, 0, 2);
                    int version = m_Port.ReadChar();
                    if (version < 20 || version > 30)
                        return false; // Weird version code - not a WinKey?

                    m_Port.DataReceived += new SerialDataReceivedEventHandler(DataReceived);

                    // Use the speed pot value
                    m_Port.Write(new byte[] { 0x02, 0x00 }, 0, 2);

                    return true;
                }
            }
            catch
            {
                return false;
            }
        }
 /// <summary>
 /// 从串口输入缓冲区中同步读取一个字符
 /// </summary>
 /// <returns>读取的字符</returns>
 public int ReadChar()
 {
     return(COM.ReadChar());
 }
Exemple #14
0
        private void StartCounterThread()
        {
            SerialPort ComPort = new SerialPort(selectedPortName);
            ComPort.Open();

            using (System.IO.StreamWriter fs = System.IO.File.AppendText(this.fileName.Text))
            {
               // fs.WriteLine("StartTime: {0:O} EndTime{1:O}", num, time);
                fs.AutoFlush = false;
                while (durationTimer.Enabled)
                {
                    char num = (char) ComPort.ReadChar();
                    DateTime time = DateTime.Now;
                    fs.WriteLine("{0} {1:O}", num, time);

                    AddText($"{num} {time:O} \n");
                }
                fs.Close();
            }
            ComPort.Close();
        }
        public static AsyncSerial SearchPort(string write, char search, int baud = 9600)
        {
            foreach (string port in SerialPort.GetPortNames())
            {
                SerialPort temp;
                try
                {
                    temp = new SerialPort(port, baud);
                    try
                    {
                        temp.Open();
                        temp.ReadTimeout = 2500;
                        temp.Write(write);
                        var v = temp.ReadChar();
                        if (v == search)
                        {
                            temp.Close();
                            return new AsyncSerial(port);
                        }
                    }
                    catch
                    { }
                    finally
                    {
                        temp.Close();
                    }
                }
                catch
                { }
            }

            throw new Exception("Port not found.");
        }
Exemple #16
0
    void Update()
    {
        ///string s = "";
        string s = "";

        if (enableLerpTween)
        {
            TweenViewToTarget();
        }


        ///      hanfeng   ///


        if (!m)          // 如果m 刚开始不是0(因为开始是0 则true) 则 开始调用函数
        {
            Serial_Init();
            m = true;
        }

        //serialPort.DiscardOutBuffer();

        /*
         * if (serialPort.Read(gest, 0, 8) != 0)                            // gest 读进来
         * {
         *  string s = "";
         *  //if(sizeof(gest) == 7)
         *  //    Debug.Log(gest);
         *  s = System.Text.Encoding.UTF8.GetString(gest, 0, 8);
         *  Debug.Log(s);
         *  serialPort.DiscardOutBuffer();
         *
         * }
         */
        while (s.Length < 7)
        {
            char character = (char)serialPort.ReadChar();             /// ///
            s += character.ToString();
        }
        Debug.Log(s);

        serialPort.DiscardOutBuffer();

        if ((s.Contains("#-3333")) && (GameObject.Find("clone") == null))           // 向左转
        {
            // orderListy.Add(Order.TurnLeft);
            //  SmoothMenuRotationAnimation(true);
            //Debug.Log(97987978);
            // 执行OnBtnLeftClick
            OnBtnRightClick();
            //  Debug.Log(s);
        }


        if (s.Contains("!#-4444"))
        {
            // orderListy.Add(Order.TurnRight);
            // SmoothMenuRotationAnimation(false);

            OnBtnLeftClick();
        }

        if (GameObject.Find("clone") == null)
        {
            if (s.Contains("!#-1111"))
            {
                //   GameObject.Find("/fuzi");
                //   if (gameobject.Find == ""
                //   obj.scale +=...
                // if()
                //  transform.localScale -= new Vector3(1, 1, 0);
                transform.localScale = new Vector3(0, 0, 0);   //背景消失

                //Instantiate(GameObject.Find("fuzi"), new Vector3(0, 0, 0), Quaternion.identity); // 这里应该是 curCenterItem

                //  GameObject EnhanceScrollView = Instantiate(GameObject.Find("fuzi"), new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
                //  EnhanceItem curCenterItem

                //     GameObject EnhanceScrollView = Instantiate(EnhanceItem.curCenterItem, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
                GameObject Show = Instantiate(instance.curCenterItem.gameObject, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
                Show.transform.parent = GameObject.Find("Show").transform;

                Show.transform.localPosition = new Vector3(-7.0f, 46.0f, 0);
                // = GameObject.Instantiate(oklable.gameObject.Vector3.zero, Quaternion.identity) as GameObject;
                Show.name = "clone";
                //  GameObject.Find("clone").transform.position = new Vector3 (0.021875f, 0.08125f, 0);    //  (-7, 26, 0);


                //   Gameobject missileCopy = Instantiate<Missile>(missile);
                // GameObject.Find("fuzi").transform.localScale = new Vector3(0, 0, 0);
                Show.transform.localScale = new Vector3(1.1f, 1.1f, 1.1f);



                GameObject.Find("LeftArrow").SetActive(false);
                GameObject.Find("RightArrow").SetActive(false);
                GameObject.Find("DoubleArrow").SetActive(false);
                GameObject.Find("BtnLeft").SetActive(false);
                GameObject.Find("BtnRight").SetActive(false);
                GameObject.Find("BtnDoubleTap").SetActive(false);

                GameObject root7 = GameObject.Find("UI Root");
                GameObject map7  = root7.transform.Find("BtnSingle").gameObject;

                map7.SetActive(true);


                GameObject root8 = GameObject.Find("UI Root");
                GameObject map8  = root8.transform.Find("SingleArrow").gameObject;

                map8.SetActive(true);
            }
        }

        if ((GameObject.Find("clone") != null) && (s.Contains("!#-2222")))

        {
            //      if (s.Contains("!#-2222"))
            //       {
            transform.localScale += new Vector3(1, 1, 1);          // 复原

            // for(int i = 0; i < GameObject.Find("Show").transform.childCount; i++)

            //     GameObject go = GameObject.Find("Show").transform.GetChild(i).gameObject;

            Destroy(GameObject.Find("clone"));


            GameObject root1 = GameObject.Find("UI Root");
            GameObject map1  = root1.transform.Find("LeftArrow").gameObject;

            map1.SetActive(true);
            // GameObject.Find ("UI Root/LeftArrow").SetActive (true);

            GameObject root2 = GameObject.Find("UI Root");
            GameObject map2  = root2.transform.Find("RightArrow").gameObject;

            map2.SetActive(true);


            GameObject root3 = GameObject.Find("UI Root");
            GameObject map3  = root3.transform.Find("DoubleArrow").gameObject;

            map3.SetActive(true);

            GameObject root4 = GameObject.Find("UI Root");
            GameObject map4  = root4.transform.Find("BtnLeft").gameObject;

            map4.SetActive(true);

            GameObject root5 = GameObject.Find("UI Root");
            GameObject map5  = root5.transform.Find("BtnRight").gameObject;

            map5.SetActive(true);

            GameObject root6 = GameObject.Find("UI Root");
            GameObject map6  = root6.transform.Find("BtnDoubleTap").gameObject;

            map6.SetActive(true);

            GameObject root9 = GameObject.Find("UI Root");
            GameObject map9  = root9.transform.Find("BtnSingle").gameObject;

            map9.SetActive(false);


            GameObject root10 = GameObject.Find("UI Root");
            GameObject map10  = root10.transform.Find("SingleArrow").gameObject;

            map10.SetActive(false);
        }
    }