3

I'm developing a WPF application, which interacts with my ELM327. It's connected to my PC via bluetooth and it's able to establish it successfully.

When I manually send one command at a time (e.g. "010C\r") it properly returns me the RPM of my car ("010C\r41 0C 0C 30 \r").

I then tried to send the command every three seconds. The first time, it sometimes works, if it's sent the second time, the ELM327 returns nothing. If I debug it step by step, the values get properly returned by the ELM without any errors. I think the reader is reading the response, before the ELM has time to send it.

The loop:

private async Task InitializeElm327()
    {
        string answer = string.Empty;

        tbx_dump.Text += "\n\nSetting up Reader and Writer";
        SetupReaderWriter();
        tbx_dump.Text += "\nReader and Writer setup finished";

        while (true)
        {
            int revs = await GetRPM();
            tbx_revs.Text = revs.ToString();
            System.Threading.Thread.Sleep(3000);
        }
    }

The function that returns the RPM:

private async Task<int> GetRPM()
    {
        string cmdAnswer = await SendCommand("010C\r");
        int rpm = ConvertRPM(cmdAnswer);
        return rpm;
    }

The function that sends the command:

private async Task<string> SendCommand(string command)
    {
        tbx_dump.Text += "\n\nSending command " + command + " to Elm327";
        m_dataWriter.WriteString(command);
        await m_dataWriter.StoreAsync();
        await m_dataWriter.FlushAsync();
        uint count = await m_dataReader.LoadAsync(512);
        return m_dataReader.ReadString(count).Trim('>');
    }

Is there a way to prevent this from happening?

Cardstdani
  • 4,999
  • 3
  • 12
  • 31
  • 2
    `System.Threading.Thread.Sleep(3000);` have you tried `await Task.Delay(3000);` instead? – Fildor Jul 09 '20 at 09:18
  • 2
    I'd also use a `Progress` to make sure UI ELements are accessed on the UI thread. – Fildor Jul 09 '20 at 09:20
  • 2
    @Fildor Sorry for such a late answer, I only had time to try it out today. It works fine on an ECU Simulation, I'm gonna try it out in my car too tonight. Thank you :) –  Jul 28 '20 at 12:00
  • 1
    @reithoufr which library are you using BTW? looks like UWP stuff accessing BT stack directly and not via virtual serial port? – Falco Alexander Jan 22 '22 at 08:46

1 Answers1

2

As fildor commented, the mistake was the System.Threading.Thread.Sleep(3000);

I simply replaced it with await Task.Delay(3000); and now it properly returns the RPM.