handling when a button is pressed - c

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.

Related

Monitor flashing when running a Windows SendInput API

Well, I certainly should go to python since I did several functions of this type, keyboard event and mouse event, but decide to try to learn the windows api.
My goal is to know when button 1 of the mouse is pressed.
I created this file in a very beginner way, it returns in mouseData only 0.
The curious thing is that whenever I run it, it flashes my monitor at short intervals in blinks, but between 1 second with it off. Very strange that, execution is not viable.
Could someone help me understand and try to execute to see if it is only here.
Code:
int main()
{
DWORD mouseData = 0;
MOUSEINPUT tagMouse;
tagMouse.dx = 0;
tagMouse.dy = 0;
tagMouse.mouseData = mouseData;
tagMouse.dwFlags = MOUSEEVENTF_XDOWN;
tagMouse.dwExtraInfo = 0;
INPUT tagInput;
tagInput.type = INPUT_MOUSE;
tagInput.mi = tagMouse;
while (true) {
if (GetAsyncKeyState(VK_DELETE)) break;
SendInput(1, &tagInput, sizeof(INPUT));
printf("KEYWORD: %d\n", mouseData);
Sleep(500);
}
system("pause");
return 0;
}
I can reproduce your reported 'symptoms' - and the effect is really brutal!
Now, while I cannot offer a full explanation, I can offer a fix! You have an uninitialized field in your tagMouse structure (the time member, which is a time-stamp used by the system). Setting this to zero (which tells the system to generate its own time-stamp) fixes the problem. So, just add this line to your other initializer statements:
//...
tagMouse.dwExtraInfo = 0;
tagMouse.time = 0; // Adding this line fixes it!
//...
Note: I, too, would appreciate a fuller explanation; however, an uninitialized field, to me, smells like undefined behaviour! I have tried a variety of other values (i.e. not zero) for the time field but haven't yet found one that works.
The discussion here on devblogs may help. This quote seems relevant:
And who knows what sort of havoc that will create if a program checks
the timestamps and notices that they are either from the future or
have traveled back in time.

"resettable" loop DSL with C macros?

