Nhiệm vụ của analogRead() là đọc giá trị điện áp từ một chân Analog (ADC). Trên mạch Arduino UNO có 6 chân Analog In, được kí hiệu từ A0 đến A5. Trên các mạch khác cũng có những chân tương tự như vậy với tiền tố "A" đứng đầu, sau đó là số hiệu của chân.
analogRead() luôn trả về 1 số nguyên nằm trong khoảng từ 0 đến 1023 tương ứng với thang điện áp (mặc định) từ 0 đến 5V. Bạn có thể điều chỉnh thang điện áp này bằng hàm analogReference().
Hàm analogRead() cần 100 micro giây để thực hiện.
Khi người ta nói "đọc tín hiệu analog", bạn có thể hiểu đó chính là việc đọc giá trị điện áp.
Cú pháp
analogRead([chân đọc điện áp]);
Ví dụ
int voltage = analogRead(A0);
Trong đó A0 là chân dùng để đọc điện áp.
Nếu bạn chưa kết nối chân đọc điện áp, hàm analogRead() sẽ trả về một giá trị ngẫu nhiên trong khoảng từ 0 đến 1023. Để khắc phục điều này, bạn phải mắc thêm một điện trở có trị số lớn (khoảng 10k ohm trở lên) hoặc một tụ điện 104 từ chân đọc điện áp xuống GND.
Trong đó A0 là chân dùng để đọc điện áp.
Nếu bạn chưa kết nối chân đọc điện áp, hàm analogRead() sẽ trả về một giá trị ngẫu nhiên trong khoảng từ 0 đến 1023. Để khắc phục điều này, bạn phải mắc thêm một điện trở có trị số lớn (khoảng 10k ohm trở lên) hoặc một tụ điện 104 từ chân đọc điện áp xuống GND.
/*Analog InputDemonstrates analog input by reading an analog sensor on analog pin 0 andturning on and off a light emitting diode(LED) connected to digital pin 13.The amount of time the LED will be on and off depends on the value obtainedby analogRead().The circuit:- potentiometercenter pin of the potentiometer to the analog input 0one side pin (either one) to groundthe other side pin to +5V- LEDanode (long leg) attached to digital output 13cathode (short leg) attached to ground- Note: because most Arduinos have a built-in LED attached to pin 13 on theboard, the LED is optional.created by David Cuartiellesmodified 30 Aug 2011By Tom IgoeThis example code is in the public domain.http://www.arduino.cc/en/Tutorial/AnalogInput*/int sensorPin = A0; // select the input pin for the potentiometerint ledPin = 13; // select the pin for the LEDint sensorValue = 0; // variable to store the value coming from the sensorvoid setup() {// declare the ledPin as an OUTPUT:pinMode(ledPin, OUTPUT);}void loop() {// read the value from the sensor:sensorValue = analogRead(sensorPin);// turn the ledPin ondigitalWrite(ledPin, HIGH);// stop the program for <sensorValue> milliseconds:delay(sensorValue);// turn the ledPin off:digitalWrite(ledPin, LOW);// stop the program for for <sensorValue> milliseconds:delay(sensorValue);}
No comments:
Post a Comment