ใบงาน 3.6 การเขียนโปรแกรมใช้งานบอร์ด Arduino ที่มีการใช้ฟังก์ชันที่สร้างขึ้นและมีการทำงานแบบวนซ้ำ (while loops)
ใบงาน 3.6 การเขียนโปรแกรมใช้งานบอร์ด Arduino ที่มีการใช้ฟังก์ชันที่สร้างขึ้นและมีการทำงานแบบวนซ้ำ (while loops)
วิธีการทดลอง
ทำการศึกษาแผนผังการต่อวงจรเพื่อใช้งานฟังก์ชันที่สร้างขึ้นและมีการทำงานวนซ้ำ (while loop)
ทำการต่อวงจรเพื่อใช้งานฟังก์ชันที่สร้างขึ้นและมีการทำงานวนซ้ำ (while loop)
ทำการเขียนโปรแกรมภาษาซี ดังนี้
การกำหนดพินและตัวแปร:
sensorPin (A0): พินที่เชื่อมต่อกับเซ็นเซอร์
ledPin (9): พินที่เชื่อมต่อกับ LED
indicatorLedPin (13): พินที่เชื่อมต่อกับ LED ในตัวบอร์ด
buttonPin (2): พินที่เชื่อมต่อกับปุ่ม
sensorMin และ sensorMax: ค่าต่ำสุดและค่าสูงสุดที่อ่านได้จากเซ็นเซอร์
sensorValue: ค่าที่อ่านได้จากเซ็นเซอร์
ฟังก์ชัน setup():
กำหนดพินต่าง ๆ เป็น input หรือ output
เริ่มต้นการสื่อสารผ่าน Serial ที่ความเร็ว 9600 bps
ฟังก์ชัน loop():
ขณะที่ปุ่มถูกกด (digitalRead(buttonPin) == HIGH), จะเรียกใช้ฟังก์ชัน calibrate() เพื่อปรับเทียบค่าเซ็นเซอร์
หลังจากการปรับเทียบเสร็จสิ้น, ปิด LED ที่พิน indicatorLedPin
อ่านค่าจากเซ็นเซอร์ (analogRead(sensorPin))
ปรับค่าที่อ่านได้ให้อยู่ในช่วง 0 ถึง 255 (map(sensorValue, sensorMin, sensorMax, 0, 255))
ตรวจสอบให้แน่ใจว่าค่าอยู่ในช่วง 0 ถึง 255 (constrain(sensorValue, 0, 255))
ปรับความสว่างของ LED ตามค่าที่ปรับเทียบแล้ว (analogWrite(ledPin, sensorValue))
code โปรแกรม
//Function & while loop
const int sensorPin = A0; // pin that the sensor is attached to
const int ledPin = 9; // pin that the LED is attached to
const int indicatorLedPin = 13; /* pin that the built-in LED is
attached to */
const int buttonPin = 2; // pin that the button is attached to
// These variables will change:
int sensorMin = 1023; // minimum sensor value
int sensorMax = 0; // maximum sensor value
int sensorValue = 0; // the sensor value
void setup() {
// set the LED pins as outputs and the switch pin as input:
pinMode(13, OUTPUT);
pinMode(9, OUTPUT);
pinMode(2, INPUT);
Serial.begin(9600);
}
void loop() {
// while the button is pressed, take calibration readings:
while (digitalRead(buttonPin) == HIGH) {
calibrate();
}
// signal the end of the calibration period
digitalWrite(indicatorLedPin, LOW);
// read the sensor:
sensorValue = analogRead(sensorPin);
// apply the calibration to the sensor reading
sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);
// in case the sensor value is outside the range seen during calibration
sensorValue = constrain(sensorValue, 0, 255);
//Serial.print(sensorValue);
// fade the LED using the calibrated value:
analogWrite(ledPin, sensorValue);
Serial.println(sensorValue);
}
void calibrate() {
// turn on the indicator LED to indicate that calibration is happening:
digitalWrite(indicatorLedPin, HIGH);
// read the sensor:
sensorValue = analogRead(sensorPin);
// record the maximum sensor value
if (sensorValue > sensorMax) {
sensorMax = sensorValue;
}
// record the minimum sensor value
if (sensorValue < sensorMin) {
sensorMin = sensorValue;
}
}