I have 5 analog input sensors, 3 quadrature encoders (for measuring motor speed), 3 motors, 5 LED lights connected to a 2560 Mega.
LED lights come on randomly, user presses an analog input sensor corresponding to the LED light closest to it and I log that data to a CSV file on an SD card.
At the same time I'm running a routine where I'm monitoring the motors and running them through a routine.
I'm having a hard time figuring out how to run through a loop that monitors the sensors and records data and another loop that runs the motors without it all being in a single function and since Arduino doesn't do threading does anyone have any suggestions?
I'm having a hard time figuring out how to run through a loop that monitors the sensors and records data and another loop that runs the motors without it all being in a single function and since Arduino doesn't do threading does anyone have any suggestions?
Just the usual one when one posts on the Programming forum. Post your code!
This is easier if you use classes. For example, in a program I'm writing now, I've got to poll sensors and an RTC and then make decisions based upon that -- several of these decision objects (called outletObjects in my code) are timers and other things that work asynchronously. You instantiate the classes as global variables and then link them all to the data object by passing them its address during setup. In each execution of the main loop, you poll the sensors, record the data to the globalDataObject, and then tell each OutletObject to look at that data and do their thing, one by one.
Basically, it looks something like this:
globalDataObject;
poller;
OutletObjectA;
OutletObjectB;
OutletObjectC;
setup()
{
poller.setDataSource(&globalDataObject);
OutletObjectA.setDataSource(&globalDataObject);
OutletObjectB.setDataSource(&globalDataObject);
OUtletObjectC.setDataSource(&globalDataObject);
}
loop()
{
poller.pollsensors(); // Looks at all the sensors and records the data to globalDataObject;
OutletObjectA.tick(); // Tells OutletObject A to do its thing -- it looks at the globalDataObject and, depending on the type of outletObject, does stuff based on that data
OutletObjectB.tick();
OutletObjectC.tick();
}
If you encapsulate each function as its own object like this, you get a kind of ghetto multithreading. If you take care to avoid using things like delay() and extensive looping inside the decision objects, it works pretty well.
Somebody recently advertised a library which lets you declare timers to invoke callbacks at intervals you specify. It doesn't do anything you can't code yourself just polling all your functions at whatever interval you want, but if you're struggling with that then this library might save you a lot of hassle. I'm too lazy to go searching back for the post describing it, but I'm sure you can find it yourself if you do a search.