Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

write code in C for Arduino that reads the state of pin 1 every 50 milliseconds, then…

  1. User

    write code in C for Arduino that reads the state of pin 1 every 50 milliseconds, then increments a counter if that pin is high. keep doing this and print the accumulated counter result every 5 seconds

  2. Assistant
    const int inputPin = 1; // define input pin
    int counter = 0; // initialize counter variable
    unsigned long previousMillis = 0; // initialize previous millis variable 
    
    void setup() {
      pinMode(inputPin, INPUT); // set input pin mode
      Serial.begin(9600); // initialize serial communication
    }
    
    void loop() {
      unsigned long currentMillis = millis(); // save current millis
      if (currentMillis - previousMillis >= 50) { // check time elapsed
        previousMillis = currentMillis; // reset previous millis
        if (digitalRead(inputPin) == HIGH) { // check if pin is high
          counter++; // increment counter
        }
      }
      if ((currentMillis % 5000) == 0) { // check if 5 seconds elapsed
        Serial.println(counter); // print current counter value
      }
    }