Search code examples
c#multithreadingmonoraspberry-piwiringpi

C# I²C sender Thread via wiringPi


Im trying to do a I²C Sending Worker with a working list.

Im saveing the I²C Commands in a ConCurrentQueue and try to send it via the wiringPi Libary

Im new to Threading and Queues, thats why i cant figure out how to do it the right way.

I tried this, but it wont work at all :D

Would be nice if someone could have a look at this an tell me what im doing wrong.

class worker
{
    public bool enabled = false;
    public struct i2c_command
    {
        public int chip_number;
        public byte subadress;
        public byte data;
    }

    private ConcurrentQueue<i2c_command> i2c_commandsList = new ConcurrentQueue<i2c_command>();

    public void write_i2c(int cn, byte sa, byte data)
    {
        i2c_command i2c_c = new i2c_command();
        i2c_c.chip_number = cn;
        i2c_c.subadress = sa;
        i2c_c.data = data;
        i2c_commandsList.Enqueue(i2c_c);
    }

    public void i2c_worker()
    {
        enabled = true;
        while (enabled = true)
        {
            i2c_command i2c_send = new i2c_command();
            i2c_commandsList.TryDequeue(out i2c_send);

            WiringPi.I2C.wiringPiI2CWriteReg8(i2c_send.chip_number, i2c_send.subadress, i2c_send.data);
        }
    }
}

This is starting the Thread:

worker worker = new worker();
ThreadStart i2c_sender_ref = new ThreadStart(worker.i2c_worker);
Thread i2c_sender = new Thread(i2c_sender_ref);
i2c_sender.Start();

Solution

  • For a start you do not check if you get a command from the queue - your code needs to be more like this :

    public void i2c_worker()
    {
        enabled = true;
        while (enabled)
        {
            i2c_command i2c_send;
            if (i2c_commandsList.TryDequeue(out i2c_send))
                WiringPi.I2C.wiringPiI2CWriteReg8(i2c_send.chip_number, i2c_send.subadress, i2c_send.data);
        }
    }