Search code examples
c#wpfobd-iielm327

ELM327 returns nothing when sending several Commands


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?


Solution

  • 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.