// these constants won't change. They are the lowest and highest readings you
// get from your sensor:
const int sensorMin = 8; // sensor minimum, discovered through experiment
const int sensorMax = 1016; // sensor maximum, discovered through experiment
void setup() {
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
// read the sensor:
int sensorReading = analogRead(A0);
// map the sensor range to a range of four options:
int range = map(sensorReading, sensorMin, sensorMax, 0, 3);
/*
int newvalue = map ( value, fromLow, fromHigh, toLow, toHigh )
โดยพารามิเตอร์
value คือค่าเดิมที่อาจจะอ่านได้จาก analogread หรือค่าจากตัวแปรใด ๆ ที่เราต้องการเปลี่ยนมัน
fromLow คือค่าต่ำสุดของค่าเดิม
fromHigh คือค่าสูงสุดของค่าเดิม
toLow คือค่าต่ำสุดของค่าใหม่ที่เราต้องการเมื่อค่าเก่ามีค่าต่ำสุด
toHigh ค่าค่าสูงสุดของค่าใหม่ที่เราต้องการเมื่อค่าเก่ามีค่าสูงสุด
เช่น กรณีค่าที่เราอ่านจากเซนเซอร์เดิมๆ ได้ 0-1023 แต่ต้องการปรับช่วง
ค่าเป็นตั้งแต่ 25-80 ก็ใส่ลงในฟังก์ชั่นเป็น
int val = map(analogRead(A7), 0, 1023, 25, 80);
*/
// do something different depending on the range value:
switch (range) {
case 0: // your hand is on the sensor
Serial.println("dark");
break;
case 1: // your hand is close to the sensor
Serial.println("dim");
break;
case 2: // your hand is a few inches from the sensor
Serial.println("medium");
break;
case 3: // your hand is nowhere near the sensor
Serial.println("bright");
break;
}
delay(1); // delay in between reads for stability
}