Low Pass filter in C - c

I'm implementing a low pass filter in C wih the PortAudio library.
I record my microphone input with a script from PortAudio itself. There I added the following code:
float cutoff = 4000.0;
float filter(float cutofFreq){
float RC = 1.0/(cutofFreq * 2 * M_PI);
float dt = 1.0/SAMPLE_RATE;
float alpha = dt/(RC+dt);
return alpha;
}
float filteredArray[numSamples];
filteredArray[0] = data.recordedSamples[0];
for(i=1; i<numSamples; i++){
if(i%SAMPLE_RATE == 0){
cutoff = cutoff - 400;
}
data.recordedSamples[i] = data.recordedSamples[i-1] + (filter(cutoff)*(data.recordedSamples[i] - data.recordedSamples[i-1]));
}
When I run this script for 5 seconds it works. But when I try to run this for more then 5 seconds it fails. The application records everything, but crashes on playback. If I remove the filter, the application works.
Any advice?

The problem:
you are lowering the cutoff frequency by 400 Hz everytime i%SAMPLE_RATE == 0
never stop so you go below zero
this is not done once per second !!!
instead every time your for passes through second barrier in your data
that can occur more often then you think if you are not calling your calls in the right place
which is not seen in your code
you are filtering in wrong oorder
... a[i]=f(a[i],a[i-1]; i++;
that means you are filtering with already filtered a[i-1] value
What to do with it
check the code placement
it should be in some event like on packed done sompling
or in thread after some Sleep(...); (or inside timer)
change the cut off changing (handle edge cases)
reverse filter for direction
Something like this:
int i_done=0;
void on_some_timer()
{
cutoff-=400;
if (cutoff<1) cutoff=1; // here change 1 for limit frequency
if (numSamples!=i_done)
for (i=numSamples-1,i>=i_done;i--)
data.recordedSamples[i] = data.recordedSamples[i-1] + (filter(cutoff)*(data.recordedSamples[i] - data.recordedSamples[i-1]));
i_done=numSamples;
}
if your code is already OK (you did not post th whole thing so I can missing something)
then just add the if (cutoff<1) cutoff=1; after cutoff change

Related

How to make code run every X seconds in C programming language

I am trying to make a code run repeatedly every X seconds.
Let me paint a wrestling scenario.
I have already written a code line to give Tyson fury a 5Kg punch at 40 seconds into the fight and then stop.. but there's no way I'm going to win the match with just one 5kg punch at 40 seconds. I need to be able to keep punching every 40 seconds.
Please who knows how I can achieve this?
PS.
{
real punch;
real time = CURRENT_TIME;
real tau = 40;
if (time<=tau)
{
punch=5;
}
else
{
punch=0;
}
return punch;
}
In a scenario where time acquisition is possible, as I can see you use
CURRENT_TIME
You can do it like this:
static int lastTimeExecuted = 0; // Using int here, but you should mach type of CURRENT_TIME
// See how much time passed since last execution
if ((CURRENT_TIME - lastTimeExecuted) >= 40)
{
punch = 5;
lastTimeExecuted = CURRENT_TIME ;
}
else
{
punch = 0;
}
Just remember that code abowe shuld be in a loop.

Animated ASCII art flickering in c

I'm making an ASCII art game in c (windows), but for some reason when i play it is all flickering at apparently random intervals, and for most of the time i can't see anything. can anyone explain why or how to solve it?
this is my code:
const int WIDTH = 20, HEIGTH = 5;
const int AREA = (WIDTH) * HEIGTH;
const int gl = HEIGTH - 2; //Ground level
const float delta = 0.1f; //Frame rate
char scr[AREA]; //String for displaying stuff
char input;
int posx = 10, posy = gl - 1; //Player position
int vel = 0; //player velocity
while(1)
{
//TODO: player input
for(i = 0; i < AREA; i++) //Rendering part
{
if(i % WIDTH == 0 && i != 0)
{
scr[i] = '\n';
continue;
}
if(floor(i / WIDTH) >= gl) //i is on ground
{
scr[i] = '.';
continue;
}
scr[i] = ' ';
}
//Set player position
scr[posy * WIDTH + posx + 1] = '#';
scr[(posy + 1) * WIDTH + posx + 1] = '#';
system("cls");// Clear terminal
printf(scr);// Print screen
usleep(delta * 1000);//Sleep
}
output:
#
..........#........
...................►↓#
It works, but it flickers...
One possible reason for your problem is that there may be output waiting in the output buffer when you call your sleep function usleep. In that case, you should always flush all output before sleeping, by calling the function fflush( stdout );.
Also, using system("cls"); is highly inefficient. It is generally better to use the Console Functions API, or, if you are targetting platforms with Windows 10 or later, you can also use Console Virtual Terminal Sequences instead.
If you decide to use the Console Functions API, then the main functions that you will be needing in order to replace system("cls"); are GetStdHandle to obtain the output handle, and SetConsoleCursorPosition. That way, you won't have to clear the whole screen, but will only have to overwrite the parts of the screen that are changing. I also recommend that you replace printf with WriteConsole, otherwise you may run into buffering issues.
If this does not solve your flickering problem, then there also is the possibility of using double-buffering. Both the Console Functions API and Console Virtual Terminal Sequences support this.
When using the Console Functions API, you can use the function CreateConsoleScreenBuffer to create a new buffer to write to, without it being displayed immediately. This will allow you to first finish building the next screen, without any flickering occuring while doing so (because it is not being displayed yet). Once you have finished building the next screen, you can display it using the function SetConsoleActiveScreenBuffer.
Console Virtual Terminal Sequences offer similar functionality by supporting an alternate screen buffer.

handling when a button is pressed

I have the current code, and ive tried to add in a toggle_speed() function, this will be called in the main function in an if statement of, else if (button_pushed() == 2). What im trying to accomplished is that when the button is pressed it doubles the speed, but if it is pushed again the speed will go back to normal. This is the code I have, all help is appreciated, im quite new to this. We are programming this onto AVR working with ATmega324A. Basically, I need help in constructing a valid toggle_speed function as what ive done is most certai
You basically want something like this:
volatile uint32_t background_speed, alien_speed, projectile_speed;
...
void toggle_speed(void){
static int doublespeedactive;
doublespeedactive = !doublespeedactive;
if (doublespeedactive)
{
background_speed = 600;
alien_speed = 400;
projectile_speed = 300;
}
else
{
background_speed = 600 / 2;
alien_speed = 400 / 2;
projectile_speed = 300 / 2;
}
}
doublespeedactive is a state variable. If it's 1, then double speed is active, if it's 0, then normal speed is active.
doublespeedactive = !doublespeedactive; toggles the value of doublespeedactive from 1 to 0 or from 0 to 1.
Read about the ! operator.
However you don't call toggle_speed anywhere in the code you show in your question, so this answer is possibly incomplete.
Be aware that the volatile keyword is necessary if you intend to call toogle_speed from an ISR.

How do I correctly create a copy of an array in C or set a reference to one?

so, I'm very new to C, coming from a Java/C# background and I can't quite wrap my head around it so far.
What I'm trying to do is program a microcontroller (Adafruit Feather running an atmega32u4 in this case) to pose as a USB-coupled controller for Nintendo Switch and run automated commands.
The project I'm trying to expand upon is using a struct array of commands like this:
typedef struct {
Buttons_t button;
uint16_t duration; // 1 equals 0.025s on ATmega32u4 => 1s = 40
} command;
static const command loop[] = {
// do stuff
{ NOTHING, 150 },
{ TRIGGERS, 15 }, { NOTHING, 150 },
{ TRIGGERS, 15 }, { NOTHING, 150 },
{ A, 5 }, { NOTHING, 250 }
};
Now initially this was all there was to it, the program would loop through the commands, send a button to the console and "hold" it for the defined period of time. When the program ran to the end of the array, it would simply reset the index and start anew.
Now I'm trying to send different commands to the console, based on a few easy if..else queries. Specifically, the program will start with a day, month and year variable (the date the Switch console is currently set to) and roll days forward individually to get to a set date in the future. To this end, I want to check at every 'step' if the date +1 day is valid as described in this tutorial and based on the result either roll one day, one day and one month or one day, one month and one year forward. Then I want it to end after a set amount of days.
I wrote several arrays of commands to represent the different steps needed for setting up the controller, moving to where it's supposed to loop, rolling a day, a month or a year like this:
static const command setupController[] = {
// Setup controller
...
};
static const command moveToLoop[] = {
// Go into date settings
...
};
static const command rollDay[] = {
//roll to next day
...
};
static const command rollMonth[] = {
//roll to next month
...
};
static const command rollYear[] = {
//roll to next year
...
};
And another array I want to copy those to like this:
#define COMMANDMAXSIZE 100
static command activeCommand[COMMANDMAXSIZE];
I know this is (extremely) wasteful of memory, but I'm definitely not good enough at C to come up with fancier, more conservative solutions yet.
Then I go into my program, which looks like this:
int main(void) {
SetupHardware(); //Irrelevant, because it is exactly like I downloaded it and it works even with the bumbling changes I've made
GlobalInterruptEnable(); //Ditto
RunOnce(setupController);
RunOnce(moveToLoop);
while (daysSkipped != stopDay)
{
if (datevalid((dayOfMonth + 1), month, year)) {
dayOfMonth++;
RunOnce(rollDay);
}
else if (datevalid(1, (month + 1), year)) {
dayOfMonth = 1;
month++;
RunOnce(rollMonth);
}
else if (datevalid(1, 1, (year + 1))) {
dayOfMonth = 1;
month = 1;
year++;
RunOnce(rollYear);
}
daysSkipped++;
}
}
and finally (I swear I'll be done soon), the start of RunOnce looks like this
void RunOnce(command stepsToRun[]) {
memcpy(activeCommand, stepsToRun, sizeof(activeCommand)); //set the setup commands to be active
activeBounds = sizeof(stepsToRun) / sizeof(stepsToRun[0]);
...
Later in the program, the task that translates commands into button presses for the console actually runs one fixed array, so I figured I'd just "mark" the commands to run as active, and only ever run the active array. Only, it doesn't work as expected:
The program runs, sets up the controller, moves to the date settings and indeed starts to roll a date, but then, regardless if the next day is valid or not, it rolls forward a month, then a year and then it gets stuck moving the simulated analog stick upwards and pressing A indefinitely.
I figure the problem lies in my memcpy to overwrite the active array with the steps I want to run next, but I can't think of a way to solve it. I tried writing a function that was supposed to overwrite the active array element by element using a for loop, but this way the controller wouldn't even set itself up correctly and effectively nothing happened. Usually with any kind of output capabilities I'd try to fit in prints at points of interest, but I have virtually no way of getting feedback on my microcontroller.
Any help would be greatly appreciated.
Ignoring that doing a hard copy of the data is incredibly slow and wasteful, it is also incorrect indeed.
memcpy(activeCommand, stepsToRun, sizeof(activeCommand));
Here you need to copy the size of the data you pass on, not the size of the target buffer! Right now you end up copying more data than you have, because all of these declarations static const command rollDay[] etc get a variable size depending on the number of items in the initializer list.
The quick & dirty fix to your immediate problem would be to pass along the size:
void RunOnce(size_t size, command stepsToRun[size])
{
memcpy(activeCommand, stepsToRun, size);
and then call this function with RunOnce(sizeof rollDay, rollDay); etc.
The activeBounds = sizeof(stepsToRun) / sizeof(stepsToRun[0]); part is also incorrect but not the immediate reason for the bug. See How to find the 'sizeof' (a pointer pointing to an array)? and What is array to pointer decay? etc.
When you pass array to function it decays to a pointer.
RunOnce(rollYear);
Thus
void RunOnce(command stepsToRun[]) {
memcpy(activeCommand, stepsToRun, sizeof(activeCommand)); //set the setup commands to be active
activeBounds = sizeof(stepsToRun) / sizeof(stepsToRun[0]);
}
sizeof(stepsToRun) doesn't yield the correct result as you expected, since it is now sizeof(pointer) in function.
You will have to pass the size of the array as an extra argument to RunOnce function.

watching variable values in Code Composer

I work in Code Composer Studio Version: 6.0.1.00040
with the card LCDK C6748, but I think this is a more general question, relating to CCS generally.
I'm trying to implement LMS for cancelling acoustic echoes,
this is the skeleton of my .c file:
void waitForInterrupt()
{
while (flag==0) {}
flag=0; // reach this line only when flag == 1
}
interrupt void interrupt4(void)
{
// Inputs
inputRight_micSignal = (float)input_right_sample();
// Outputs
outputLeft_referenceSignal= whiteNoiseSample;
codec_data.channel[RIGHT]= (uint16_t)outputRight_cleanedSound;
codec_data.channel[LEFT]= (uint16_t)outputLeft_referenceSignal;
output_sample(codec_data.uint);
flag = 1;
}
void main()
{
// variables decelerations
int i;
float filter_output;
// initialising filter coefficients
for (i=0 ; i<ADAPTIVE_FILT_SIZE ; i++) // initialise weights and delay line
{
w[i] = 0.0;
x[i] = 0.0;
}
// initialising the interrupt routine
L138_initialise_intr(FS_8000_HZ,ADC_GAIN_0DB,DAC_ATTEN_0DB,LCDK_MIC_INPUT);
while(1) // adaptive filtering routine
{
waitForInterrupt();
whiteNoiseSample = getPrnFiltered();
for (i = ADAPTIVE_FILT_SIZE-1; i > 0; i--) // update delay line - TDL:merge later with w loop (still make sure no magic NaN's appear)
{
x[i] = x[i-1];
}
x[0] = outputLeft_referenceSignal; // input to adaptive filter
filter_output = 0; //reseting filter output
// compute adaptive filter output
for (i = 0; i < ADAPTIVE_FILT_SIZE; i++)
filter_output += (w[i]*x[i]);
outputRight_cleanedSound = inputRight_micSignal - filter_output; // compute error
for (i = ADAPTIVE_FILT_SIZE-1; i >= 0; i--) // update weights and delay line
{
w[i] = w[i] + beta*outputRight_cleanedSound*x[i]; // w[i]+=beta*"error"*"reference"
}
from some reason when I put the arrays x[] and w[] in the "watch table"
and I suspend the running of the program (in order to examine w[] coefficients after awhile, I see that it is full of NaN's - while x[] contains "regular"
values.
when I put breakpoint inside the line where w[] is calculated:
w[i] = w[i] + beta*outputRight_cleanedSound*x[i]; // w[i]+=beta*"error"*"reference"
I see the flow goes there.
What could be the reason for the NaN's?
Is there a way to watch w[] in the "wach table"?
These three steps work for me:
1) First you need to make sure the variables are globally available (e.g. that they are not allocated on the stack).
2) You need to halt the processor before trying to read the variables. (In Debug view: Tools -> Debugger Options -> Auto Run and Launch Options).
3) Enable "halt the target before any debugger access" on the watch window and click the "auto-update" icon in the "Variables"-window.
I've uploaded a screenshot with red boxes around the stuff you need to touch.
See if that helps you :) Otherwise check out TI's Engineer2Engineer forum (E2E). In my experience the TI guys are quick to answer and I've gotten very competent help from them.
Tell me how it works for you :) ?
FWIW I'm using Code Composer Studio v.5.5.0.00077.

Resources