Frequency Adjusting with STM32 DAC - stm32

I used STM32F407VG to create a 30 khz sine wave. Timer settings are; Prescaler = 2-1, ARR = 1, also the clock is 84 Mhz(the clock which runs DAC).
I wrote a function called generate_sin();
#define SINE_ARY_SIZE (360)
const int MAX_SINE_DEGERI = 4095; // max_sine_value
const double BASLANGIC_NOKTASI = 2047.5; //starting point
uint32_t sine_ary[SINE_ARY_SIZE];
void generate_sine(){
for (int i = 0; i < SINE_ARY_SIZE; i++){
double deger = (sin(i*M_PI*360/180/SINE_ARY_SIZE) * BASLANGIC_NOKTASI) + BASLANGIC_NOKTASI; //double value
sine_ary[i] = (uint32_t)deger; // value
}
This is the function which creates sine wave. I used HAL DMA to send DAC output variables.
HAL_TIM_Base_Start(&htim2);
generate_sine();
HAL_DAC_Start_DMA(&hdac, DAC_CHANNEL_1, sine_ary, SINE_ARY_SIZE, DAC_ALIGN_12B_R);
These are the codes i used to do what i want. But im having a trouble to change frequency without changing prescaler or ARR.
So here is my question. Can i change frequency without changing timer settings ? For example i want to use buttons and whenever i push button i want my frequency to change.

The generate_sine function will give you one period of a sine wave which has SINE_ARY_SIZE of samples.
To increase the frequency you need to make the period shorter (for 2x frequency, you would have half the number of samples per period). So you should calculate the array for smaller SINE_ARY_SIZE (which will fill just part of the original buffer with a shorter sine wave) and also put this smaller value in the HAL_DAC_Start_DMA function.
Decreasing the frequency will require making the array longer.
You should declare the sine_ary with a maximum length that you will need (for lowest frequency). Make sure it fits in RAM.
#define MAXIMUM_ARRAY_LENGTH 360
uint32_t usedArrayLength = 180;
const double amplitude = 2047.5;
uint32_t sine_ary[MAXIMUM_ARRAY_LENGTH];
void generate_sine(){
for (int i = 0; i < usedArrayLength; i++){
double value = (sin(i*M_PI*2/usedArrayLength) * amplitude) + amplitude;
sine_ary[i] = (uint32_t)value; // value
}
This will have two times higher frequency than the original code, because it only has 180 samples per period, compared to 360.
Start it using
HAL_DAC_Start_DMA(&hdac, DAC_CHANNEL_1, sine_ary, usedArrayLength, DAC_ALIGN_12B_R);
To change the frequency, stop DAC, change the value of usedArrayLength (smaller value means higher frequency, must be less or equal to MAXIMUM_ARRAY_LENGTH). Then call the generate_sine function and start the DAC again by the same function (that now uses new usedArrayLength).
Frequency will be: Clock/prescaler/ARR/usedArrayLength
Also, you should use uint16_t for the array (values are from 0 to 4095, the DAC is 12bit I suppose) and DMA should be set to Half-word (2 bytes per value).

Related

How to generate Sine Wave on top of Triangular Wave using the DAC with DMA of STM32G4

I have a STM32G4 nucleo board. I would like to generate a summation waveform consisting of triangular wave (~1Hz) and sine wave (500Hz) using the DAC and DMA on STM32G4.
Is it possible to get the summation waveform out from one DAC channel? Can anyone help me with this? Any help is appreciated. Thanks.
I computed a lookup table for one cycle of sine wave. And I added the sine wave onto an incrementing line. Then I realized it will only generate a triangle wave with one cycle of sine wave when it is ramping up and one cycle of sine wave when it is ramping down.
#define dac_buf_len 200
HAL_DAC_Start_DMA(&hdac1, DAC_CHANNEL_2, (uint32_t *) dac, dac_buf_len,DAC_ALIGN_12B_R);
//generate sine wave
for (uint32_t i=0; i < dac_buf_len; i++)
{
float s = (float) i/(float)(dac_buf_len-1);
dac_sin[i] = sine_amplitude * sin(2*M_PI*s); //one cycle of sine wave
}
//generate triangular wave (ramp up)
for (uint32_t i=0; i<dac_buf_len/2; i++)
{
dac_triangular[i] = 0.006*i - 0.5;
}
//generate triangular wave (ramp down)
for (uint32_t i=0; i<dac_buf_len/2; i++)
{
dac_triangular[100+i] = -0.006*i + 0.1;
}
//sum two waves together
for (uint32_t i=0; i< dac_buf_len; i++)
{
dac[i] = dac_sin[i] + dac_triangular[i];
}
for me it sounds like you'd want the DAC Peripheral / the DMA Peripheral do the Math automatically do for you. IMHO this is simply not possible and the wrong approach.
The correct approach would be:
calculate the sinus wave, calculate the triangular wave, add both values (for each sample), convert it into the corresponding integer value and store it in the DMA buffer. Then the DAC will create the output voltages that correspond to a superposition of both signals you generated.
if you want to fill the DMA Buffer blockwise, do the same, but in a loop.

STM32 HAL Nucleo F446RE Quadrature Encoder

I have a problem with the quadrature encoder mode on timer TIM3 of my
STM32F446RE /
NUCLEO-F446RE:
TIM3 counts on every rising edge on the first signal.
The CNT register counts up and I read the value with 1 Hz and then
I set the register to 0.
When I look on the
oscilloscope
the frequency is half as high as the value from the
CNT register output (1hz).
Why?
TIM3 counts on both edges on the first signal.
The
CNT register output (1 Hz)
is completely wrong.
My configuration is:
GPIO_InitTypeDef sInitEncoderPin1;
sInitEncoderPin1.Pin = pin1Encoder.pin; // A GPIO_PIN_6
sInitEncoderPin1.Mode = GPIO_MODE_AF_PP;
sInitEncoderPin1.Pull = GPIO_PULLUP;
sInitEncoderPin1.Speed = GPIO_SPEED_HIGH;
sInitEncoderPin1.Alternate = altFunctionEncoder; // GPIO_AF2_TIM3
GPIO_InitTypeDef sInitEncoderPin2;
sInitEncoderPin2.Pin = pin2Encoder.pin; // A GPIO_PIN_7
sInitEncoderPin2.Mode = GPIO_MODE_AF_PP;
sInitEncoderPin2.Pull = GPIO_PULLUP;
sInitEncoderPin2.Speed = GPIO_SPEED_HIGH;
sInitEncoderPin2.Alternate = altFunctionEncoder; // GPIO_AF2_TIM3
HAL_GPIO_Init(GPIOA, &sInitEncoderPin1);
HAL_GPIO_Init(GPIOA, &sInitEncoderPin2);
encoderTimer.Init.Period = 0xffff;
encoderTimer.Init.Prescaler = 0;
encoderTimer.Init.CounterMode = TIM_COUNTERMODE_UP;
encoderTimer.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
encoderTimer.Init.RepetitionCounter = 0;
HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
HAL_NVIC_SetPriority(SysTick_IRQn, 0, 1);
encoder.EncoderMode = TIM_ENCODERMODE_TI1;
encoder.IC1Filter = 0x0f;
encoder.IC1Polarity = TIM_INPUTCHANNELPOLARITY_RISING; // TIM_INPUTCHANNELPOLARITY_BOTHEDGE
encoder.IC1Prescaler = TIM_ICPSC_DIV1;
encoder.IC1Selection = TIM_ICSELECTION_DIRECTTI;
encoder.IC2Filter = 0x0f;
encoder.IC2Polarity = TIM_INPUTCHANNELPOLARITY_RISING;
encoder.IC2Prescaler = TIM_ICPSC_DIV1;
encoder.IC2Selection = TIM_ICSELECTION_DIRECTTI;
HAL_TIM_Encoder_Init(&encoderTimer, &encoder);
HAL_TIM_Encoder_Start_IT(&encoderTimer, TIM_CHANNEL_ALL);
The
oscilloscope screenshot
shows a frequency of about 416 Hz.
The values shown in the
first shell output
are (very roughly!) twice as high (as the question points out already).
This appears (nearly...) correct to me since the shown configuration
encoder.EncoderMode = TIM_ENCODERMODE_TI1;
selects the "X2 resolution encoder mode", which counts 2 CNT increments per signal period.
In an application note on
timer overview,
(Sec. 4.3.4 / Fig. 7) there is an illustrative diagram how the encoder mode works in detail.
The
second screenshot
results from an incorrect TIM3 configuration:
The encoder mode (TIM_ENCODERMODE_TI1) assumes that both channels trigger only upon directed flanks in an alternating way (see the AN link above).
If one of the two channels triggers twice as many events due to
configuration
encoder.IC1Polarity = TIM_INPUTCHANNELPOLARITY_BOTHEDGE,
the counter will only count up one position and then "recognize" a "reversal" event (= change of direction).
Keeping in mind that
65535u = 0xFFFF = -1
the second screenshot only shows values -1, 0, +1 - which fits perfectly with this explanation.
The question remains why the first screenshot shows (reproducible) measurements between 800 and 822.
I assume that
the physical source of the encoder signal runs at a constant pace
the 1 Hz timer that triggered shell output is independent from TIM3, and
it has been started before the encoder timer
(i.e., above the shown code sample).
This may explain why the first two values look like nonsense (0: TIM3 has not been started yet. 545: TIM3 has been started during the shell output timer period).
Discarding the first two measurement samples, the average and standard deviation, resp., of the measured signal frequency are
808,9091 +/- 0,5950 [X2 increments per second]
404,4545 +/- 0,2975 [Hz]
which corresponds to a period of
2,4331 +/- 0,003 [ms].
Hence, the measured frequency is too low by about 11 Hz, i.e., measured period too high by nearly 30 µs, and this error is clearly beyond the statistical noise.
The question gives a hint where this error might come from:
The CNT register counts up and I read the value with 1 Hz and then I set the register to 0.
Whenever the 1 Hz "polling timer" expires, it triggers an interrupt
(or a logical event in polling software).
Processing of this interrupt/event may be delayed a little,
depending on other software (IRQ: deactivation times elsewhere in the software,
Polling: loop duration until event is polled).
Software reads CNT value.
Software resets CNT value to zero,
discarding further increments since the CNT value has been read.
TIM3 continues counting (from zero).
This hints that software needs 30 µs between (3.) and (4.), which would be quite a lot of time on an STM32F4.
Edit: I just re-checked the oscilloscope screenshot. The error is visible, but I believe it is smaller than I originally assumed (from counting flanks in the picture).

What is the best way to convert adc values

I need to convert my ADC result value from an hexadecimal value to a float value and a percentage.
For example I've a 12bit resolution stored into a uint16_t(becouse I've possibility to change resolution). So VREF should be 0x0FFF and GND 0x0000.
Now, I need to convert this values into volts and percentage.
I wanted to do this:
float volt, perc, vref;
vref = 3.3;
uint16_t adc_value = ADC_RESULT;
volt = (vref/0x0FFF)*adc_value;
perc = adc_value/(0x0FFF/100);
Since I'm performing this operation in a MCU, I wanted to make it more efficent. How do you advice me to do and which type of variable should I use(or made conversions)?

Procedural structure generation

I have a voxel based game in development right now and I generate my world by using Simplex Noise so far. Now I want to generate some other structures like rivers, cities and other stuff, which can't be easily generated because I split my world (which is practically infinite) into chunks of 64x128x64. I already generated trees (the leaves can grow into neighbouring chunks), by generating the trees for a chunk, plus the trees for the 8 chunks surrounding it, so leaves wouldn't be missing. But if I go into higher dimensions that can get difficult, when I have to calculate one chunk, considering chunks in an radius of 16 other chunks.
Is there a way to do this a better way?
Depending on the desired complexity of the generated structure, you may find it useful to first generate it in a separate array, perhaps even a map (a location-to-contents dictionary, useful in case of high sparseness), and then transfer the structure to the world?
As for natural land features, you may want to google how fractals are used in landscape generation.
I know this thread is old and I suck at explaining, but I'll share my approach.
So for example 5x5x5 trees. What you want is for your noise function to return the same value for an area of 5x5 blocks, so that even outside of the chunk, you can still check if you should generate a tree or not.
// Here the returned value is different for every block
float value = simplexNoise(x * frequency, z * frequency) * amplitude;
// Here it will return the same value for an area of blocks (you should use floorDiv instead of dividing, or you it will get negative coordinates wrong (-3 / 5 should be -1, not 0 like in normal division))
float value = simplexNoise(Math.floorDiv(x, 5) * frequency, Math.floorDiv(z, 5) * frequency) * amplitude;
And now we'll plant a tree. For this we need to check what x y z position this current block is relative to the tree's starting position, so we can know what part of the tree this block is.
if(value > 0.8) { // A certain threshold (checking if tree should be generated at this area)
int startX = Math.floorDiv(x, 5) * 5; // flooring the x value to every 5 units to get the start position
int startZ = Math.floorDiv(z, 5) * 5; // flooring the z value to every 5 units to get the start position
// Getting the starting height of the trunk (middle of the tree , that's why I'm adding 2 to the starting x and starting z), which is 1 block over the grass surface
int startY = height(startX + 2, startZ + 2) + 1;
int relx = x - startX; // block pos relative to starting position
int relz = z - startZ;
for(int j = startY; j < startY + 5; j++) {
int rely = j - startY;
byte tile = tree[relx][rely][relz]; // Get the needing block at this part of the tree
tiles[i][j][k] = tile;
}
}
The tree 3d array here is almost like a "prefab" of the tree, which you can use to know what block to set at the position relative to the starting point. (God I don't know how to explain this, and having english as my fifth language doesn't help me either ;-; feel free to improve my answer or create a new one). I've implemented this in my engine, and it's totally working. The structures can be as big as you want, with no chunk pre loading needed. The one problem with this method is that the trees or structures will we spawned almost within a grid, but this can easily be solved with multiple octaves with different offsets.
So recap
for (int i = 0; i < 64; i++) {
for (int k = 0; k < 64; k++) {
int x = chunkPosToWorldPosX(i); // Get world position
int z = chunkPosToWorldPosZ(k);
// Here the returned value is different for every block
// float value = simplexNoise(x * frequency, z * frequency) * amplitude;
// Here it will return the same value for an area of blocks (you should use floorDiv instead of dividing, or you it will get negative coordinates wrong (-3 / 5 should be -1, not 0 like in normal division))
float value = simplexNoise(Math.floorDiv(x, 5) * frequency, Math.floorDiv(z, 5) * frequency) * amplitude;
if(value > 0.8) { // A certain threshold (checking if tree should be generated at this area)
int startX = Math.floorDiv(x, 5) * 5; // flooring the x value to every 5 units to get the start position
int startZ = Math.floorDiv(z, 5) * 5; // flooring the z value to every 5 units to get the start position
// Getting the starting height of the trunk (middle of the tree , that's why I'm adding 2 to the starting x and starting z), which is 1 block over the grass surface
int startY = height(startX + 2, startZ + 2) + 1;
int relx = x - startX; // block pos relative to starting position
int relz = z - startZ;
for(int j = startY; j < startY + 5; j++) {
int rely = j - startY;
byte tile = tree[relx][rely][relz]; // Get the needing block at this part of the tree
tiles[i][j][k] = tile;
}
}
}
}
So 'i' and 'k' are looping withing the chunk, and 'j' is looping inside the structure. This is pretty much how it should work.
And about the rivers, I personally haven't done it yet, and I'm not sure why you need to set the blocks around the chunk when generating them ( you could just use perlin worms and it would solve problem), but it's pretty much the same idea, and for your cities too.
I read something about this on a book and what they did in these cases was to make a finer division of chunks depending on the application, i.e.: if you are going to grow very big objects, it may be useful to have another separated logic division of, for example, 128x128x128, just for this specific application.
In essence, the data resides is in the same place, you just use different logical divisions.
To be honest, never did any voxel, so don't take my answer too serious, just throwing ideas. By the way, the book is game engine gems 1, they have a gem on voxel engines there.
About rivers, can't you just set a level for water and let rivers autogenerate in mountain-side-mountain ladders? To avoid placing water inside mountain caveats, you could perform a raycast up to check if it's free N blocks up.

How do I set up a buffer when doing an FFT using the Accelerate framework?

I'm using the Accelerate framework to perform a Fast Fourier Transform (FFT), and am trying to find a way to create a buffer for use with it that has a length of 1024. I have access to the average peak and peak of a signal on which I want to do the FFT.
Can somebody help me or give me some hints to do this?
Apple has some examples of how to set up FFTs in their vDSP Programming Guide. You should also check out the vDSP Examples sample application. While for the Mac, this code should translate directly across to iOS as well.
I recently needed to do a simple FFT of an 64 integer input waveform, for which I used the following code:
static FFTSetupD fft_weights;
static DSPDoubleSplitComplex input;
static double *magnitudes;
+ (void)initialize
{
/* Setup weights (twiddle factors) */
fft_weights = vDSP_create_fftsetupD(6, kFFTRadix2);
/* Allocate memory to store split-complex input and output data */
input.realp = (double *)malloc(64 * sizeof(double));
input.imagp = (double *)malloc(64 * sizeof(double));
magnitudes = (double *)malloc(64 * sizeof(double));
}
- (CGFloat)performAcceleratedFastFourierTransformAndReturnMaximumAmplitudeForArray:(NSUInteger *)waveformArray;
{
for (NSUInteger currentInputSampleIndex = 0; currentInputSampleIndex < 64; currentInputSampleIndex++)
{
input.realp[currentInputSampleIndex] = (double)waveformArray[currentInputSampleIndex];
input.imagp[currentInputSampleIndex] = 0.0f;
}
/* 1D in-place complex FFT */
vDSP_fft_zipD(fft_weights, &input, 1, 6, FFT_FORWARD);
input.realp[0] = 0.0;
input.imagp[0] = 0.0;
// Get magnitudes
vDSP_zvmagsD(&input, 1, magnitudes, 1, 64);
// Extract the maximum value and its index
double fftMax = 0.0;
vDSP_maxmgvD(magnitudes, 1, &fftMax, 64);
return sqrt(fftMax);
}
As you can see, I only used the real values in this FFT to set up the input buffers, performed the FFT, and then read out the magnitudes.