How do i stop the blocking? - c

Hey all I've asked this question a few times in the past few days but I just don't get it...I basically want to have the while loop for the Beep command executed in the background while the user can interact with the available case statements (only one shown..there are others)....i keep getting blocked and everytime i want the beep to make a sound constantly i block the rest of my program...I have to use Beep so please don't suggest any other functionality..
here's a sample code...
while( keypress != 'q' || keypress != 'Q')
{
x = Beep(x);
while (x == 1)
Beep(350,300);
alarm_t current;
keypress = _getch();
switch(keypress){
case 'h':
sprintf_s(current.message,"high alarm");
current.timeOfEvent = time(NULL);
recordEvent(current);
break;
Now...my issue is with the while loop and the Beep command....here is what i call to Beep(x)
int Beep(int y)
{
return y;
}
So basically i am trying to call a function outside of my current cpp file to just compare x and y, and return y as being equivalent to x...i thought this might avoid blocking but it doesn't...

Your while loop around beep just won't work and _getch is blocking. So it will just block until there's a character.
Depending what platform you are on, you need something like kbhit (and if you google that you will find alternatives for other platforms). ie it's not standard C functionality and platform specific.
kbhit will return true or false depending if there is a character or not.
So you can do:
while(!key_is_quit(ch))
{
Beep();
if(kbhit())
{
ch = getch();
// switch....
}
}

Related

threads in c, how to use them to move a player?

Update my code
So i am working on a 2d game in c, now i am using threads to do different stuff in the same time, to move the player, cars etc.
But somehow i don't get it how can i move my player just one step, i know that the problem lays in my global variable movement. But can figure it how to do it the right way. So i hope someone can help me.
The code is huge so i will not passt all of it but the parts that are interesting for the player movement.
void moveFroggy() {
// froggy.y = SCREEN_HEIGHT - OUTER_BORDER;
if((movement == 'a') && (froggy.x > OUTER_BORDER))
froggy.x--;
if((movement == 'd') && (froggy.x < (SCREEN_WIDTH - OUTER_BORDER)))
froggy.x++;
if ((movement == 'w') && (froggy.y >= (SCREEN_HEIGHT - NUM_LANES - OUTER_BORDER - GRASS_BORDER)))
froggy.y--;
if ((movement == 's') && (froggy.y < (SCREEN_HEIGHT - OUTER_BORDER)))
froggy.y++;
if(movement == 'q')
quit = 1;
if(froggy.y <= (SCREEN_HEIGHT - NUM_LANES - OUTER_BORDER - GRASS_BORDER))
player_won = 1;
movement = '0';
}
Now inside the main we have a while loop that runs all the time, till the player complete the game or quit it.
pthread_create(&input_t, NULL, input_runner, NULL);
while(!quit && !error && !player_lost && !player_won) {
moveFroggy();
moveCarsOnMotorway();
startCar((SCREEN_WIDTH - OUTER_BORDER));
drawScreen();
usleep(GAME_SPEED);
}
pthread_join(input_t, NULL);
So my input_t thread is calling the input_runner function inside that function i get the user input.
void *input_runner(void* arg) {
char input;
if(!player_lost || !player_won){
while((input = getchar()) != EOF){
movement = input;
}
}
pthread_exit(0);
}
Just to know movement is a global variable so i can use it for moveFroggy function. but that is the problem to because it stores "w" and it just repeat itself till the user hit any other command. But it should move the player just one step ahead, so how can i reset the value and how to do proper clean up for threads if one is needed.
I am new in using thread,
Well, it seems the simple way to only move one step would be, at the bottom of moveFroggy() to clear movement value.
As an aside, it looks like you're creating an input-processing thread on every iteration of your game loop; is that really what you intend? If you want an input-processing thread, why not have it run its own loop to constantly read input until the game is over?
I'm also not sure of this overall multithreading strategy, but perhaps it will work for you...
This is not a good use of threads, and will be prone to synchronization errors.
Variables that are accessed by multiple threads must be protected by a mutex or accessed using atomic methods. Failing to do so will result in unpredictable behavior.
In any case, you don't need threads for this. If you want to read from the keyboard without blocking, there are a number of ways of doing that, including:
If on Linux, use the ncurses library, which natively provides non-blocking keyboard input through getch().
If on Windows, use kbhit().
Use fcntl() with F_SETFL to set standard input as non-blocking.
Use select() or poll() to check for input before trying to read.
Avoid the console entirely, and use a graphics library such as SDL.

Input text in graphics in C programming

I am making a project in C. Its simple, just a Hangman Game.
Got the logic already cause I've done that only in console.
Now, I'm trying to do it in C again with GRAPHICS. I am using Turbo C.
I've read some of the functions of graphics.h: so far I've seen outtext() / outtextxy() something like that. It can print a string.
Can you input a char or string in graphics? Searched a lot but seen nothing.
Seen only drawing shapes examples.
How do you input characters, integers etc. in the graphics mode?
From memory, while you can use regular stdio functions printf, scanf, and gets, the graphics driver will paint them over your screen onto a "virtual cursor" position and scroll the screen when it reaches the bottom. You can use the nonstandard conio.h functions such as gotoxy and attempt to position the cursor, but it's still a mediocre way of inputting text, messing up the graphics stuff. You also cannot use the fancy fonts!
So use getch to read characters without showing them; update a string buffer (manually handling special keys such as Backspace and Return), and draw that on the screen using a font of your choice.
A short sample snippet of code to get you started:
#define MAX_INPUT_LEN 80
char inputbuf[MAX_INPUT_LEN];
int input_pos = 0;
then, in your main loop
int the_end = 0;
do
{
outtextxy (0,0, inputbuf);
c = getch();
switch (c)
{
case 8: /* backspace */
if (input_pos)
{
input_pos--;
inputbuf[input_pos] = 0;
}
break;
case 13: /* return */
the_end = 1;
break;
case 27: /* Escape = Abort */
inputbuf[0] = 0;
the_end = 1;
break;
default:
if (input_pos < MAX_INPUT_LEN-1 && c >= ' ' && c <= '~')
{
inputbuf[input_pos] = c;
input_pos++;
inputbuf[input_pos] = 0;
}
}
} while (!the_end);
Before you draw the text, make sure to erase the previous line! I left that out because it's been too long ago I used Turbo-C.
For taking input from used.. you can use scanf function similar to how we take input in any non-graphics c program.
You can do this by using normal scanf function. And by using sprintf copy a integer/whatever variable into a string. Now you can use outtextxy to set the string in specified location using x,y axis. Check geeksforgeeks to learn sprintf syntax.
I know it is too late. Hope it helps someone else.!

C - Ncurses - How to stop cursor from moving over walls (walls made up of a bunch of charecters)

Is there a way or function available which would stop me from going over the characters. The maze looks like the following below. I actually dont use printf, but mvprint. I just used printf as an example below.
printf("xxxxxx x");
printf("xxxxxx x");
printf("xxxxxx x");
printf("x x");
printf("x xxxxxx");
printf("x xxxxxx");
I tried the this code below but it doesn't seem to work. The cursor still goes over the x characters. In the third line of the code you can see I've said that if there is a character 'f' there which is created by the bunch of printf statements seen above, the cursor shouldn't move. This doesn't seem to work.
if(m == 's')
{
if((oldy+1,x)=='x') // This is the part of the code where i say that if the next spot is an 'x' dont move.
{
mvprint(win, 10,0,"Sorry, you cant move there.");
refresh(win);
}
else
{
move((y= oldy+1),x);
refresh();
oldy = y;
}
}
After a little bit of research, I think you want your inner condition to be:
if(mvinch(oldy+1,x) == 'x')
The mvinch(y,x) function moves and returns the character at that location.
Also, as other people mentioned, mixing standard I/O and Curses is unreliable at best. When I tried something like this on my machine to test, my program told me that the entire screen was made up of spaces.

how to stop a loop arduino

I have this loop, how would I end the loop?
void loop() {
// read the pushbutton input pin:
a ++;
Serial.println(a);
analogWrite(speakerOut, NULL);
if(a > 50 && a < 300){
analogWrite(speakerOut, 200);
}
if(a <= 49){
analogWrite(speakerOut, NULL);
}
if(a >= 300 && a <= 2499){
analogWrite(speakerOut, NULL);
}
This isn't published on Arduino.cc but you can in fact exit from the loop routine with a simple exit(0);
This will compile on pretty much any board you have in your board list. I'm using IDE 1.0.6. I've tested it with Uno, Mega, Micro Pro and even the Adafruit Trinket
void loop() {
// All of your code here
/* Note you should clean up any of your I/O here as on exit,
all 'ON'outputs remain HIGH */
// Exit the loop
exit(0); //The 0 is required to prevent compile error.
}
I use this in projects where I wire in a button to the reset pin. Basically your loop runs until exit(0); and then just persists in the last state. I've made some robots for my kids, and each time the press a button (reset) the code starts from the start of the loop() function.
Arduino specifically provides absolutely no way to exit their loop function, as exhibited by the code that actually runs it:
setup();
for (;;) {
loop();
if (serialEventRun) serialEventRun();
}
Besides, on a microcontroller there isn't anything to exit to in the first place.
The closest you can do is to just halt the processor. That will stop processing until it's reset.
Matti Virkkunen said it right, there's no "decent" way of stopping the loop. Nonetheless, by looking at your code and making several assumptions, I imagine you're trying to output a signal with a given frequency, but you want to be able to stop it.
If that's the case, there are several solutions:
If you want to generate the signal with the input of a button you could do the following
int speakerOut = A0;
int buttonPin = 13;
void setup() {
pinMode(speakerOut, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
}
int a = 0;
void loop() {
if(digitalRead(buttonPin) == LOW) {
a ++;
Serial.println(a);
analogWrite(speakerOut, NULL);
if(a > 50 && a < 300) {
analogWrite(speakerOut, 200);
}
if(a <= 49) {
analogWrite(speakerOut, NULL);
}
if(a >= 300 && a <= 2499) {
analogWrite(speakerOut, NULL);
}
}
}
In this case we're using a button pin as an INPUT_PULLUP. You can read the Arduino reference for more information about this topic, but in a nutshell this configuration sets an internal pullup resistor, this way you can just have your button connected to ground, with no need of external resistors.
Note: This will invert the levels of the button, LOW will be pressed and HIGH will be released.
The other option would be using one of the built-ins hardware timers to get a function called periodically with interruptions. I won't go in depth be here's a great description of what it is and how to use it.
The three options that come to mind:
1st) End void loop() with while(1)... or equally as good... while(true)
void loop(){
//the code you want to run once here,
//e.g., If (blah == blah)...etc.
while(1) //last line of main loop
}
This option runs your code once and then kicks the Ard into
an endless "invisible" loop. Perhaps not the nicest way to
go, but as far as outside appearances, it gets the job done.
The Ard will continue to draw current while it spins itself in
an endless circle... perhaps one could set up a sort of timer
function that puts the Ard to sleep after so many seconds,
minutes, etc., of looping... just a thought... there are certainly
various sleep libraries out there... see
e.g., Monk, Programming Arduino: Next Steps, pgs., 85-100
for further discussion of such.
2nd) Create a "stop main loop" function with a conditional control
structure that makes its initial test fail on a second pass.
This often requires declaring a global variable and having the
"stop main loop" function toggle the value of the variable
upon termination. E.g.,
boolean stop_it = false; //global variable
void setup(){
Serial.begin(9600);
//blah...
}
boolean stop_main_loop(){ //fancy stop main loop function
if(stop_it == false){ //which it will be the first time through
Serial.println("This should print once.");
//then do some more blah....you can locate all the
// code you want to run once here....eventually end by
//toggling the "stop_it" variable ...
}
stop_it = true; //...like this
return stop_it; //then send this newly updated "stop_it" value
// outside the function
}
void loop{
stop_it = stop_main_loop(); //and finally catch that updated
//value and store it in the global stop_it
//variable, effectively
//halting the loop ...
}
Granted, this might not be especially pretty, but it also works.
It kicks the Ard into another endless "invisible" loop, but this
time it's a case of repeatedly checking the if(stop_it == false) condition in stop_main_loop()
which of course fails to pass every time after the first time through.
3rd) One could once again use a global variable but use a simple if (test == blah){} structure instead of a fancy "stop main loop" function.
boolean start = true; //global variable
void setup(){
Serial.begin(9600);
}
void loop(){
if(start == true){ //which it will be the first time through
Serial.println("This should print once.");
//the code you want to run once here,
//e.g., more If (blah == blah)...etc.
}
start = false; //toggle value of global "start" variable
//Next time around, the if test is sure to fail.
}
There are certainly other ways to "stop" that pesky endless main loop
but these three as well as those already mentioned should get you started.
This will turn off interrupts and put the CPU into (permanent until reset/power toggled) sleep:
cli();
sleep_enable();
sleep_cpu();
See also http://arduino.land/FAQ/content/7/47/en/how-to-stop-an-arduino-sketch.html, for more details.
just use this line to exit function:
return;

Can anyone suggest a way of coding captureing keystrokes without waiting for keys to be pressed?

I'm coding a snake game in C and my compiler is turbo C.
I've got a problem with moving the snake. I need a function or a way of coding so that I can move my snake without the keyboard waiting for a key to be pressed. but if a key is pressed some specific actions are to be done. I used the structure below but it doesn't work as I explained above:
while (gameStatus == CONTINUE)
{
if(kbhit)
{
char c = getch();
.....
}
.....
}
can anyone help?
kbhit is a function. When you write if(kbhit) you are testing if the function exists. Instead call the function by writing if(kbhit()).
while (gameStatus == CONTINUE)
{
if (kbhit())
{
char c = '\0';
/*a keystroke return 0*/
if ((c=getch())!=0)
{
c=getch(); /*then you capture the actual directional key*/
......conditionals
}
//else if not was a directional, you Can Pause or Something
.....
}
.....
}

Resources