CodeWarrior Get variable value from a event.c - c

to enter context I'm doing this:
Drive a stepper motor through the variation of pulse frequency input to a Driver (A4988) (It is not necessary to know the functioning of this for this question). Now and got varying the frequency of the pulses (They change the engine speed). You need to know that for the motor shaft 1 full turn have to get 200 pulses (The engine is 1.8 ° degrees per step).
I got the engine and make him a full turn in 1 second.
Period = 0.005s
To program this I am using the component: TimerUnit_LDD.
With a frequency of 163840 Hz count
In the case of the whole turn 1 to get that frequently use this function.
---- main.c
TU1_Enable (TU1_DeviceData);
 TU1_SetPeriodTicks (TU1_DeviceData, 410);
  
The parameter 410 is compared to the period I want, as is sending pulses programmed by changing the value of a pin taken into account both the high and the low pulse, like this:
----- Events.c
TU1_OnCounterRestart void (* UserDataPtr LDD_TUserData)
{
 Step1_NegVal ();
 }
The period for serious formulates 819.2, having in mind the above serious approximates 409.6 and 410 (seen in a oscilloscope frequency is 200 Hz (ok).
Already entered in context the problem is this:
---- main.c
TU1_Enable (TU1_DeviceData); // Enable the counter
TU1_SetPeriodTicks (TU1_DeviceData, 410); // Setting the desired period
for (;;) {
           TU1_Enable (TU1_DeviceData);
           WAIT1_Waitms (1000); // Rotation time
 TU1_Enable (TU1_DeviceData); // Disable the counter
}
With this code is what I try to check that the frequency calculation was correct and that in one second would 1 turn. But what happens is that it gives the rotation but is offset a little more. I guess this goes through the runtime required for each line of code.
What I want to know is, how could obtain the numerical value of a variable in an event? how could I do something like this.
---- main.c
TU1_Enable (TU1_DeviceData); // Initialize the counter
TU1_SetPeriodTicks (TU1_DeviceData, 410); // Setting the desired period
for (;;) {
for (;;) {
      if (GetValue (x) == 200) break; // GetValue (x) This function is what I want to achieve
}
WAIT1_Waitms (1000);
}
----- Events.c
TU1_OnCounterRestart void (* UserDataPtr LDD_TUserData)
{
 Step1_NegVal ();
x = x + 1;
 }
GetValue (x) this function would obtain the value of x which is in Events.c and define a number of pulses to control espefico.
Take a variable and is affected by the counter, and that this gets to 200 (for 1 turn in 1 second).
This would have the certainty that menera be sent alone and lonely, neither more nor less, only 200 pulses.
I require this as specific as I am desarrolando the program for a CNC machine and is too importanto precision is the highest.
I hope you understand and I speak Spanish and this was translated by Chrome
Programmed in C language,
Freescale KL25Z,
CodeWarrior,
OPEN_SDA,

I managed to implement something but I think it may be easier to get
-----(main.c)
extern int count;//called external variable
int main(void){
PE_low_level_init();
TU1_Enable(TU1_DeviceData);
TU1_SetPeriodTicks(TU1_DeviceData,410);//T=0.005 sec
for(;;){
Term1_Cls();// Clear Console
WAIT1_Waitms(1000);
Term1_MoveTo(0,0);// Set 0,0 in Console
for(;;){
TU1_Enable(TU1_DeviceData);
Term1_SendNum(count);
Term1_CRLF();
if (count>400){//amount of high and low pulse counting
count=0;
TU1_Disable(TU1_DeviceData);
break;
}
}
WAIT1_Waitms(1000);
Dir1_NegVal();
}
----(Events.c)
int count;
void TU1_OnCounterRestart(LDD_TUserData *UserDataPtr)
{
Step1_NegVal();
count=count+1; //counter
}

Related

FFT with dsPIC33E returns no frequency

I'm working with a dsPIC33EP128GP502 and try to run a FFT to measure the dominant frequency on the input. The compiler shows no errors and the ADC itself seems to work... (for single values)
I expect as result some frequency value between 0 Hz and ~96 kHz in the variable peakFrequency. With a noise signal (or no signal at all) the value should be more or less random. With an external applied single tone signal I expect to measure the input frequency +/- ~100 Hz. Sadly, my frequency output is always 0.
The test signals are generated by external signal generators and the ADC works fine if I want to measure single values!
The FFT has to run on the DSP-core of the dsPIC33E due to some performance needs.
Has anyone any experience with the dsPIC33E and an idea were my mistake is?
ADC: TAD -> 629.3 ns, Conversion Trigger -> Clearing sample bit ends sampling and starts conversion, Output Format -> Fractional result, signed, Auto Sampling -> enabled
#include "mcc_generated_files/mcc.h"
#include <xc.h>
#include <dsp.h>
#define FFT_BLOCK_LENGTH 1024
#define LOG2_BLOCK_LENGTH 10
#define AUDIO_FS 192042
int16_t peakFrequencyBin;
uint16_t ix_MicADCbuff;
uint16_t peakFrequency;
fractional fftMaxValue;
fractcomplex twiddleFactors[FFT_BLOCK_LENGTH/2] __attribute__ ((space(xmemory)));
fractcomplex sigCmpx[FFT_BLOCK_LENGTH] __attribute__ ((space(ymemory), aligned(FFT_BLOCK_LENGTH * 2 *2)));
bool timeGetAdcSample = false;
void My_ADC_IRS(void)
{
timeGetAdcSample = true;
}
void readOutput(void)//Sample output
{
for(ix_MicADCbuff=0;ix_MicADCbuff<FFT_BLOCK_LENGTH;ix_MicADCbuff++)
{
ADC1_ChannelSelect(mix_output);
ADC1_SoftwareTriggerEnable();
while(!timeGetAdcSample); //wait for TMR1 interrupt (5.2072 us)
timeGetAdcSample = false;
ADC1_SoftwareTriggerDisable();
while(!ADC1_IsConversionComplete(mix_output));
sigCmpx[ix_MicADCbuff].real = ADC1_Channel0ConversionResultGet();
sigCmpx[ix_MicADCbuff].imag = 0;
}
}
void signalFreq(void)//Detect the dominant frequency
{
readOutput();
FFTComplexIP(LOG2_BLOCK_LENGTH, &sigCmpx[0], &twiddleFactors[0], COEFFS_IN_DATA);/
BitReverseComplex(LOG2_BLOCK_LENGTH, &sigCmpx[0]);
SquareMagnitudeCplx(FFT_BLOCK_LENGTH, &sigCmpx[0], &sigCmpx[0].real);
VectorMax(FFT_BLOCK_LENGTH/2, &sigCmpx[0].real, &peakFrequencyBin);
peakFrequency = peakFrequencyBin*(AUDIO_FS/FFT_BLOCK_LENGTH);
}
int main(void)
{
SYSTEM_Initialize();
TwidFactorInit(LOG2_BLOCK_LENGTH, &twiddleFactors[0], 0);
TMR1_SetInterruptHandler(My_ADC_IRS);
TMR1_Start();
while (1)
{
signalFreq();
UART1_32_Write((uint32_T)peakFrequency); // output via UART
}
return 1;
}
Perhaps anyone can figure out the error/problem in my code!

Servo Motor not moving properly in Proteus

I'm trying to control a Servo Motor with a PIC18f4550, but before buying one, I'm trying to simulate it on Proteus ISIS, but I'm getting some inconsistencies when setting the angle.
I've tried using a 20ms period and 1ms, 1.167ms, 1.333ms, 1.5ms, 1.667ms or 1.833ms duty cycle and it results in a -69.8° Angle on Proteus MOTOR-PWMSERVO, but using a 2ms duty cycle results in a full 90.0° Angle
#define CONTROL PORTCbits.RC0
#define BUTTON PORTCbits.RC1
const Ang_Neg90 = 1.0;
const Ang_Neg60 = 1.167;
const Ang_Neg30 = 1.333;
const Ang_0 = 1.5;
const Ang_30 = 1.667;
const Ang_60 = 1.833;
const Ang_90 = 2.00;
// ------------------------------------------------- //
void ServoPosition (unsigned float Angle) {
CONTROL = 1;
Delay_ms(Angle);
CONTROL = 0;
Delay_ms(20 - Angle);
}
void main(){
while(1){
ServoPosition(Ang_0);
if (BUTTON == 1){
break;
while(1){
ServoPosition(Ang_90);
}
}
}
}
I want my program to be able to go from 0 degrees to 90 degrees, but all I'm getting is -69.8 to 90. Any ideas of what I'm getting wrong?
It's hard to tell without seeing your entire setup, so here's a list of things it might be.
Check Simulated Servo Settings
Make sure it's set to the default values.
Measure your PWM signal with the Oscilloscope Tool
The Hobby Servo Motor sample shows how to use the oscilloscope tool. Hook the oscilloscope up to your pic18f4550 PWM output and measure it to make sure the duty cycle is correct. You're having problems at the low end (trying to reach 1ms) so I suspect the oscilloscope will show your duty cycle is too long.
If you find that your duty cycles are too long, you can try:
Subtracting a fudge value to deal with whatever falloff time is present in the simulation. You might have to use different values when you run on real hardware.
Using a dedicated PWM module on the pic18f4550. This is probably the best solution since you can just set the PWM registers (assuming this is how it works... I haven't looked closely at the manual) and then let it control the duty cycle for you.
Check Voltages
The battery in the Hobby Server was 6V, but 5V also seemed to work. Lower than that and it began to act strange.
The type of your constant is wrong:
const Ang_Neg90 = 1.0;
This is a constant of type int with the value 1.
I guess you mean:
const float Ang_Neg90 = 1.0;
But anyway:
If you use the Microchip built in delay function the argument should be of the type unsigned long and you are working with unsigned float.
Try to define your delay times in us (integer not float values!) and use the function __delay_us(...). And be sure to define _XTAL_FREQ correctly.
And as already mentioned: Please remember there don't exist a type unsigned float. float is always unsigned.

Best way to read from a sensor that doesn't have interrupt pin and requires some time before the measurement is ready

I'm trying to interface a pressure sensor (MS5803-14BA) with my board (NUCLEO-STM32L073RZ).
According to the datasheet (page 3), the pressure sensor requires some milliseconds before the measurement is ready to be read. For my project, I would be interested in the highest resolution that requires around 10 ms for the conversion of the raw data.
Unfortunately, this pressure sensor doesn't have any interrupt pin that can be exploited to see when the measurement is ready, and therefore I temporarily solved the problem putting a delay after the request of new data.
I don't like my current solution, since in those 10 ms I could put the mcu working on something else (I have several other sensors attached to my board), but without any interrupt pin, I'm not sure about what is the best way to solve this problem.
Another solution came into my mind: Using a timer that triggers every say 20 ms and performs the following operations:
1.a Read the current value stored in the registers (discarding the first value)
1.b Ask for a new value
In this way, at the next iteration I would just need to read the value requested at the end of the previous iteration.
What I don't like is that my measurement would be always 20 ms old. Until the delay remains 20 ms, it should be still fine, but if I need to reduce the rate, the "age" of the reading with my solution would increase.
Do you have any other idea about how to deal with this?
Thank you.
Note: Please let me know if you would need to see my current implementation.
How to do high-resolution, timestamp-based, non-blocking, single-threaded cooperative multi-tasking
This isn't a "how to read a sensor" problem, this is a "how to do non-blocking cooperative multi-tasking" problem. Assuming you are running bare-metal (no operating system, such as FreeRTOS), you have two good options.
First, the datasheet shows you need to wait up to 9.04 ms, or 9040 us.
Now, here are your cooperative multi-tasking options:
Send a command to tell the device to do an ADC conversion (ie: to take an analog measurement), then configure a hardware timer to interrupt you exactly 9040 us later. In your ISR you then can either set a flag to tell your main loop to send a read command to read the result, OR you can just send the read command right inside the ISR.
Use non-blocking time-stamp-based cooperative multi-tasking in your main loop. This will likely require a basic state machine. Send the conversion command, then move on, doing other things. When your time stamp indicates it's been long enough, send the read command to read the converted result from the sensor.
Number 1 above is my preferred approach for time-critical tasks. This isn't time-critical, however, and a little jitter won't make any difference, so Number 2 above is my preferred approach for general, bare-metal cooperative multi-tasking, so let's do that.
Here's a sample program to demonstrate the principle of time-stamp-based bare-metal cooperative multi-tasking for your specific case where you need to:
request a data sample (start ADC conversion in your external sensor)
wait 9040 us for the conversion to complete
read in the data sample from your external sensor (now that the ADC conversion is complete)
Code:
enum sensorState_t
{
SENSOR_START_CONVERSION,
SENSOR_WAIT,
SENSOR_GET_CONVERSION
}
int main(void)
{
doSetupStuff();
configureHardwareTimer(); // required for getMicros() to work
while (1)
{
//
// COOPERATIVE TASK #1
// Read the under-water pressure sensor as fast as permitted by the datasheet
//
static sensorState_t sensorState = SENSOR_START_CONVERSION; // initialize state machine
static uint32_t task1_tStart; // us; start time
static uint32_t sensorVal; // the sensor value you are trying to obtain
static bool newSensorVal = false; // set to true whenever a new value arrives
switch (sensorState)
{
case SENSOR_START_CONVERSION:
{
startConversion(); // send command to sensor to start ADC conversion
task1_tStart = getMicros(); // get a microsecond time stamp
sensorState = SENSOR_WAIT; // next state
break;
}
case SENSOR_WAIT:
{
const uint32_t DESIRED_WAIT_TIME = 9040; // us
uint32_t tNow = getMicros();
if (tNow - task1_tStart >= DESIRED_WAIT_TIME)
{
sensorState = SENSOR_GET_CONVERSION; // next state
}
break;
}
case SENSOR_GET_CONVERSION:
{
sensorVal = readConvertedResult(); // send command to read value from the sensor
newSensorVal = true;
sensorState = SENSOR_START_CONVERSION; // next state
break;
}
}
//
// COOPERATIVE TASK #2
// use the under-water pressure sensor data right when it comes in (this will be an event-based task
// whose running frequency depends on the rate of new data coming in, for example)
//
if (newSensorVal == true)
{
newSensorVal = false; // reset this flag
// use the sensorVal data here now for whatever you need it for
}
//
// COOPERATIVE TASK #3
//
//
// COOPERATIVE TASK #4
//
// etc etc
} // end of while (1)
} // end of main
For another really simple timestamp-based multi-tasking example see Arduino's "Blink Without Delay" example here.
General time-stamp-based bare-metal cooperative multi-tasking architecture notes:
Depending on how you do it all, in the end, you basically end up with this type of code layout, which simply runs each task at fixed time intervals. Each task should be non-blocking to ensure it does not conflict with the run intervals of the other tasks. Non-blocking on bare metal means simply "do not use clock-wasting delays, busy-loops, or other types of polling, repeating, counting, or busy delays!". (This is opposed to "blocking" on an operating-system-based (OS-based) system, which means "giving the clock back to the scheduler to let it run another thread while this task 'sleeps'." Remember: bare metal means no operating system!). Instead, if something isn't quite ready to run yet, simply save your state via a state machine, exit this task's code (this is the "cooperative" part, as your task must voluntarily give up the processor by returning), and let another task run!
Here's the basic architecture, showing a simple timestamp-based way to get 3 Tasks to run at independent, fixed frequencies withOUT relying on any interrupts, and with minimal jitter, due to the thorough and methodical approach I take to check the timestamps and update the start time at each run time.
1st, the definition for the main() function and main loop:
int main(void)
{
doSetupStuff();
configureHardwareTimer();
while (1)
{
doTask1();
doTask2();
doTask3();
}
}
2nd, the definitions for the doTask() functions:
// Task 1: Let's run this one at 100 Hz (every 10ms)
void doTask1(void)
{
const uint32_t DT_DESIRED_US = 10000; // 10000us = 10ms, or 100Hz run freq
static uint32_t t_start_us = getMicros();
uint32_t t_now_us = getMicros();
uint32_t dt_us = t_now_us - t_start_us;
// See if it's time to run this Task
if (dt_us >= DT_DESIRED_US)
{
// 1. Add DT_DESIRED_US to t_start_us rather than setting t_start_us to t_now_us (which many
// people do) in order to ***avoid introducing artificial jitter into the timing!***
t_start_us += DT_DESIRED_US;
// 2. Handle edge case where it's already time to run again because just completing one of the main
// "scheduler" loops in the main() function takes longer than DT_DESIRED_US; in other words, here
// we are seeing that t_start_us is lagging too far behind (more than one DT_DESIRED_US time width
// from t_now_us), so we are "fast-forwarding" t_start_us up to the point where it is exactly
// 1 DT_DESIRED_US time width back now, thereby causing this task to instantly run again the
// next time it is called (trying as hard as we can to run at the specified frequency) while
// at the same time protecting t_start_us from lagging farther and farther behind, as that would
// eventually cause buggy and incorrect behavior when the (unsigned) timestamps start to roll over
// back to zero.
dt_us = t_now_us - t_start_us; // calculate new time delta with newly-updated t_start_us
if (dt_us >= DT_DESIRED_US)
{
t_start_us = t_now_us - DT_DESIRED_US;
}
// PERFORM THIS TASK'S OPERATIONS HERE!
}
}
// Task 2: Let's run this one at 1000 Hz (every 1ms)
void doTask2(void)
{
const uint32_t DT_DESIRED_US = 1000; // 1000us = 1ms, or 1000Hz run freq
static uint32_t t_start_us = getMicros();
uint32_t t_now_us = getMicros();
uint32_t dt_us = t_now_us - t_start_us;
// See if it's time to run this Task
if (dt_us >= DT_DESIRED_US)
{
t_start_us += DT_DESIRED_US;
dt_us = t_now_us - t_start_us; // calculate new time delta with newly-updated t_start_us
if (dt_us >= DT_DESIRED_US)
{
t_start_us = t_now_us - DT_DESIRED_US;
}
// PERFORM THIS TASK'S OPERATIONS HERE!
}
}
// Task 3: Let's run this one at 10 Hz (every 100ms)
void doTask3(void)
{
const uint32_t DT_DESIRED_US = 100000; // 100000us = 100ms, or 10Hz run freq
static uint32_t t_start_us = getMicros();
uint32_t t_now_us = getMicros();
uint32_t dt_us = t_now_us - t_start_us;
// See if it's time to run this Task
if (dt_us >= DT_DESIRED_US)
{
t_start_us += DT_DESIRED_US;
dt_us = t_now_us - t_start_us; // calculate new time delta with newly-updated t_start_us
if (dt_us >= DT_DESIRED_US)
{
t_start_us = t_now_us - DT_DESIRED_US;
}
// PERFORM THIS TASK'S OPERATIONS HERE!
}
}
The code above works perfectly but as you can see is pretty redundant and a bit irritating to set up new tasks. This job can be a bit more automated and much much easier to do by simply defining a macro, CREATE_TASK_TIMER(), as follows, to do all of the redundant timing stuff and timestamp variable creation for us:
/// #brief A function-like macro to get a certain set of events to run at a desired, fixed
/// interval period or frequency.
/// #details This is a timestamp-based time polling technique frequently used in bare-metal
/// programming as a basic means of achieving cooperative multi-tasking. Note
/// that getting the timing details right is difficult, hence one reason this macro
/// is so useful. The other reason is that this maro significantly reduces the number of
/// lines of code you need to write to introduce a new timestamp-based cooperative
/// task. The technique used herein achieves a perfect desired period (or freq)
/// on average, as it centers the jitter inherent in any polling technique around
/// the desired time delta set-point, rather than always lagging as many other
/// approaches do.
///
/// USAGE EX:
/// ```
/// // Create a task timer to run at 500 Hz (every 2000 us, or 2 ms; 1/0.002 sec = 500 Hz)
/// const uint32_t PERIOD_US = 2000; // 2000 us pd --> 500 Hz freq
/// bool time_to_run;
/// CREATE_TASK_TIMER(PERIOD_US, time_to_run);
/// if (time_to_run)
/// {
/// run_task_2();
/// }
/// ```
///
/// Source: Gabriel Staples
/// https://stackoverflow.com/questions/50028821/best-way-to-read-from-a-sensors-that-doesnt-have-interrupt-pin-and-require-some/50032992#50032992
/// #param[in] dt_desired_us The desired delta time period, in microseconds; note: pd = 1/freq;
/// the type must be `uint32_t`
/// #param[out] time_to_run A `bool` whose scope will enter *into* the brace-based scope block
/// below; used as an *output* flag to the caller: this variable will
/// be set to true if it is time to run your code, according to the
/// timestamps, and will be set to false otherwise
/// #return NA--this is not a true function
#define CREATE_TASK_TIMER(dt_desired_us, time_to_run) \
{ /* Use scoping braces to allow multiple calls of this macro all in one outer scope while */ \
/* allowing each variable created below to be treated as unique to its own scope */ \
time_to_run = false; \
\
/* set the desired run pd / freq */ \
const uint32_t DT_DESIRED_US = dt_desired_us; \
static uint32_t t_start_us = getMicros(); \
uint32_t t_now_us = getMicros(); \
uint32_t dt_us = t_now_us - t_start_us; \
\
/* See if it's time to run this Task */ \
if (dt_us >= DT_DESIRED_US) \
{ \
/* 1. Add DT_DESIRED_US to t_start_us rather than setting t_start_us to t_now_us (which many */ \
/* people do) in order to ***avoid introducing artificial jitter into the timing!*** */ \
t_start_us += DT_DESIRED_US; \
/* 2. Handle edge case where it's already time to run again because just completing one of the main */ \
/* "scheduler" loops in the main() function takes longer than DT_DESIRED_US; in other words, here */ \
/* we are seeing that t_start_us is lagging too far behind (more than one DT_DESIRED_US time width */ \
/* from t_now_us), so we are "fast-forwarding" t_start_us up to the point where it is exactly */ \
/* 1 DT_DESIRED_US time width back now, thereby causing this task to instantly run again the */ \
/* next time it is called (trying as hard as we can to run at the specified frequency) while */ \
/* at the same time protecting t_start_us from lagging farther and farther behind, as that would */ \
/* eventually cause buggy and incorrect behavior when the (unsigned) timestamps start to roll over */ \
/* back to zero. */ \
dt_us = t_now_us - t_start_us; /* calculate new time delta with newly-updated t_start_us */ \
if (dt_us >= DT_DESIRED_US) \
{ \
t_start_us = t_now_us - DT_DESIRED_US; \
} \
\
time_to_run = true; \
} \
}
Now, there are multiple ways to use it, but for the sake of this demo, in order to keep the really clean main() loop code which looks like this:
int main(void)
{
doSetupStuff();
configureHardwareTimer();
while (1)
{
doTask1();
doTask2();
doTask3();
}
}
Let's use the CREATE_TASK_TIMER() macro like this. As you can see, the code is now much cleaner and easier to set up a new task. This is my preferred approach, because it creates the really clean main loop shown just above, with just the various doTask() calls, which are also easy to write and maintain:
// Task 1: Let's run this one at 100 Hz (every 10ms, or 10000us)
void doTask1(void)
{
bool time_to_run;
const uint32_t DT_DESIRED_US = 10000; // 10000us = 10ms, or 100Hz run freq
CREATE_TASK_TIMER(DT_DESIRED_US, time_to_run);
if (time_to_run)
{
// PERFORM THIS TASK'S OPERATIONS HERE!
}
}
// Task 2: Let's run this one at 1000 Hz (every 1ms)
void doTask2(void)
{
bool time_to_run;
const uint32_t DT_DESIRED_US = 1000; // 1000us = 1ms, or 1000Hz run freq
CREATE_TASK_TIMER(DT_DESIRED_US, time_to_run);
if (time_to_run)
{
// PERFORM THIS TASK'S OPERATIONS HERE!
}
}
// Task 3: Let's run this one at 10 Hz (every 100ms)
void doTask3(void)
{
bool time_to_run;
const uint32_t DT_DESIRED_US = 100000; // 100000us = 100ms, or 10Hz run freq
CREATE_TASK_TIMER(DT_DESIRED_US, time_to_run);
if (time_to_run)
{
// PERFORM THIS TASK'S OPERATIONS HERE!
}
}
Alternatively, however, you could structure the code more like this, which works equally as well and produces the same effect, just in a slightly different way:
#include <stdbool.h>
#include <stdint.h>
#define TASK1_PD_US (10000) // 10ms pd, or 100 Hz run freq
#define TASK2_PD_US (1000) // 1ms pd, or 1000 Hz run freq
#define TASK3_PD_US (100000) // 100ms pd, or 10 Hz run freq
// Task 1: Let's run this one at 100 Hz (every 10ms, or 10000us)
void doTask1(void)
{
// PERFORM THIS TASK'S OPERATIONS HERE!
}
// Task 2: Let's run this one at 1000 Hz (every 1ms)
void doTask2(void)
{
// PERFORM THIS TASK'S OPERATIONS HERE!
}
// Task 3: Let's run this one at 10 Hz (every 100ms)
void doTask3(void)
{
// PERFORM THIS TASK'S OPERATIONS HERE!
}
int main(void)
{
doSetupStuff();
configureHardwareTimer();
while (1)
{
bool time_to_run;
CREATE_TASK_TIMER(TASK1_PD_US, time_to_run);
if (time_to_run)
{
doTask1();
}
CREATE_TASK_TIMER(TASK2_PD_US, time_to_run);
if (time_to_run)
{
doTask2();
}
CREATE_TASK_TIMER(TASK3_PD_US, time_to_run);
if (time_to_run)
{
doTask3();
}
}
}
Part of the art (and fun!) of embedded bare-metal microcontroller programming is the skill and ingenuity involved in deciding exactly how you want to interleave each task and get them to run together, all as though they were running in parallel. Use one of the above formats as a starting point, and adapt to your particular circumstances. Message-passing can be added between tasks or between tasks and interrupts, tasks and a user, etc, as desired, and as required for your particular application.
Here's an example of how to configure a timer for use as a timestamp-generator on an STM32F2 microcontroller.
This shows functions for configureHardwareTimer() and getMicros(), used above:
// Timer handle to be used for Timer 2 below
TIM_HandleTypeDef TimHandle;
// Configure Timer 2 to be used as a free-running 32-bit hardware timer for general-purpose use as a 1-us-resolution
// timestamp source
void configureHardwareTimer()
{
// Timer clock must be enabled before you can configure it
__HAL_RCC_TIM2_CLK_ENABLE();
// Calculate prescaler
// Here are some references to show how this is done:
// 1) "STM32Cube_FW_F2_V1.7.0/Projects/STM32F207ZG-Nucleo/Examples/TIM/TIM_OnePulse/Src/main.c" shows the
// following (slightly modified) equation on line 95: `Prescaler = (TIMxCLK/TIMx_counter_clock) - 1`
// 2) "STM32F20x and STM32F21x Reference Manual" states the following on pg 419: "14.4.11 TIMx prescaler (TIMx_PSC)"
// "The counter clock frequency CK_CNT is equal to fCK_PSC / (PSC[15:0] + 1)"
// This means that TIMx_counter_clock_freq = TIMxCLK/(prescaler + 1). Now, solve for prescaler and you
// get the exact same equation as above: `prescaler = TIMxCLK/TIMx_counter_clock_freq - 1`
// Calculating TIMxCLK:
// - We must divide SystemCoreClock (returned by HAL_RCC_GetHCLKFreq()) by 2 because TIM2 uses clock APB1
// as its clock source, and on my board this is configured to be 1/2 of the SystemCoreClock.
// - Note: To know which clock source each peripheral and timer uses, you can look at
// "Table 25. Peripheral current consumption" in the datasheet, p86-88.
const uint32_t DESIRED_TIMER_FREQ = 1e6; // 1 MHz clock freq --> 1 us pd per tick, which is what I want
uint32_t Tim2Clk = HAL_RCC_GetHCLKFreq() / 2;
uint32_t prescaler = Tim2Clk / DESIRED_TIMER_FREQ - 1; // Don't forget the minus 1!
// Configure timer
// TIM2 is a 32-bit timer; See datasheet "Table 4. Timer feature comparison", p30-31
TimHandle.Instance = TIM2;
TimHandle.Init.Period = 0xFFFFFFFF; // Set pd to max possible for a 32-bit timer
TimHandle.Init.Prescaler = prescaler;
TimHandle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP;
TimHandle.Init.RepetitionCounter = 0; // NA (has no significance) for this timer
// Initialize the timer
if (HAL_TIM_Base_Init(&TimHandle) != HAL_OK)
{
// handle error condition
}
// Start the timer
if (HAL_TIM_Base_Start(&TimHandle) != HAL_OK)
{
// handle error condition
}
}
// Get the 1 us count value on Timer 2.
// This timer will be used for general purpose hardware timing that does NOT rely on interrupts.
// Therefore, the counter will continue to increment even with interrupts disabled.
// The count value increments every 1 microsecond.
// Since it is a 32-bit counter it overflows every 2^32 counts, which means the highest value it can
// store is 2^32 - 1 = 4294967295. Overflows occur every 2^32 counts / 1 count/us / 1e6us/sec
// = ~4294.97 sec = ~71.6 min.
uint32_t getMicros()
{
return __HAL_TIM_GET_COUNTER(&TimHandle);
}
References:
https://www.arduino.cc/en/tutorial/BlinkWithoutDelay
Doxygen: What's the right way to reference a parameter in Doxygen?
Enum-based error codes for error handling: Error handling in C code
Other architectural styles in C, such as "object-based" C via opaque pointers: Opaque C structs: various ways to declare them
See also:
A full, runnable Arduino example with an even better version of my CREATE_TASK_TIMER() macro from above:
My answer for C and C++, including microcontrollers and Arduino (or any other system): Full coulomb counter example demonstrating the above concept with timestamp-based, single-threaded, cooperative multi-tasking
First of all thank you for your suggestions. I tried to analyze every single possible solution you proposed.
The solution proposed by Peter seemed very interesting but I have to say that, after having gone through the datasheet several times, I don't believe that is feasible. My consideration is based on the following facts.
Using a scope I see that the acknowledge is received right after sending the command for doing conversion. See following image concerning the temperature conversion:
It seems quite clear to me the acknowledge bit right after the command. After that the SDA line (yellow) goes high, therefore I don't see how it is possible that I can exploit that for detecting when the conversion is ready.
Concerning the solution when using SPI, yes, the SDO remains low during the conversion, but I cannot use it: I need to stick with I2C. Furthermore, I have other sensors attached to that SPI bus and I agree with what Gabriel Staples says.
After my consideration I went for the solution proposed by Gabriel Staples (considering that, in order to read pressure value, I also need to read and convert temperature).
My current solution is based on a state machine with 6 states. In my solution, I distinguish between the wait time for the pressure conversion and the wait time for the temperature conversion with the idea the I could try to see how much the pressure reading degrades if I use a less precise temperature reading.
Here is my current solution. The following function is called inside the main while:
void MS5803_update()
{
static uint32_t tStart; // us; start time
switch (sensor_state)
{
case MS5803_REQUEST_TEMPERATURE:
{
MS5803_send_command(MS5803_CMD_ADC_CONV + TEMPERATURE + baro.resolution);
tStart = HAL_GetTick();
sensor_state = MS5803_WAIT_RAW_TEMPERATURE;
break;
}
case MS5803_WAIT_RAW_TEMPERATURE:
{
uint32_t tNow = HAL_GetTick();
if (tNow - tStart >= conversion_time)
{
sensor_state = MS5803_CONVERTING_TEMPERATURE;
}
break;
}
case MS5803_CONVERTING_TEMPERATURE:
{
MS5803_send_command(MS5803_CMD_ADC_READ);
uint8_t raw_value[3]; // Read 24 bit
MS5803_read_value(raw_value,3);
temperature_raw = ((uint32_t)raw_value[0] << 16) + ((uint32_t)raw_value[1] << 8) + raw_value[2];
sensor_state = MS5803_REQUEST_PRESSURE;
break;
}
case MS5803_REQUEST_PRESSURE:
{
MS5803_send_command(MS5803_CMD_ADC_CONV + PRESSURE + baro.resolution);
tStart = HAL_GetTick();
sensor_state = MS5803_WAIT_RAW_PRESSURE;
break;
}
case MS5803_WAIT_RAW_PRESSURE:
{
uint32_t tNow = HAL_GetTick();
if (tNow - tStart >= conversion_time)
{
sensor_state = MS5803_CONVERTING_PRESSURE;
}
break;
}
case MS5803_CONVERTING_PRESSURE:
{
MS5803_send_command(MS5803_CMD_ADC_READ);
uint8_t raw_value[3]; // Read 24 bit
MS5803_read_value(raw_value,3);
pressure_raw = ((uint32_t)raw_value[0] << 16) + ((uint32_t)raw_value[1] << 8) + raw_value[2];
// Now I have both temperature and pressure raw and I can convert them
MS5803_updateMeasurements();
// Reset the state machine to perform a new measurement
sensor_state = MS5803_REQUEST_TEMPERATURE;
break;
}
}
}
I don't pretend that my solution is better. I just post it in order to have an opinion from you guys. Note: I'm still working on it. Therefore I cannot guarantee is bug-free!
For PeterJ_01: I could agree that this is not strictly a teaching portal, but I believe that everybody around here asks questions to learn something new or to improve theirselves. Therefore, if you believe that the solution using the ack is better, it would be great if you could show us a draft of your idea. For me it would be something new to learn.
Any further comment is appreciated.

Average from error prone measurement samples without buffering

I got a µC which measures temperature with of a sensor with an ADC. Due to various circumstances it can happen, that the reading is 0 (-30°C) or a impossible large Value (500-1500°C). I can't fix the reasons why these readings are so bad (time critical ISRs and sometimes a bad wiring) so I have to fix it with a clever piece of code.
I've come up with this (code gets called OVERSAMPLENR-times in a ISR):
#define OVERSAMPLENR 16 //read value 16 times
#define TEMP_VALID_CHANGE 0.15 //15% change in reading is possible
//float raw_tem_bed_value = <sum of all readings>;
//ADC = <AVR ADC reading macro>;
if(temp_count > 1) { //temp_count = amount of samples read, gets increased elsewhere
float avgRaw = raw_temp_bed_value / temp_count;
float diff = (avgRaw > ADC ? avgRaw - ADC : ADC - avgRaw) / (avgRaw == 0 ? 1 : avgRaw); //pulled out to shorten the line for SO
if (diff > TEMP_VALID_CHANGE * ((OVERSAMPLENR - temp_count) / OVERSAMPLENR)) //subsequent readings have a smaller tollerance
raw_temp_bed_value += avgRaw;
else
raw_temp_bed_value += ADC;
} else {
raw_temp_bed_value = ADC;
}
Where raw_temp_bed_value is a static global and gets read and processed later, when the ISR got fired 16 times.
As you can see, I check if the difference between the current average and the new reading is less then 15%. If so I accept the reading, if not, I reject it and add the current average instead.
But this breaks horribly if the first reading is something impossible.
One solution I though of is:
In the last line the raw_temp_bed_value is reset to the first ADC reading. It would be better to reset this to raw_temp_bed_value/OVERSAMPLENR. So I don't run in a "first reading error".
Do you have any better solutions? I though of some solutions featuring a moving average and use the average of the moving average but this would require additional arrays/RAM/cycles which we want to prevent.
I've often used something what I call rate of change to the sampling. Use a variable that represents how many samples it takes to reach a certain value, like 20. Then keep adding your sample difference to a variable divided by the rate of change. You can still use a threshold to filter out unlikely values.
float RateOfChange = 20;
float PreviousAdcValue = 0;
float filtered = FILTER_PRESET;
while(1)
{
//isr gets adc value here
filtered = filtered + ((AdcValue - PreviousAdcValue)/RateOfChange);
PreviousAdcValue = AdcValue;
sleep();
}
Please note that this isn't exactly like a low pass filter, it responds quicker and the last value added has the most significance. But it will not change much if a single value shoots out too much, depending on the rate of change.
You can also preset the filtered value to something sensible. This prevents wild startup behavior.
It takes up to RateOfChange samples to reach a stable value. You may want to make sure the filtered value isn't used before that by using a counter to count the number of samples taken for example. If the counter is lower than RateOfChange, skip processing temperature control.
For a more advanced (temperature) control routine, I highly recommend looking into PID control loops. These add a plethora of functionality to get a fast, stable response and keep something at a certain temperature efficiently and keep oscillations to a minimum. I've used the one used in the Marlin firmware in my own projects and works quite well.

Audio tone for Microcontroller p18f4520 using a for loop

I'm using C Programming to program an audio tone for the microcontroller P18F4520.
I am using a for loop and delays to do this. I have not learned any other ways to do so and moreover it is a must for me to use a for loop and delay to generate an audio tone for the target board. The port for the speaker is at RA4. This is what I have done so far.
#include <p18f4520.h>
#include <delays.h>
void tone (float, int);
void main()
{
ADCON1 = 0x0F;
TRISA = 0b11101111;
/*tone(38.17, 262); //C (1)
tone(34.01, 294); //D (2)
tone(30.3, 330); //E (3)
tone(28.57, 350); //F (4)
tone(25.51, 392); //G (5)
tone(24.04, 416); //G^(6)
tone(20.41, 490); //B (7)
tone(11.36, 880); //A (8)*/
tone(11.36, 880); //A (8)
}
void tone(float n, int cycles)
{
unsigned int i;
for(i=0; i<cycles; i++)
{
PORTAbits.RA4 = 0;
Delay10TCYx(n);
PORTAbits.RA4 = 1;
Delay10TCYx(n);
}
}
So as you can see what I have done is that I have created a tone function whereby n is for the delay and cycles is for the number of cycles in the for loop. I am not that sure whether my calculations are correct but so far it is what I have done and it does produce a tone. I'm just not sure whether it is really a A tone or G tone etc. How I calculate is that firstly I will find out the frequency tone for example A tone has a frequency of 440Hz. Then I will find the period for it whereby it will be 1/440Hz. Then for a duty cycle, I would like the tone to beep only for half of it which is 50% so I will divide the period by 2 which is (1/440Hz)/2 = 0.001136s or 1.136ms. Then I will calculate delay for 1 cycle for the microcontroller 4*(1/2MHz) which is 2µs. So this means that for 1 cycle it will delay for 2µs, the ratio would be 2µs:1cyc. So in order to get the number of cycles for 1.136ms it will be 1.136ms:1.136ms/2µs which is 568 cycles. Currently at this part I have asked around what should be in n where n is in Delay10TCYx(n). What I have gotten is that just multiply 10 for 11.36 and for a tone A it will be Delay10TCYx(11.36). As for the cycles I would like to delay for 1 second so 1/1.136ms which is 880. That's why in my method for tone A it is tone(11.36, 880). It generates a tone and I have found out the range of tones but I'm not really sure if they are really tones C D E F G G^ B A.
So my questions are
1. How do I really calculate the delay and frequency for tone A?
2. for the state of the for loop for the 'cycles' is the number cycles but from the answer that I will get from question 1, how many cycles should I use in order to vary the period of time for tone A? More number of cycles will be longer periods of tone A? If so, how do I find out how long?
3. When I use a function to play the tone, it somehow generates a different tone compared to when I used the for loop directly in the main method. Why is this so?
4. Lastly, if I want to stop the code, how do I do it? I've tried using a for loop but it doesn't work.
A simple explanation would be great as I am just a student working on a project to produce tones using a for loop and delays. I've searched else where whereby people use different stuff like WAV or things like that but I would just simply like to know how to use a for loop and delay for audio tones.
Your help would be greatly appreciated.
First, you need to understand the general approach to how you generate an interrupt at an arbitrary time interval. This lets you know you are able to have a specific action occur every x microseconds, [1-2].
There are already existing projects that play a specific tone (in Hz) on a PIC like what you are trying to do, [3-4].
Next, you'll want to take an alternate approach to generating the tone. In the case of your delay functions, you are effectively using up the CPU for nothing, when it could be done something else. You would be better off using timer interrupts directly so you're not "burning the CPU by idling".
Once you have this implemented, you just need to know the corresponding frequency for the note you are trying to generate, either by using a formula to generate a frequency from a specific musical note [5], or using a look-up table [6].
What is the procedure for PIC timer0 to generate a 1 ms or 1 sec interrupt?, Accessed 2014-07-05, <http://www.edaboard.com/thread52636.html>
Introduction to PIC18′s Timers – PIC Microcontroller Tutorial, Accessed 2014-07-05, <http://extremeelectronics.co.in/microchip-pic-tutorials/introduction-to-pic18s-timers-pic-microcontroller-tutorial/>
Generate Ring Tones on your PIC16F87x Microcontroller, Accessed 2014-07-05, <http://retired.beyondlogic.org/pic/ringtones.htm>http://retired.beyondlogic.org/pic/ringtones.htm
AN655 - D/A Conversion Using PWM and R-2R Ladders to Generate Sine and DTMF Waveforms, Accessed 2014-07-05, <http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=1824&appnote=en011071>
Equations for the Frequency Table, Accessed 2014-07-05, <http://www.phy.mtu.edu/~suits/NoteFreqCalcs.html>
Frequencies for equal-tempered scale, A4 = 440 Hz, Accessed 2014-07-05, <http://www.phy.mtu.edu/~suits/notefreqs.html>
How to compute the number of cycles for delays to get a tone of 440Hz ? I will assume that your clock speed is 1/2MHz or 500kHz, as written in your question.
1) A 500kHz clock speed corresponds to a tic every 2us. Since a cycle is 4 clock tics, a cycle lasts 8 us.
2) A frequency of 440Hz corresponds to a period of 2.27ms, or 2270us, or 283 cycles.
3) The delay is called twice per period, so the delays should be about 141 cycles for A.
About your tone function...As you compile your code, you must face some kind of warning, something like warning: (42) implicit conversion of float to integer... The prototype of the delay function is void Delay10TCYx(unsigned char); : it expects an unsigned char, not a float. You will not get any floating point precision. You may try something like :
void tone(unsigned char n, unsigned int cycles)
{
unsigned int i;
for(i=0; i<cycles; i++)
{
PORTAbits.RA4 = 0;
Delay1TCYx(n);
PORTAbits.RA4 = 1;
Delay1TCYx(n);
}
}
I changed for Delay1TCYx() for accuracy. Now, A 1 second A-tone would be tone(141,440). A 1 second 880Hz-tone would be tone(70,880).
There is always a while(1) is all examples about PIC...if you just need one beep at start, do something like :
void main()
{
ADCON1 = 0x0F;
TRISA = 0b11101111;
tone(141,440);
tone(70,880);
tone(141,440);
while(1){
}
}
Regarding the change of tone when embedded in a function, keep in mind that every operation takes at least one cycle. Calling a function may take a few cycles. Maybe declaring static inline void tone (unsigned char, int) would be a good thing...
However, as signaled by #Dogbert , using delays.h is a good start for beginners, but do not get used to it ! Microcontrollers have lots of features to avoid counting and to save some time for useful computations.
timers : think of it as an alarm clock. 18f4520 has 4 of them.
interruption : the PIC stops the current operation, performs the code specified for this interruption, erases the flag and comes back to its previous task. A timer can trigger an interruption.
PWM pulse wave modulation. 18f4520 has 2 of them. Basically, it generates your signal !

Resources