I would like to know if I can use a pressure sensor with an Arduino. The code will detect when the sensor is on, will start a timer, stop when the sensor is off, and display the time elapsed.

Here is the code for the timer:

int main(void) {
  LARGE_INTEGER frequency; // ticks per second
  LARGE_INTEGER t1,t2; // ticks
  double elapsedTime;
  // get ticks per second
  // start timer
  //the code for sensorwill be written here
  elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
  printf("\nElapsed time : %lf ms.\n", elapsedTime );
  return 0;
  • QueryPerformanceCounter is a function from windows API. Arduino's millis() function will act in a similar way, but only in millisecond accuracy.
    – chamod
    Oct 26, 2016 at 7:44
  • @chamod Arduino also has a micros() function which has accuracy down to 4 microseconds
    – Mukira
    Oct 26, 2016 at 12:09

2 Answers 2


You can easily do this in Arduino.

However I've noticed that you've written the code in C with the Windows functions. Why not write the Arduino code and use what the Arduino already has available, which is the millis() and micros() functions? The only problem with the micros() function is that it will overflow after 70 minutes.

The other thing to mention is how will you know when your sensor is on? One way would be to constantly read the value and set a threshold so that you can see whether the pressure sensor is under pressure or not.

Most of the code for this can be extracted from the various Arduino examples that are on the website.

For the pressure sensor threshold you can use the Arduino AnalogInput example and add an if statement after the analog read and combine that with the millis() function from the Arduino BlinkWithoutDelay example:

int sensorPin = A0; // Choose whichever analog pin you like
int sensorValue = 0;
int flagA = 0;
// flag is used just to indicate if timer has started or stopped

unsigned long startTime;
unsigned long stopTime;
unsigned long elapsedTime;

void setup() {

void loop() {
  sensorValue = analogRead(sensorPin);
  // read the value from the sensor
  if(flagA == 0  && sensorValue > xxx) then {
    // if above threshold run timer
    startTime = millis();
    flagA = 1;
  if(flagA == 1 && sensorValue < xxx) then {
    // if falls below threshold stop timer
    stopTime = millis();
    elapsedTime = stopTime - startTime;
    Serial.print("Elapsed time = ");
    // Put your print function in here
    Serial.println(" ms");
    flagA = 0;

Fairly easy, as basically you just need to time stamp the events from the sensor.

You can create a time base for the stamping. Triggering for the stamping can be done via polling, external or pin hanger I terrupts, or capture. To list a few.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.