C clock program - c

I was trying to create a clock program with c using the eclipse ide.
When I run the program it keeps executing every single count.
I used system("cls"). Also tried "clear"
It shows no error but it is not working. I want the screen cleared after every count. It is showing a ⍰ symbol sometimes.
https://i.stack.imgur.com/0ElDL.png ---This is what I got.
int main(void)
{
int hour,minute,second;
hour=minute=second=0;
setbuf(stdout,NULL);
while(1)
{
system("cls");
printf("%02d:%02d:%02d\n",hour,minute,second);
fflush(stdout);
second++;
if(second==60)
{
minute += 1;
second=0;
}
if(minute==60)
{
hour += 1;
minute=0;
}
if(hour==24)
{
hour=0;
minute=0;
second=0;
}
sleep(1);
}
return 0;
.

try using system("clear");

According to example published above you need only one line to display clock. It's easier to add carriage return:
while(1)
{
printf("%02d:%02d:%02d\r",hour,minute,second);
fflush(stdout);
...
}

Related

Print data just once

i need to make somekind of "on-off" button with my project.
when the button not pressed, it supposed to print
stopped
if pressed
started
the problem is, when im not pressin it, it keep printin 'stopped', same when i keep pushin the button. i want it to only print the data once.
more detail, what i need is, the button hold the stay in 'STARTED' position until i press it again.
here is my code
{
int main (void)
int TestM4;
while(1)
{
if (!(PORTJ_IN&PIN1_bm)) //test m4
{
testM4 = 1;
printf("%d\n", testM4);
}
else
{
testM4 = 0;
printf("%d\n", testM4);
}
while(1)
This runs the while loop continuously.
So, it checks the buttons, prints out the statements, and then goes back straightaway to check them again.
To run it only once, remove the while loop altogether, but then the program will end pretty quickly.
Perhaps, look at ways to pause the program.
I don't know all the code, so while(1) could be good or bad code, but you can test as a flag to change it and print once only.
while(1)
{
if (!(PORTJ_IN&PIN1_bm)) //test m4
{
if(testM4 != 1) // status as button up
{
testM4 = 1;
printf("%d\n", testM4);
}
}
else
{
if(testM4 != 0)
{
testM4 = 0;
printf("%d\n", testM4);
}
}
}

C sleep method obstructs output to console

I have a C program, where I just wanted to test if I could reproduce a console spinner used in npm install while it installs a module. This particular spinner simply spins in this order:
|
/
-
\
on the same space, so I use the following program:
#include <stdio.h>
int main() {
char sequence[4] = "|/-\\";
while(1) {
for(int i = 0; i < 4; i++) {
// \b is to make the character print to the same space
printf("\b%c", sequence[i]);
// now I want to delay here ~0.25s
}
}
}
So I found a way to make it rest for that long from <time.h> documentation and made this program:
#include <stdio.h>
#include <time.h>
void sleep(double seconds) {
clock_t then;
then = clock();
while(((double)(clock() - then) / CLOCKS_PER_SEC) < seconds); //do nothing
}
int main() {
char sequence[4] = "|/-\\";
while(1) {
for(int i = 0; i < 4; i++) {
printf("\b%c", sequence[i]);
sleep(0.25);
}
}
}
But now nothing prints to the console. Does anyone know how I can go about producing the behavior I want?
EDIT According to what appears to be popular opinion, I've updated my code above to be the following:
#include <stdio.h>
#include <unistd.h>
int main() {
char sequence[4] = "|/-\\";
while(1) {
for(int i = 0; i < 4; i++) {
printf("\b%c", sequence[i]);
/* fflush(stdout); */
// commented out to show same behavior as program above
usleep(250000); // 250000 microseconds = 0.25 seconds
}
}
}
You will need to flush after you wrote to the console. Otherwise, the program will buffer your output:
fflush(stdout);
Things do get printed to console, it's just does not get flushed. Add fflush(stdout) to see the results, or set the console in an unbuffered mode by calling setbuf:
setbuf(stdout, NULL);
A bigger problem with your code is that your sleep method runs a busy loop, which burns CPU cycles for no good reason. A better alternative would be to call usleep, which takes the number of microseconds:
usleep(25000);
The sleep function isn't really your problem. The issue is that the output is buffered. The simplest thing to do will be to research ncurses.
For now:
fflush(stdout);

Lag using Xlib/X11 event handling in C

Beginner user of C here.
I'm trying to build a library in C using X11/Xlib so I can use it just for little projects and I'm running into a problem when trying to handle events to get input(button presses and key presses) from the user. It works fine for a while and then it starts to build up a significant lag over time.
Right now what I have is my program checking if there is an event waiting and if there is, retrieving it.
I think that my problem right now is that the events are getting stored in memory and its bogging down the program. But that's just a total guess.
Any help will be appreciated. Thank you.
EDIT: Forgot code (I knew I forgot something)
The two functions in question are:
int event_waiting()
{
XEvent event;
if(XCheckMaskEvent(dspy,-1,&event)) {
if(event.type==KeyPress) {
XPutBackEvent(dspy,&event);
return 1;
} else if (event.type==ButtonPress) {
XPutBackEvent(dspy,&event);
return 1;
}
} /* <<=== added missing close-curly here */
return 0;
}
char wait()
{
XEvent event;
XNextEvent(dspy,&event);
if(event.type==KeyPress) {
saved_x = event.xkey.x;
saved_y = event.xkey.y;
return XLookupKeysym(&event.xkey,0);
} else if(event.type==ButtonPress) {
saved_x = event.xkey.x;
saved_y = event.xkey.y;
return event.xbutton.button;
}
}
And then they are called in the main like so,
if (event_waiting()){
char c = wait();
//Switch case goes here
}
EDIT 2: UPDATED CODE
XEvent event;
if(XCheckMaskEvent(display,-1,&event))
{
if(event.type==KeyPress) {
XPutBackEvent(display,&event);
return 1;
} else if (event.type==ButtonPress) {
XPutBackEvent(display,&event);
return 1;
}
}
XFlush(display);
return 0;
`
The lag, which gets worse over time, means that you have many untouched events in your event queue, which slows down XCheckMaskEvent().
Try specifying events using XSelectInput(... ButtonPressMask | KeyPressMask), and try flushing the event queue using XFlush() if there is no event in which you are interested:
if(event.type==KeyPress) {
XPutBackEvent(dspy,&event);
return 1;
} else if (event.type==ButtonPress) {
XPutBackEvent(dspy,&event);
return 1;
} else {
XFlush(dspy); // this
}

Exit a loop at anytime

I'm trying to exit a loop at anytime I want by pressing any key. I've tried the code below but it can't be done. Gotta need your help. Thank you in advance. I'm using a C-Free 5.0.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int b=0, i;
int seconds;
printf("\nEnter number of seconds : ");
scanf("%d", &seconds);
while (b==0)
{
for(i=1;i<=seconds;i++)
{
time_t end = time(0) + 1;
while(time(0) < end)
;
seconds -= 1;
printf("Number of seconds left : %d\n", seconds);
b=kbhit();
}
if(seconds == 0)
{
exit(0);
}
}
printf("Number of remaining seconds left : %d\n", seconds);
}
You are "busy-waiting" in the innermost while loop. That might not be the best solution, but if that is what you want to do, you need to add a test in that loop to check if a key has been hit.
To exit a loop use a function in c++ called khbit. It becomes 1 when any key is pressed and to empty it again assign the key pressed to clear the buffer using getch()
#include <conio.h>
#include <iostream>
using namespace std;
int main()
{
while(1)
{
if(kbhit()) // khbit will become 1 on key entry.
{
break; // will break the loop
}
// Try to use some delay like sleep(100); // sleeps for 10th of second to avoid stress on CPU
}
// If you want to use khbit again then you must clear it by char dump = getch();
// This way you can also take a decision that which key was pressed like
// if(dump == 'A')
//{ cout<<"A was pressed e.t.c";}
}

How to break an infinite for(;;) loop in C?

I have a vital infinite for loop that allows a sensor to keep updating its values. However I would like to break that for loop when another sensor brings in new values. How can I switch from one infinite for loop to another?
Current code:
for(;;){
SON_Start();
// Wait 65ms for max range time
delay10ms(7);
// Read Range
i = SON_Read(SON_ADDRESSES[sonarReading]);
// pause
delayMs(100);
if(i<15)
drive(200, RadCW);
}
What I would like to add:
If Sensor2 returns a reading (e.g. Sensor2 > 20), then I want to break the loop and goto another infinite for loop to begin a new function.
If you are looking for "switching between 2 infinite loops" it could be "wrapped" by third loop and this "switching" could be done by simple break.
But since you want your program to stop some day, this loop could be placed within the function and you could use return; for ending it:
void myMagicLoop()
{
for(;;)
{
for(;;)
{
if ( I should stop )
return;
if ( I should switch to second loop )
break;
}
for(;;)
{
if ( I should stop )
return;
if ( I should switch back to first loop)
break;
}
}
}
And somewhere you just call:
myMagicLoop();
Hope this helps.
This will switch between loop A and loop B.
for (;;)
{
// Loop A
for (;;)
{
if WANT_TO_SWITCH
{
break;
}
}
// Loop B
for (;;)
{
if WANT_TO_SWITCH
{
break;
}
}
}
You use break; to break a loop and pass control beyond its closing brace. For example
for(;;) {
if( whatever ) {
break;
}
}
//break gets you here
Alternatively you could consider rewriting this with an event-driven approach. This will of course depend on what your hardware is capable of, but at the very least you should be able to produce some timer events.
Then the code would go something like this:
static volatile bool sensor_1_ready;
static volatile bool sensor_2_ready;
for(;;)
{
switch(state_machine)
{
case READING_SENSOR_1:
if(sensor_2_ready)
{
state_machine = READING_SENSOR_2;
}
else if(sensor_1_ready)
{
process sensor 1
}
break;
case READING_SENSOR_2:
if(!sensor_2_ready && some_timeout_etc)
{
state_machine = READING_SENSOR_1;
}
else if(sensor_2_ready)
{
process sensor 2
}
break;
}
}
void callback_sensor_1 (void) // some sort of interrupt or callback function
{
sensor_1_ready = true;
}
void callback_sensor_2 (void) // some sort of interrupt or callback function
{
sensor_2_ready = true;
}
(Before commenting on the volatile variables, please note that volatile is there to prevent dangerous compiler optimizations and not to serve as some mutex guard/atomic access/memory barrier etc.)
The "break" command should do what you need?
The best way to do that is to change the for statement to something like:
for (; Sensor2 <= 20;) {
...
Alternatively you can change it from a for to a while statement:
while (Sensor2 <= 20) {
...
If that doesn't suite your needs you can always use a break instead.
Another option could be to use signals (SIGUSR1,SIGUSR2) to switch from one loop to another.
Something of this sort:
void sensor2(int signum)
{
for (; ;)
...
/* Need to process sensor 1 now */
kill(pid, SIGUSR1);
}
void sensor1(int signum)
{
for (; ;)
...
/* Need to process sensor 2 now */
kill(pid, SIGUSR2);
}
int main()
{
/* register the signal handlers */
signal(SIGUSR1, sensor1);
signal(SIGUSR2, sensor2);
...
}

Resources