I am currently working on a little Arduino project, which is using an infrared temperature sensor for measuring certain surface temperatures.
The hardware works perfectly and also simply reading analog signals with analogRead() works fine, but using this simple function for filtering the measured analog values to get better results just doesn't get along with the Arduino.
Every time the sketch running this function is uploaded to the Arduino (Pro Micro), the program just gets stuck and disables the Arduino, so that it has to be reset before appearing again in the "Ports" Menu as a COM Port.
Here is the simple function in which I cannot find the bug:
int TemperatureDifferenceSensor::measureRawFilteredTemperatureValue(int numberOfMeasurements) {
int temperatureMeasurementValueSum = 0;
int maxMeasuredTempValue = 0;
int minMeasuredTempValue = 0;
for (int i = 0; i < numberOfMeasurements; ++i) {
int measuredTemperatureValue = analogRead(analogObjectTempPin);
temperatureMeasurementValueSum += measuredTemperatureValue;
if (measuredTemperatureValue > maxMeasuredTempValue) {
maxMeasuredTempValue = measuredTemperatureValue;
} else if (measuredTemperatureValue < minMeasuredTempValue) {
minMeasuredTempValue = measuredTemperatureValue;
}
// A small delay, to not measure the same or similar value every time...
delay(10);
}
temperatureMeasurementValueSum -= maxMeasuredTempValue;
temperatureMeasurementValueSum -= minMeasuredTempValue;
int temperatureMeasurementAverageValue = (int) (temperatureMeasurementValueSum / (numberOfMeasurements - 2));
return temperatureMeasurementAverageValue;
}
If analogRead and delay works as you expected, it should be somewhat ok. One big issue with the function is that it can't be called with argument 2. This would cause zero-division exception and probably also a black hole. Why not something like:
...
} // the for-loop closes here.
if (numberOfMeasurements == 0)
return 0;
// Must have at least 3 measurements in order to remove 2 of them.
else if (numberOfMeasurements > 2)
{
temperatureMeasurementValueSum -= maxMeasuredTempValue;
temperatureMeasurementValueSum -= minMeasuredTempValue;
numberOfMeasurements -= 2; // Compensate removing two measurements.
}
// Average is sum divided by measurements.
int temperatureMeasurementAverageValue = temperatureMeasurementValueSum / numberOfMeasurements;
return temperatureMeasurementAverageValue;
Related
I am using STM32F769 Disc board with Mbed online compiler. My task is to change the PWM frequency and duty ratio according to input.
I've created a simple algorithm according to my need, the program is working well but whenever the controller updates the PWM frequency, there is strange behavior(overlapped maybe, difficult to explain verbally for me), the frequency is changed instantly and the output is incorrect at that moment. For other controllers (like arduino) this never happens, the controller updates value after the time period of PWM is over. But not in this case.
What can be wrong?
I thought to add a small delay before value is updated but that will not work, as every time a different delay would be needed. I have attached the code and screenshots.
#include "mbed.h"
AnalogIn analog_value(A0);
PwmOut pulse(D11);
int main() {
double meas_v = 0;
double out_freq, out_duty, s_time;
while (1) {
meas_v = analog_value.read() * 3300;
if (meas_v < 1) {
out_freq = 50000;
out_duty = 40;
} else if (meas_v >= 1000) {
out_freq = 100000;
out_duty = 80;
} else {
out_freq = 50000 + (meas_v * 50);
out_duty = 40 + (meas_v * 0.04);
}
pulse.period(1.0 / out_freq);
pulse = out_duty / 100;
s_time = 0.0001;
wait(s_time);
}
}
The output should be updated after the current period is completed, not instantly.
Error I am getting
The underlying HAL code probably resets the current count value of the timer when you set the new period. You'll have to read the current timer cnt value and wait for it to reach 0. You can set a new period when the timer cnt value reaches 0.
You need to update the value in the update interrupt or use the timer DMA burst mode
I am writing a printing function synonymous with 3D printing which reads an SD file and then acts on each line of the data. Below is my code: (variables have been assigned previously and code works).
void Print() {
Home_Y();
delay(100);
Home_X();
px = 75;
py = 67.5;
Read_SD(); //Opens the SD card
while (printFile.available() > 0) {
char character = printFile.read();
if (bufferposition < buffer_size - 1)
{
Buffer[bufferposition++] = character;
}
if (character == '\n')
{
Buffer[bufferposition] = 0;
//****************// add in command here
bufferposition = 0;
}
}
//The code then continues down further.
I want to run a separate function at the point in the code marked "//***//" continuously until switched off later in the code. My problem is that I can only run this function once, multiple calls would just delay the following processes.
My Question:
I was wondering if there was any way around this, or to simulate two functions running simultaneously. I have read somewhere about interrupts and timing delays, but wasn't sure if I was heading down the right path?
I want to write a program in c++ that are able to stress a windows 7 system. In my intention I want that this program brings the cpu usage to 100%, using all ram installed.
I have tried with a big FOR cycle that run a simple multiplication at every step: the cpu usage increase but the ram used remain low.
What is the best approach to reach my target?!
In an OS agnostic way, you could allocate and fill heap memory obtained with malloc(3) (so do some computation with that zone), or in C++ with operator new. Be sure to test against failure of malloc. And increase the size of your zone progressively.
If your goal is ability to stress CPU and RAM utilization (and not necessarily writing a program), try HeavyLoad which is free and does just that http://www.jam-software.com/heavyload/
I wrote a test program for this using multithreading and Mersenne Primes as the algorithm for stress testing
The code first determines the number of cores on the machine (WINDOWS only guys, sorry!!)
NtQuerySystemInformation(SystemBasicInformation, &BasicInformation, sizeof(SYSTEM_BASIC_INFORMATION), NULL);
It then runs a test method to spawn a thread for each core
// make sure we've got at least as many threads as cores
for (int i = 0; i < this->BasicInformation.NumberOfProcessors; i++)
{
threads.push_back(thread(&CpuBenchmark::MersennePrimes, CpuBenchmark()));
}
running our load
BOOL CpuBenchmark::IsPrime(ULONG64 n) // function determines if the number n is prime.
{
for (ULONG64 i = 2; i * i < n; i++)
if (n % i == 0)
return false;
return true;
}
ULONG64 CpuBenchmark::Power2(ULONG64 n) //function returns 2 raised to power of n
{
ULONG64 square = 1;
for (ULONG64 i = 0; i < n; i++)
{
square *= 2;
}
return square;
}
VOID CpuBenchmark::MersennePrimes()
{
ULONG64 i;
ULONG64 n;
for (n = 2; n <= 61; n++)
{
if (IsPrime(n) == 1)
{
i = Power2(n) - 1;
if (IsPrime(i) == 1) {
// dont care just want to stress the CPU
}
}
}
}
and waits for all threads to complete
// wait for them all to finish
for (auto& th : threads)
th.join();
Full article and source code on my blog site
http://malcolmswaine.com/c-cpu-stress-test-algorithm-mersenne-primes/
I have a procedure that calculates the outcome of a game by random sample; it is passed a number of iterations, runs a loop of that size storing the outcomes in a local variable (subHits), then after the loop is done, adds the totals from the local variables into a class level member variable (m_Hits), to wit:
void Game::LogOutcomes(long periodSize) {
int subHits[11];
for (int i = 0; i < 11; ++i) {
subHits[i] = 0;
}
for (int iters = 0; iters < periodSize; ++iters) {
// ... snipped out code calculating rankIndex by random sample.
++subHits[rankIndex];
}
for (int i = 0; i < 11; ++i) {
m_Hits[i] += subHits[i];
}
}
.. of course, it uses a local variable as temporary storage for purposes of running the procedure in parallel, which I invoke with:
dispatch_queue_t globalQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply(m_BatchSize / m_PeriodSize, globalQ, ^(size_t periodCount) {
LogBonusWager(m_PeriodSize);
});
.. and it seems to work perfectly (all results are sufficiently close to statistically expected value). I can't help but think there's something wrong, because nowhere am I specifically 'locking' the class level variable when updating it with the contents of the local variable, and that I'm getting the right results through sheer good fortune.
Is there something I'm missing?
You're getting lucky. You should either have a dedicated (serial) queue for updating the shared state, or use OSAtomicAddSize to add to it. Without this you'll be losing updates occasionally.
I am developing a simple game in c++, a chase-the-dot style one, where you must click a drawn circle on the display and then it jumps to another random location with every click, but I want to make the game end after 60 seconds or so, write the score to a text file and then upon launching the program read from the text file and store the information into an array and somehow rearrange it to create a high score table.
I think I can figure out the high score and mouse clicking in a certain area myself, but I am completely stuck with creating a possible timer.
Any help appreciated, cheers!
In C++11 there is easy access to timers. For example:
#include <chrono>
#include <iostream>
int main()
{
std::cout << "begin\n";
std::chrono::steady_clock::time_point tend = std::chrono::steady_clock::now()
+ std::chrono::minutes(1);
while (std::chrono::steady_clock::now() < tend)
{
// do your game
}
std::cout << "end\n";
}
Your platform may or may not support <chrono> yet. There is a boost implementation of <chrono>.
Without reference to a particular framework or even the OS this is unanswerable.
In SDL there is SDL_GetTicks() which suits the purpose.
On linux, there is the general purpose clock_gettime or gettimeofday that should work pretty much everywhere (but beware of the details).
Win32 API has several function calls related to this, including Timer callback mechanisms, such as GetTickCount, Timers etc. (article)
Using timers is usually closely related to the meme of 'idle' processing. So you'd want to search for that topic as well (and this is where the message pump comes in, because the message pump decides when (e.g.) WM_IDLE messages get sent; Gtk has a similar concept of Idle hooks and I reckon pretty much every UI framework does)
Usually GUI program has so called "message pump" loop. Check of that timer should be a part of your loop:
while(running)
{
if( current_time() > end_time )
{
// time is over ...
break;
}
if( next_ui_message(msg) )
dispatch(msg);
}
Try this one out:
//Creating Digital Watch in C++
#include<iostream>
#include<Windows.h>
using namespace std;
struct time{
int hr,min,sec;
};
int main()
{
time a;
a.hr = 0;
a.min = 0;
a.sec = 0;
for(int i = 0; i<24; i++)
{
if(a.hr == 23)
{
a.hr = 0;
}
for(int j = 0; j<60; j++)
{
if(a.min == 59)
{
a.min = 0;
}
for(int k = 0; k<60; k++)
{
if(a.sec == 59)
{
a.sec = 0;
}
cout<<a.hr<<" : "<<a.min<<" : "<<a.sec<<endl;
a.sec++;
Sleep(1000);
system("Cls");
}
a.min++;
}
a.hr++;
}
}
See the details at: http://www.programmingtunes.com/creating-timer-c/#sthash.j9WLtng2.dpuf