C program to detect the time change and reset the counter [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have an inbuilt algorithm in my application. Whenever I run the algorithm, it saves that exact run time in the database. For example, if I run the algorithm at 11.00, it saves that time. And again if I run at 11.05, it saves 11.05 in the database.
I want to detect the number of times it Ran. So that once it runs for 5 times, I need to do some action like changing the values and reset the counter to 0. So that when it reaches 5 iterations, again I should reset the counter.
I am a beginner. It will be helpful if you could help me with the syntax.
MAIN
{
int temp1, temp2, flag = 0, max = 5;
temp1 = GET_INT_VALUE(8,1,84,1,0);
if flag = 0;
while(1)
{
if (templ == temp2)
flag++;
else
flag = 0;
if (flag == max)
{
//sprintf(Message,"SE value is %d",temp2);
PRINTOUT("Message");
flag = 0;
break;
}
}
}
END

The best way is to use a static local variable, like this:
void foo(void) {
static int counter = 0;
counter++;
if(counter > 5) {
counter = 0;
/* Do something every fifth time */
}
}
Note that you can't use a normal local variable (e.g. int counter = 0;) because its contents will be lost when the function returns. The static makes it work more like a global variable (so its value isn't lost when the function returns).

Related

Loop does not stop even after passing condition [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
void initTimer (void);
void delay (unsigned long milli);
void main (void)
{
//initialize peripherals
initTimer();
//PORTB all outputs
TRISB = 0;
LATB = 0;
TRISA = 0x0F;
ANSA = 0;
unsigned int allon = 0b1111111111111111;
unsigned int counter;
unsigned int zero = 0b0000000000000000;
if (PORTAbits.RA0 == 1 && PORTAbits.RA1 == 1 && PORTAbits.RA2 == 0)
for (counter = 0; counter < 5; counter++)
{
LATB = allon;
delay(SHORT_DELAY);
LATB = zero;
delay(LONG_DELAY);
}
}
I thought this was like the most foolproof code ever, but it doesnt stop after 5 times, not sure whats going on. The variables are set to binary, which determines which outputs are on or off, zero is alloff, and allon is the opposite
Unlike programs in hosted environments (that is running under OS) which can "return" from main by passing control back to the host, embedded bare-metal programs have nowhere to return. So a typical bare-metal program should have an infinite loop somewhere - either as some even-processing loop, periodic task loop or just in the end of the main function in case it has a finite sequence of actions. In your case it seem to be the last one - you only want to blink few times and halt. So the solution is to place
while(1);
in the end of main function such that it will enter infinite idle loop after execution until reset.

The output is correct but the online judge wouldn't accept? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I had tried all the C compiler but keep getting wrong answer on test 1, even though i already try to use the input on test 1 and had received the correct output when I tried it on the DEV c++.
input:
5
0 1 0 1 1
output:
4
this is a case study, so basically 5 in the input means the amount of period.
0 means break time and 1 means study time. if input is 1 total hour of study hours would be added by one, if its 0 there will be no study hence study hours would not be added. there is also a special case, like shown in the input if previously she was studying and now she is having breaks but after the breaks she will have a class (1 0 1) the break will be counted as study time and so study hours will be ++.
any idea? is it the code perhaps?
(the accepted code)
#include <stdio.h>
#include <string.h>
int main()
{
int n,hours=0;
scanf("%d",&n);
char str[n*2];
int x[n];
while ((getchar()) != '\n');
fgets(str, n*2 , stdin);
char* piece = strtok(str, " ");
for(int i=1; piece != NULL ; i++)
{
sscanf(piece, "%d" , &x[i]);
piece = strtok(NULL, " ");
}
for(int i=0 ; i<n+1; i++)
{
if(i==0)
{
if(x[0]==1){
hours++;
}
}
else
{
if(x[i]==0)
{
if( x[i-1]==1 && x[i+1]==1 )
{
hours++;
}
}
else
{
hours++;
}
}
}
printf("%d\n",hours);
return 0;
}
You are using [ i-1 ] and when index is 0 in for some inputs you will get a garbage value. May be it will work for some inputs,and not for others.
The most common reason the online judge do not accept the solution even though the answer is correct in other ide is either because you have extra indentation in your program or a loop doesn't terminate, or you get garbage value or you try incrementing a not defined value.

Meltdown PoC Detailed Code Review [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I read all the week-end about Meltdown and Spectre
I also have already read the .pdfs for Spectre and Meltdown
which are Must Read for anyone seeking more knowledge about these exploits but unfortunately don't provide detailed explanations on the code.
I found various PoC on github, which were very interesting but I lack the knowledge to fully understand it. I would be thanksful about more explanation on specific parts:
From this link https://github.com/dendisuhubdy/meltdown/blob/master/src/poc.c , and other git repositories as well, there are many interesting parts in the conception of this exploit.
Time reads
/* Time reads. Order is lightly mixed up to prevent stride prediction */
for (i = 0; i < 256; i++) {
mix_i = ((i * 167) + 13) & 255;
addr = &array2[mix_i * 512];
time1 = __rdtscp(&junk); /* READ TIMER */
junk = *addr; /* MEMORY ACCESS TO TIME */
time2 = __rdtscp(&junk) - time1; /* READ TIMER & COMPUTE ELAPSED TIME */
if (time2 <= CACHE_HIT_THRESHOLD && mix_i != array1[tries % array1_size])
results[mix_i]++; /* cache hit - add +1 to score for this value */
}
why do we use prime numbers 167 and 13 ?
/* Locate highest & second-highest results results tallies in j/k */
Why do we care about getting the max value ?
Other parts explanations are very welcome as well !!

What is the C way to report progress of computation? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
This is a follow-up question to Using a thread in C++ to report progress of computations.
Suppose that I have a for loop which executes run_difficult_task() many times, and I would like to infer how far the loop has advanced. I used to write:
int i;
for (i=0; i < 10000; ++i) {
run_difficult_task(i);
if (i % 100 == 0) {
printf("i = %d\n", i);
}
}
but the main problem with such approach is that executing run_difficult_task() might literally take forever (by being stuck in an infinite loop, etc.), so I would like to get a progress report in every k seconds by means of printing out the value of the loop variable i.
I found quite a rich literature on this site regarding object-oriented multithreading (of which I am not really familiar with) in various programming languages, but the questions I found doing this in C-style seem quite outdated. Is there a platform-independent, C11 way to do what I want? If there is not any, then I would be interested in methods working in unix and with gcc.
Note: I do not wish to run various instances of run_difficult_task in parallel (with, for example, OpenMP), but I want to run the for loop and the reporting mechanism in parallel.
Related: How to "multithread" C code and How do I start threads in plain C?
Linux (and also POSIX systems) provide the alarm library call. This allows you to do something after an interval of seconds without interrupting your main thread, and without bothering with multi-threading when you don't really need it. It was very much created for use cases like yours.
You can try using one thread (the worker thread) or possibly two (one that does computations and one that displays output while main is doing something else or just waiting) and some global variables (ugh).
The first thread will be your workhorse doing computations and updating some global variable. The second one (maybe simply the main thread) will then check whether this variable has changed or not and then print the stats (perhaps, that variable will hold the stats, for example, percentage).
What you can try:
int ping = 0, working = 0, data;
// in main thread
for (/* something */){
// spawn worker thread
while (working) {
if (ping) printf("%d\n", data), ping = 0;
}
}
// in worker thread
working = 1;
while (/* something */) {
// do a lot of computations
if (/* some condition */) {
if (! ping) {
data = /* data */
ping = 1;
}
}
}
working = 0;
Here's a simple time based progress indicator that I've often used:
void
progress(int i)
{
time_t tvnow;
static time_t tvlast;
static time_t tvbeg;
if (tvbeg == 0) {
tvbeg = time(NULL);
tvlast = tvbeg - 2;
}
tvnow = time(NULL);
if ((tvnow - tvlast) >= 1) {
printf("\r%ld: i = %d",tvnow - tvbeg,i);
fflush(stdoout);
tvlast = tvnow;
}
}
int i;
for (i=0; i < 10000; ++i) {
run_difficult_task(i);
progress(i);
}
UPDATE:
Does this update if run_difficult_task(i) runs for longer than 2seconds?
No, but I've updated the example to put the progress code in a separate function, which is what I normally do in my own code.
You'll have to add calls to the progress function within run_difficult_task to get finer grain progress--this is something I also do in my own code.
But, notice that I added an elapsed time [in seconds] to the progress.
If you didn't care about that, if run_difficult_task takes longer than 2 seconds to run, there is no progress until it returns as you define it because progress is defined by incrementing i which is done by the outer loop.
For my own stuff, the progress function can handle an arbitrary number of progress indicators from an arbitrary number of worker threads.
So, if that would be of interest to you, and [say] run_difficult_task has some inner loop variables like j, k, l, these could be added to the progress. Or, whatever you wish to report on.

Value being reset in while loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am very new to this programming, trying to seta project up on proteus to add, minus and set an alarm through the use of buttons connected to a PIC. Issue is the count is not saving after the while loop and is being reset.
- button1= ADD, button2=MINUS, button 1+2+3 = ALARM
- cant figure out why overall count is being reset to 0
- Any help would be amazing
#include <main.h>
#ZERO_RAM
int a = 0;
int state;
char data = 'y';
short int flags[3];
char uart_rd;
void main()
{
setup_wdt(WDT_1MS); //~1.0 ms reset
port_a_pullups(0xFF); // Defining PORTA as pullup Resistors
printf("program start" nr); //<------keeps resetting value to 0 HERE
while (TRUE) // infinite loop
{
if (!input(PIN_A1)) // add button
{
if (!flags[0])
{
flags[0] = 1;
a++; // add one to overall count
printf("ADDED, Total= %dnr", a); // prints count
}
}
else
{
flags[0] = 0;
}
if (!input(PIN_A2)) // minus button
{
if (!flags[1])
{
flags[1] = 1;
a--; // take away 1 from count
printf("MINUS, Total= %dnr", a); // print count
}
}
else
{
flags[1] = 0;
}
if ((!input(PIN_A1)) && (!input(PIN_A2)) && (!input(PIN_A3))) // all buttons equal alarm
{
printf("ALARM HAS BEEN SETnr"); // if all buttons are held constant alarm
// is printed through Terminal
}
else
{
flags[2] = 0;
output_high(PIN_A0); // led goes high
delay_ms(500); // flashing LED every cycle
output_low(PIN_A0); // led goes low
printf("Overall Count= %dnr", a); // printf overall count
}
}
}
You have the following bugs:
You never initialize flags anywhere. Sure, static storage duration variables are required by the standard to be initialized to zero. But in embedded systems, there is an incredibly common non-standard extension which removes the "zero-out" part from the start up code. When you create a project you often get an option "minimal startup" or "standard C". Therefore, always initialize all your variables manually in run-time before using them. Robust embedded code makes no assumptions about the default values of variables in neither .datanor .bss segments.
You haven't implemented any debouncing. Please check some beginner tutorial about how to read buttons in embedded systems, to avoid problems with the electro-mechanical signal bounce. The signal bounce causes the code flags[0] = 0; to get executed.
Whenever someone presses a button, your condition for increasing the counter remains true for as long as the button is pressed. The microcontroller is fast enough to run that code many thousand times over during the time a slow human keeps the button pressed. Instead, you should only increase the counter when the button goes from inactive to active. Obviously, the code doing this needs to be located after the debouncing.

Resources