简体   繁体   中英

What's the correct way to access I2C devices in a multi-threaded app, in Window 10 IoT Core?

Does anyone have an example of using multiple I2C devices in multiple threads? I'm having a bit of a problem with mine, it's one of those where if I single step it everything works and if I run it full sped everything messes up - clearly a race condition. The i2C traffic is actually getting corrupted (as viewed on my logic analyzer) which surprised me a bit. I kind of assumed that I2C operations would be atomic, but it looks like that's not necessarily the case.

My app uses a temperature sensor and a motor controller, both I2C devices. The temperature probe is being sampled in a timer, which I presume is running on a worker thread.

I'm seeing data corruption of the I2C traffic, I think what could be happening is that both threads are trying to write to different slave addresses at the same time.

The documentation is a bit silent on threading issues so I'm not sure at what level I'm supposed to protect against race conditions. From the problems I'm seeing, it looks like an I2C controller can only carry out one operation at a time, so I would have to protect at the controller level.

I have some ideas on how to approach this but the documentation is a bit silent on threading requirements, so I thought I'd ask if anyone has already done it successfully before I go off down some dead ends :)

do you have a timer for scheduling operations on I2C? Outside this thread create a ConcurrentQueue as this

ConcurrentQueue<string> commandsList = new ConcurrentQueue<string>();

and when you want to send something to clinet, add a the command to the list. After, in the loop for I2C, check if you have something pending in the list and send it. In the same time try to read from device. If it doens't work, send some sample code.

I implemented a base class (wrapper) around the i2c controller instance. Each i2c device (address) derives from this base class. In the base class i added a semaphore (a singleton property for each onboard controller) to synchronize the various task read/write calls.

Works quite good with default driver. For dmap driver model (i2c lightning) i changed the semaphore with a lock mechanism. Unfortunately lightning access seems not to offer the same features of the default driver model or maybe is more sensitive to race conditions.

HTH Lorenzo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM