Methods for detecting liquid drops with phototransistor - arduino

ECE people: I have a simple circuit with an LED pointing at a phototransistor. There is a tube in between them that drops of liquid will drip through at random times. I am reading the voltage with an Arduino at the emitter as it drops when the LED is occluded.
Non-ECE people: I am reading in near constant values every time through the Arduino loop. Every once in a while this value may change for some unknown number of loops. I want to increment a counter every time this happens and avoid multiple counts.
I have tried a few methods of my own (e.g. averages last some number of values and checking for different averages) but they seem to be pretty unstable. I'm not an expert at signal processing or anything, but I was wondering what some good methods/algorithms would be for this kind of thing. Any help would be appreciated. Thanks!

This a a short function to update the count of drops detected till now.
int UpdateCount (int current, int old, int count) // current is current value of phototransisor, old is the old value
if ((current==1)&(old==0)){
return count count+1
}
}
This function takes in "filtered" current and old values of the phototransistor and based on the values updates the count.
To implement a low pass filter, refer to low-pass-filter on wiki (http://en.wikipedia.org/wiki/Low-pass_filter). You will get an expression which you can easily code.
I believe these two sub-solution on integration solve your problem.

Related

Arduino Lightbulb Control

I am completely new to arduinos, and I am trying to run a lightbulb-style apparatus off of an arduino uno, and I need it to only operate on a certain time interval that I can adjust according to the situation. I believe that there is an internal time function in the arduino that counts in milliseconds. All i need it to do is turn on after a set amount of time, and then turn off after about a minute. How would I go about setting up the code for this?
You can use the millis() function to get the current arduino operational time in milliseconds. Then compare it in the next loop(). You probably don't care what the real time is, just the relative time since the last time you checked or did something. You can create a variable to store the last event time and compare the current time to that.
Be aware that millis() may be quite large if your program runs for a long time so you should use an unsigned long type, otherwise the value may roll over the top bit and become interpreted as a negative number (this is a common problem).

Difficulty satisfying hard and medium constraints simultaneously with Optaplanner

I've implemented a sensor scheduling problem using OptaPlanner 6.2 that has 1 hard constraint, 1 medium constraint, and 1 soft constraint. The trouble I'm having is that either I can satisfy some of the hard constraints after 30 seconds of or so, and then the solver makes very little progress satisfying them constraints with additional minutes of termination. I don't think the problem is over constrained; I also don't know how to help the local search process significantly increase the score.
My problem is a scheduling one, where I precalculate all possible times (intervals) that a sensor can observe objects prior to solving. I've modeled the problem as follows:
Hard constraint - no intervals can overlap
when
$s1: A( interval!=null,$id: id, $doy : interval.doy, $interval: interval, $sensor: interval.getSensor())
exists A( id > $id, interval!=null, $interval2: interval, $interval2.getSensor() == $sensor, $interval2.getDoy() == $doy, $interval.getStartSlot() <= $interval2.getEndSlot(), $interval.getEndSlot() >= $interval2.getStartSlot() )
then
scoreHolder.addHardConstraintMatch(kcontext,-10000);
Medium constraint - every assignment should have an Interval
when
A(interval==null)
then
scoreHolder.addMediumConstraintMatch(kcontext,-100);
Soft constraint - maximize a property/value in the Interval class
when
$s1: A( interval!=null)
then
scoreHolder.addSoftConstraintMatch(kcontext,-1 * $s1.getInterval().getSomeProperty())
A: entity planning class; each instance is an assignment for a particular object (i.e has an member objectid that corresponds with one in the Interval class)
Interval: planning variable class, all possible intervals (start time, stop time) for the sensor and objects
In A, I restrict access to B instances (intervals) to just those for the object associated with that assignment. For my test case, there are 40000 or so Intervals, but only dozens for each object. There are about 1100 instances of A (so dozens of possible Intervals for each one).
#PlanningVariable(valueRangeProviderRefs = {"intervalRange"},strengthComparatorClass = IntervalStrengthComparator.class, nullable=true)
public Interval getInterval() {
return interval;
}
#ValueRangeProvider(id = "intervalRange")
public List<Interval> getPossibleIntervalList() {
return task.getAvailableIntervals();
}
In my solution class:
//have tried commenting this out since the overall interval list does not apply to all A
#ValueRangeProvider (id="intervalRangeAll")
public List getIntervalList() {
return intervals;
}
#PlanningEntityCollectionProperty
public List<A> getAList() {
return AList;
}
I've reviewed the documentation and tried a lot of things. My problem is somewhat of a cross between the nurserostering and course scheduling examples, which I have looked at. I am using the FIRST_FIT_DECREASING construction heuristic.
What I have tried:
Turning on and off nullable in the planning variable annotation for A.getInterval()
Late acceptance, Tabu, both.
Benchmarking. I wasn't seeing any problems and average
Adding an IntervalChangeFactory as a moveListFactory. Restricting the custom ChangeMove to whether the interval can be accepted or not (i.e. enforcing or not the hard constraint in the IntervalChangeMove.isDoable).
Here is an example one, where most of the hard constraints are not satisfied, but the medium ones are:
[main] INFO org.optaplanner.core.impl.solver.DefaultSolver - Solving started: time spent (202), best score (0hard/-112500medium/0soft), environment mode (REPRODUCIBLE), random (WELL44497B with seed 987654321).
[main] INFO org.optaplanner.core.impl.constructionheuristic.DefaultConstructionHeuristicPhase - Construction Heuristic phase (0) ended: step total (1125), time spent (2296), best score (-9100000hard/0medium/-72608soft).
[main] INFO org.optaplanner.core.impl.localsearch.DefaultLocalSearchPhase - Local Search phase (1) ended: step total (92507), time spent (30000), best score (-8850000hard/0medium/-74721soft).
[main] INFO org.optaplanner.core.impl.solver.DefaultSolver - Solving ended: time spent (30000), best score (-8850000hard/0medium/-74721soft), average calculate count per second (5643), environment mode (REPRODUCIBLE).
So I don't understand is why the hard constraints can't be deal with by the search process. Any my calculate count per second has dropped to below 10000 due to all the tinkering I've done.
If it's not due to the Score trap (see docs, this is the first thing to fix), it's probably because it gets stuck in a local optima and there are no moves that go from 1 feasible solution to another feasible solution except those that don't really change much. There are several ways to deal with that:
Add course-grained moves (but still leave the fine-grained moves such as ChangeMove in!). You can add generic course grained moves (such as the pillar moves) or add a custom Move. Don't start making smarter selectors that try to only select feasible moves, that's a bad idea (as it will kill your ACC or will limit your search space). Just mix in course grained moves (= diversification) to complement the fine grained moves (= intensification).
A better domain model might help too. The Project Job Scheduling and Cheap Time scheduling examples have a domain model which naturally leads to a smaller search space while still allowing all feasible solutions.
Increase Tabu list size, LA size or use a hard constraint in the SA starting temperature. But I presume you've tried that with the benchmarker.
Turn on TRACE logging to see optaplanner's decision making. Only look at the part after it reaches the local optimum.
In the future, I 'll also add Ruin&Recreate moves, which will be far less code than custom moves or a better domain model (but it will be less efficient).

Arduino 16 Megahertz, how fast is my program running?

So, in theory how many times per second will the loop function be executed?
Can this be calculated based on the Megahertz? Arduino runs at 16 Megahertz
As Gerald said, you cannot simply take the clock frequency and calculate the loop method's iterations per second, some functions take long, some dont, what about delay(1000) and conditionals?
If your program needs to know how many times the loop is happening per second you can use the millis and micros methods. For example you can count the amount of times the loop has looped and save every second by monitoring millis or micros.

How do I stop all 262,144 kernels if I find my answer

I am using pyopencl to find a certain pixel in a 512 x 512 (262,144 pixels) image. I am starting (512,512), when I run my program and comparing the pixel's neighbors to a known group of neighbors. I am doing image synthesis. I don't want to wait around for the remaining kernels to run if I find my group of pixels within a kernel. Is there a way to terminate the rest of the running kernels with a kernel program ?
Thanks
Tim
When you queue a kernel with many work items, it gets divided up into work groups and threads which keep the GPU busy. Really large global sizes start as many threads as they can and issue new ones when the old ones finish. So you could find the smallest global size that still performs well, and queue many of those (instead of one large one), but also be checking on the results of the previous ones you queued (use events to know when they are done, and read back memory to get their results). When you get the correct answer, stop queueing kernels.
so instead of this:
queue entire job (say, 4096 x 4906)
do:
do
{
queue some work (say, 32 x 32)
check if any of the prior work queued is done and check if it got the answer
}
while (no more work OR answer found)
You'll need to figure out the right tradeoff between the size of the smaller jobs and the overhead of checking their results versus extra work done.
Your question is a big issue and problem of parallelism.
What to do when one of your parallel threads has already the answer to the problem?
OpenCL does not allow to control the kernel execution. Not even at host level. And this is a big problem. However it is how it has to be, since, if the work items do not run freely detached one from another then it is not fully parallel.
The only solution is to split the computation into small parts and check the completion of each of them. But, sometimes the parts are already very small (like in your case 512x512 is quite small).
In your specific case I would process everything (512x512), after that I would use another kernel to get the final results out of the 512x512 set.
First thought it to have some sort of global memory flag that each kernel can read and set. This approach requires atomicity, so make sure to use the atomic_ functions.
__kernel void t(__global int *Data,
__global int *Flag){
if(atomic_max(*Flag, 0) == 0){
//perform calc on Data
if(PixelsFound){
//Set the flag to +1
*Flag = atomic_inc(*Flag);
}
}
}
Community, feel free to comment if this is known not to work!

qrand is not generating a random number

I have a QT app, running 2 more threads.
Inside the threads I use the qrand function to generate a random number. The following is the code used to get the number, where m_fluctuations max is a double.
int fluctuate = qrand() % (int)(m_FluctuationMax * 100);
I tried adding the following code in the main thread, and also inside the thread classes.
QTime now = QTime::currentTime();
qsrand(now.msec());
Now the problem is, that the values being generated are always the same, each time the application is started.
Shouldn't they be different, since the seed is set by 'currentTime()'.
Thanks
I had my qsrand() in the thread/class constructor. When i moved it to the run() function, it started to work randomly. Not sure why it would not work from the constructor though. Thanks everyone for your help.
This may help anyone who happened to have a similar problem:
qsrand(static_cast<quint64>(QTime::currentTime().msecsSinceStartOfDay()));
array<int, 5> arr = {qrand(), qrand(), qrand(), qrand(), qrand()};
for(auto i : arr)
cout << i << endl;
I had my qsrand() in the thread/class constructor. When i moved it to the run() function, it started to work randomly. Not sure why it would not work from the constructor though.
qsrand() uses thread-local storage to store the seed which is actually the pseudorandom number generator state that also gets updated on each call to qrand(). If you seed the PRNG outside the thread where you will be using it, that seed does not influence the outcome. Thread-local storage usually defaults to zero so that way you would get the same sequence of pseudorandoms every time because the seed is always the same.
The first thing I'd be checking is the value of now.msec(). It only returns the millisecond part of the current time and the doco states:
Note that the accuracy depends on the accuracy of the underlying operating system; not all systems provide 1-millisecond accuracy.
It may be that your platform always returns the same value for msec(). If that's the case, you could try using minutes and seconds combined somehow (assuming you're not running your code multiple times every second).
You haven't stated which platform you're running on but the Qt source code only supports sub-second resolution if either Q_OS_WIN or Q_OS_UNIX is set.
Keep in mind that the random numbers are per-thread so you should probably do the qsrand in each thread, lest it be automatically seeded with 1.

Resources