1

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();
VMAtm
  • 27,943
  • 17
  • 79
  • 125
Daniel Bucher
  • 25
  • 1
  • 6
  • You should consider posting this in https://raspberrypi.stackexchange.com – John M. Wright Jun 12 '17 at 12:59
  • Can you show the code where you create & start the thread to do the I2C write. – PaulF Jun 12 '17 at 13:03
  • The main function i look for has nothing to do with Raspberry... Im just looking for the ConcurrentQueue and how i can use it in my example – Daniel Bucher Jun 12 '17 at 13:04
  • @PaulF I am initializing the "worker" class in the "main" function and starting a thread with the "i2c_worker" fuction, so I can add commands to the Thread via the "write_i2c fuction" – Daniel Bucher Jun 12 '17 at 13:06
  • Seeing your code would help more than you trying to explain what you are trying to do - what is your "worker" class? the "i2c_worker" does not start a thread, it consists of a while loop (which has an error in it, btw). – PaulF Jun 12 '17 at 13:13
  • @PaulF added and corrected the i2c_worker – Daniel Bucher Jun 12 '17 at 13:24

1 Answers1

1

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);
    }
}
PaulF
  • 6,673
  • 2
  • 18
  • 29