## How to measure 1 and 0 in digital signal ?

I have an wind speed sensor which gives me digital signal of 1 and 0, with "1" on 3.3 V and "0" on 0 V. i use MBED NXP LPC1768 I want to count how many "1" is in my signal in 0.5 seconds This is my code below :

Problem is in that I have for output in counter numbers like 87642,72348,93484 which I think it's not right.

Has anyone have solution ?

I would much appreciate that.

So you are taking a polling approach where you spin in a loop and continuously check the input. This could work if you don't have anything else to do in the program. A more common approach would be to set a rising edge interrupt on p9. The hardware will look for the low to high transition for you and then run specified function every time a low to high transition is detected.

You don't say what sensor you are using. We would need to know exactly what output it generates in order to decode it. Should we be counting pulses? So X number of pulses in 500ms = Y wind speed? This means you want to count the number of transitions from low input to high input in 500ms. Make a variable to keep track of current pin state. When the pin state changes from low to high, increment your counter.

Another possibility is the output time high vs time low represents the wind speed. In which case you just need to add another counter and increment it when the input = 0. At the end of 500ms you get a ratio of time_high : time_low.

posted by Graham S. 19 Jun 2017

##### 2 years, 7 months ago.

Hello Stjepan,

Below is a code counting pulses (rising edges) in 500ms.

```#include "mbed.h"

Serial          pc(USBTX, USBRX);
InterruptIn     input(p9);
Timeout         timeout;
volatile bool   measuringEnabled = false;
volatile int    counter;

//ISR counting pulses
void onPulse(void) {
if(measuringEnabled)
counter++;
}

// ISR to stop counting
void stopMeasuring(void) {
measuringEnabled = false;
}

// Initializes counting
void startMeasuring(void) {
counter = 0;
timeout.attach(callback(&stopMeasuring), 0.5);
measuringEnabled = true;
}

int main() {
input.rise(callback(&onPulse)); // assign an ISR to count pulses
while(1) {
startMeasuring();
while(measuringEnabled);    // wait until the measurement has completed
pc.printf("counter = %d\r\n", counter);
}
}
```

TIP FOR EDITING: You can copy and paste a code into your question as text and enclose it within `<<code>> and <</code>>` tags as below (each tag on separate line). Then it's going to be displayed as code in a frame.

```<<code>>
#include "mbed.h"

DigitalOut led1(LED1);

int main()
{
while (1) {
led1 = !led1;
wait(0.5);
}
}
<</code>>

```