I want a loop to run once unless set to repeat, but I don't like the ugliness of having to explicitly set variables as part of normal program flow.
I'm using this but the project maintainers didn't like it:
int ok = 0;
while (ok^=1) {
// ...
if (something_failed) ok = 0;
}
(compare to while (!ok) { ok = 1; // ...)
The nice thing is that you can wrap these in macros:
#define RETRY(x) while (x^=1)
#define FAIL(x) x = 0
and use them as
int ok = 0;
RETRY(ok) {
// ...
if (something_failed) FAIL(ok);
}
How can I make these macros work without the weird xor-assign?
Using XOR 1 to toggle something between 0 and 1 repeatedly is perfectly fine, particularly in hardware-related code. Is this what you are trying to do? But this isn't how you are using it, so it doesn't make sense. Also, using it together with a signed int is questionable.
Please don't invent some ugly macro language, that's 10 times worse! This is the worst thing you can do.
There exists no reason why you can't simply do something along the lines of this:
bool retry = true;
while(retry)
{
retry = false;
...
if(something_failed) retry = true;
}

Low Pass filter in 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

How to set an int to 1 if dependent on a button and in a while loop?

I'm programming a robot, and unfortunately in its autonomous mode I'm having some issues.
I need to set an integer to 1 when a button is pressed, but in order for the program to recognize the button, it must be in a while loop. As you can imagine, the program ends up in an infinite loop and the integer values end up somewhere near 4,000.
task autonomous()
{
while(true)
{
if(SensorValue[positionSelectButton] == 1)
{
positionSelect = positionSelect + 1;
wait1Msec(0350);
}
}
}
I've managed to get the value by using a wait, but I do NOT want to do this. Is there any other way I can approach this?
assuming that the SensorValue comes from a physical component that is asynchronous to the while loop, and is a push button (i.e. not a toggle button)
task autonomous()
{
while(true)
{
// check whether
if(current_time >= next_detect_time && SensorValue[positionSelectButton] == 1)
{
positionSelect = positionSelect + 1;
// no waiting here
next_detect_time = current_time + 0350;
}
// carry on to other tasks
if(enemy_is_near)
{
fight();
}
// current_time
current_time = built_in_now()
}
}
Get the current time either by some built-in function or incrementing an integer and wrap around once reach max value.
Or if you are in another situation:
task autonomous()
{
while(true)
{
// check whether the flag allows incrementing
if(should_detect && SensorValue[positionSelectButton] == 1)
{
positionSelect = positionSelect + 1;
// no waiting here
should_detect = false;
}
// carry on to other tasks
if(enemy_is_near)
{
if(fight() == LOSING)
should_detect = true;
}
}
}
Try remembering the current position of the button, and only take action when its state changes from off to on.
Depending on the hardware, you might also get a signal as though it flipped back and forth several times in a millisecond. If that's an issue, you might want to also store the timestamp of the last time the button was activated, and then ignore repeat events during a short window after that.
You could connect the button to an interrupt and then make the necessary change in the interrupt handler.
This might not be the best approach, but it will be the simplest.
From The Vex Robotics catalogue :
(12) Fast digital I/O ports which can be used as interrupts
So, most probably which ever micro-controller of Vex you are using will support Interrupts.
Your question is a bit vague
I m not sure why u need this variable to increment and how things exactly work...but i ll make a try.Explain a bit more how things work for the robot to move...and we will be able to help more.
task autonomous()
{
int buttonPressed=0;
while(true)
{
if(SensorValue[positionSelectButton] == 1)
{
positionSelect = positionSelect +1;
buttonPressed=1;
}
else{
buttonPressed = 0;
}
//use your variables here
if( buttonPressed == 1){
//Move robot front a little
}
}
}
The general idea is :
First you detect all buttons pressed and then you do things according to them
All these go in your while loop...that will(and should) run forever(at least as long as your robot is alive :) )
Hope this helps!

How can I goto the value of a String in C?

I am programming a robot in C, and I have run into a problem I can't seem to figure out.
The only way to solve this problem would be to use a lot of goto statements.
I am trying to figure out a way to save myself writing over 100 goto points and statements and if statements, etc. and am wondering if there is a way to goto the value of a string. for example-
string Next = "beginning";
goto Next;
beginning:
Is there any way to goto the value of Next, or to substitute in the value of Next into the goto statement?
If there is a way to do this, then I will be able to just change the value of Next for each driving command, and then goto whatever the value of the string Next is.
In other words, just converting the string to a goto identifier, or substituting it in place of one.
Thanks for the help!
-EDIT-
A lot of you guys are suggesting the use of switch statements. I am not sure this would work because of how i have it programmed. The structure of the program is here--
by the way this code only includes a little of what i actually have, my real code is over 500 lines so far. Also, the driving commands are majorly simplified. but the basic concept is here, easier to understand than what i wouldve had.
task main()
{
//integer list
int forwardDrivingSelector = 0;
int backwardDrivingSelector = 0;
int rightRotatingSelector = 0;
string nextCommand;
int waitTime = 0;
int countup = 0;
//driving commands
driveForward:
while(forwardDrivingSelector == 1)
{
motor[leftMotor] = 127;
motor[rightMotor] = 127;
countup++;
wait1Msec(1);
if(countup == waitTime)
{
countup = 0;
goto nextCommand;
}
}
driveBackward:
while(backwardDrivingSelector == 1)
{
motor[leftMotor] = -127;
motor[rightMotor] = 127;
countup++;
wait1Msec(1);
if(countup == waitTime)
{
countup = 0;
goto nextCommand;
}
}
rightRotate:
while(rightRotatingSelector == 1)
{
motor[leftMotor] = 127;
motor[rightMotor] = -127;
countup++;
wait1Msec(1);
if(countup == waitTime)
{
countup = 0;
goto nextCommand;
}
}
//autonomous driving code
//first command, drive forward for 1000 milliseconds
forwardDrivingSelector = 1;
nextCommand = "secondCommand";
waitTime = 1000;
goto driveForward;
secondCommand:
forwardDrivingSelector = 0;
//second command, rotate right for 600 milliseconds
rightRotatingSelector = 1;
nextCommand = "thirdCommand";
waitTime = 600;
goto rightRotate;
thirdCommand:
rightRotatingSelector = 0;
//third command, drive backwards for 750 milliseconds
backwardDrivingSelector = 1;
nextCommand = "end";
waitTime = 750;
goto driveBackward;
end:
backwardDrivingSelector = 0;
}
so. how this works.
i have a list of integers, including driving command selectors, the countup and waitTime integers, and the string that i was talking about, nextCommand.
next comes the driving commands. in my real code, i have about 30 commands, and they are all hooked up to a remote control and its over 400 lines for just the driving commands.
next comes the autonomous code. the reason i set it up like this is so that the autonomous code part would be, short, simple, and to the point. pretty much to add a command to the driving code, you turn on the selector, tell the nextCommand string what the next command is, set the waitTime (which is how long it does the command, in milliseconds), then you make the code goto the driving command which you are putting in. the driving command drives for the amount of time you put in, then does goto nextCommand;
This would all theoretically work if there was a way to make the goto statement 'interpret' the string as an identifier so it can be changed.
There are about 4 simple ways i can think of right now that could get past this easily, but they would make the code really really long and cluttered.
Now that you have a better understanding of my question, any more input? :)
btw - i am using a program called robotC, and i am programming a vex robot. so i HAVE to use plain, basic, C, and i cant use any addons or anything... which is another reason this is complicated because i cant have multiple classes and stuff like that...
As an extension to the C language, GCC provides a feature called computed gotos, which allow you to goto a label computed at runtime. However, I strongly recommend you reconsider your design.
Instead of using gotos with over a hundred labels (which will easily lead to unmaintainable spaghetti code), consider instead using function pointers. The code will be much more structured and maintainable.
Instead of goto's, I'd call one of 100 functions. While C won't handle the conversion from string to function for you, it's pretty easy to use a sorted array of structs:
struct fn {
char name[whatever];
void (*func)(void);
};
Then do (for example) a binary search through the array to find the function that matches a string.
Also note that many real systems provide things like GetProcAddress (Windows) or dlsym (Unix/Linux) to handle some of the work for you.
You're thinking about this the wrong way. Each of the actions you need to call should be a function, then you can choose which function should be called next by inspecting a "next" variable.
This could be a string as you've mentioned, but you might be best using a enumerated type to make readable, but more efficient code.
The alternative, though probably overkill, would be to ensure your functions all use the same parameters and return types, and then use a function pointer to track which piece of code should be executed next.
Small tip: If you ever think you need more than 1 goto statement to achieve a certain goal you're probably not looking at the best solution.
You need to step back and consider other solutions for the problem you are trying to solve. One of them might look like this:
void DoSomething() {
printf("Something\n");
}
void DoSomethingElse() {
printf("Something else\n");
}
void (*nextStep)(void) = NULL;
nextStep = DoSomething;
nextStep();
nextStep = DoSomethingElse;
nextStep();
See it in action.
How about a switch? Either use an int/enum/whatever or inspect the value of the string (loop over it and strcmp, for instance) to figure out the destination.
const char *dsts[n_dsts] = {"beginning","middle",...};
...
int i;
for(i = 0; i < n_dsts; i++) if(strcmp(dsts[i]) == 0) break;
switch(i) {
case 0: // whatever
case 1: // whatever
...
break;
default: // Error, dest not found
}
Firstly, let me preface this by agreeing with everyone else: this is probably not the right way to go about what you're trying to do. In particular, I think you probably want a finite-state machine, and I recommend this article for guidelines on how to do that.
That said . . . you can more or less do this by using a switch statement. For example:
Next = BEGINNING;
HelperLabel:
switch(Next)
{
case BEGINNING:
.
.
.
Next = CONTINUING;
goto HelperLabel;
case ENDING:
.
.
.
break;
case CONTINUING:
.
.
.
Next = ENDING;
goto HelperLabel;
}
(Note that a switch statement requires integers or integer-like values rather than strings, but you can use an enum to create those integers in a straightforward way.)
See http://en.wikipedia.org/wiki/Duff's_device for the original, canonical example of using switch/case as a goto.
#define GOTO_HELPER(str, label) \
if (strcmp(str, #label) == 0) goto label;
#define GOTO(str) do { \
GOTO_HELPER(str, beginning) \
GOTO_HELPER(str, end) \
} while (0)
int main (int argc, char ** argv) {
GOTO("end");
beginning:
return 1;
end:
return 0;
}

Resources