Đo tần số xung digital bằng arduino

Đo tần số xung digital bằng arduino sử dụng pulseIn()

pulseIn()

Description

Reads a pulse (either HIGH or LOW) on a pin. For example, if value is HIGHpulseIn() waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds or 0 if no complete pulse was received within the timeout.
The timing of this function has been determined empirically and will probably show errors in shorter pulses. Works on pulses from 10 microseconds to 3 minutes in length. Please also note that if the pin is already high when the function is called, it will wait for the pin to go LOW and then HIGH before it starts counting. This routine can be used only if interrupts are activated. Furthermore the highest resolution is obtained with short intervals.

Syntax

pulseIn(pin, value) 
pulseIn(pin, value, timeout)

Parameters

pin: the number of the pin on which you want to read the pulse. (int)
value: type of pulse to read: either HIGH or LOW. (int)
timeout (optional): the number of microseconds to wait for the pulse to be completed: the function returns 0 if no complete pulse was received within the timeout. Default is one second (unsigned long).

Returns

the length of the pulse (in microseconds) or 0 if no pulse is completed before the timeout (unsigned long)
CODE

unsigned long getFrequency(int);

int pin = 7;
unsigned long duration;

void setup()
{
  Serial.begin(9600);
  pinMode(pin, INPUT);
}

void loop()
{
  Serial.println(getFrequency(pin));
  delay(2000);
}

unsigned long getFrequency(int)
{
  unsigned long duration;
  duration = pulseIn(pin, HIGH);
  duration = duration + pulseIn(pin, LOW);
  return 1000000/duration;   // duration in us => 1/(duration*10^6)
}



Nhận xét

  1. Cảm ơn bạn nhé. Mình cần cái này quá. Mình muốn dùng cái này để đo tốc độ động cơ. Cám ơn bạn

    Trả lờiXóa

Đăng nhận xét

Bài đăng phổ biến từ blog này

Thu tín hiệu điều khiển hồng ngoại Arduino

Sử dụng cảm biến màu sắc TCS3200

How to Use the Sharp IR Sensor (GP2Y0A41SK0F) - Arduino