Example #1
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (_comPort != null && _comPort.IsOpen)
            {
                _comPort.Close();
            }

            _comPort           = new SerialPort(comboBoxPorts.Text, (int)numericBaudRate.Value);
            _comPort.Parity    = Parity.None;
            _comPort.StopBits  = StopBits.One;
            _comPort.DataBits  = 8;
            _comPort.Handshake = Handshake.None;

            AppendConsoleText("Connecting...\r\n");

            try
            {
                _comPort.Open();
            }
            catch (Exception ex)
            {
                AppendConsoleText($"Error! Cannot open {comboBoxPorts.Text}: {ex.Message}");
                UpdateConnected(false);
                return;
            }

            _rtd = new RTD266x(_comPort);

            UpdateConnected(true);

            RTD266x.ErrorCode errorCode = RTD266x.ErrorCode.NoError;
            uint errorInfo = 0;

            RTD266x.Result result  = RTD266x.Result.NotOk;
            int            retries = 5;

            // try to connect a few times
            for (int i = 0; i < retries; i++)
            {
                result = _rtd.ReadErrorCode(out errorCode, out errorInfo);

                if (result == RTD266x.Result.Ok)
                {
                    break;
                }

                _rtd.ClearReadBuffer();

                AppendConsoleText($"Connection error: {RTD266x.ResultToString(result)}, retrying... ({i + 1}/{retries})\r\n");
            }

            if (result != RTD266x.Result.Ok)
            {
                AppendConsoleText($"Connection error: {RTD266x.ResultToString(result)}\r\n");
                AppendConsoleText("Did you download the sketch RTD266xArduino to your Arduino?\r\n");
                AppendConsoleText("Is the Arduino connected properly to the display?\r\n");
                AppendConsoleText("Did you select the correct COM port?\r\n");
                AppendConsoleText("Is the display powered?\r\n");
                AppendConsoleText("If the Arduino's user LED is on, the I2C connection to the display does not work.\r\n");
                AppendConsoleText("Press the Arduino's reset button and try again.\r\n\r\n");

                btnDisconnect_Click(null, null);
                return;
            }

            if (errorCode == RTD266x.ErrorCode.NoError)
            {
                AppendConsoleText("Connection successful!\r\n");
            }
            else
            {
                AppendConsoleText("Initialization error: ");
                AppendConsoleText(RTD266x.ErrorCodeToString(errorCode, errorInfo) + "\r\n");

                btnDisconnect_Click(null, null);
            }
        }