计数器的C程序

时间:2014-11-27 12:40:58

标签: c counter pic

我想创建一个计数器。每隔10秒我想检查一下开关的状态。例如,如果开关闭合则10秒计数器递增。如果它打开,它会重新进入睡眠状态,在10秒内再次唤醒并检查开关的状态。当计数达到例如100时,然后做一些事情。我该怎么做呢

我的尝试是:

for(int i=0;i<100;i++){
if(SW=1) {
    i++;
}
else
    i=0;
}

3 个答案:

答案 0 :(得分:3)

我认为你需要在这个问题上更加具体。您似乎想在每次打开开关时重置计数器。你确定要的吗?

无论如何,这可能是你想要的

#include <stdio.h>
#include <time.h>
struct tm tm;   
time_t start,enxd;
double sec;
int counter;
int main(){
    int switchCounter = 0;
    int checkSwitch;

    checkSwitch = 1; // I put this in purpose since I have no idea how you're going to read the switch. 
                     // Thus, this assumes the switch is always closed.

    while(switchCounter != 100){
        // 1. Wait for 10 seconds
        sec = 0;
        time(&start);

        while(sec !=10){
            ++counter;
            time(&enxd);
            sec=difftime(enxd,start);
        }

        // 2. Read the state of the switch here.
        // ..............

        // 3. Simple if-else
        if (checkSwitch == 1){ //switch is closed
            switchCounter++;
            printf("Counter incremented. Current = %i \n", switchCounter);
        }
        else //if switch is open
        {
            switchCounter = 0 ;// Iam confused here, is this what you want ?
            printf("Switch is open \n");
        }
    }
    // 4. Finally when your counter reaches 100, you wanna do something here
    // ............................

    return 0;
}

希望有所帮助:)

答案 1 :(得分:0)

您可以查看以下代码:

int sw = 0;
#define MAX 100
#define gotosleep sleep(10)

int main(void)
{
    int num = 0;
    while(1) {
        gotosleep;
        if(sw)
            num++;
        else
            num = 0;

        if(num == MAX) {
            //do something
            printf("Done\n");
            num = 0;
            break;
        }
    }

    return 0;
}
  1. 进入10
  2. 进入睡眠状态
  3. 如果开启为ON,则为num增量,否则为reset num to 0 and go to sleep
  4. 检查num是否已设置MAX值,如果等于MAX,则执行某项操作并break。 (要继续循环注释代码中的中断)。
  5. 10秒后再次唤醒并检查开关的状态 - &gt;第2步

答案 2 :(得分:0)

我不确定我是否正确理解了您的问题,但您可以查看以下代码以获取一些想法。这是自我解释。

注意:要在本地测试功能,请启用测试代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define MAXVAL 100
#define SLEEPTIME 10

//extern int switchSet; //if defined in some other file
int switchSet;

int main()
{
    int counter = 0;
    int toSleep = 0;
#if 0
        //for testing
    switchSet = MAXVAL; 
#endif

    while (1)
    {
        toSleep = switchSet? SLEEPTIME:0;   //check for the switch state, 0 = open, 1 = closed
        if (toSleep)
        {
            printf("Going to sleep for %d sec\n", SLEEPTIME); 
            sleep(toSleep);
        }
        else
        {
            counter++;
            printf ("No sleeping, counter is %d\n", counter);
        }
        if (counter == MAXVAL)
        break;
#if 0
        //for testing 
        switchSet--;
        if (switchSet < 0) switchSet = 0;
#endif
    }

    printf("Do Something... Did, Done !!\n");

    return 0;

}