Arduino UNO R4 Cảm Biến Cảm Ứng

Cảm biến cảm ứng (touch sensor), còn được gọi là nút cảm ứng (touch button) hoặc công tắc cảm ứng (touch switch), thường được sử dụng để điều khiển các thiết bị như đèn cảm ứng. Nó hoạt động giống như một nút nhấn thông thường. Nhiều thiết bị mới sử dụng cảm biến cảm ứng thay vì các nút nhấn truyền thống vì chúng giúp sản phẩm trở nên đẹp mắt và hiện đại hơn.

Trong hướng dẫn này, chúng ta sẽ học cách sử dụng cảm biến cảm ứng với Arduino UNO R4.

Arduino UNO R4 cảm biến chạm

Linh Kiện Cần Thiết

1×Arduino UNO R4 WiFi hoặc Arduino UNO R4 Minima
1×(Tùy chọn) DIYables STEM V4 IoT, tương thích với Arduino Uno R4 WiFi Amazon
1×Arduino UNO R4 Minima (Thay thế) Amazon
1×Cáp USB Type-C Amazon
1×Cảm Biến Cảm Ứng Amazon
1×Dây Nối Jumper Amazon
1×(Khuyến nghị) Screw Terminal Block Shield for Arduino UNO R4 Amazon
1×(Khuyến nghị) Sensors/Servo Expansion Shield for Arduino UNO R4 Amazon
1×(Khuyến nghị) Breadboard Shield for Arduino UNO R4 Amazon
1×(Khuyến nghị) Enclosure for Arduino UNO R4 Amazon
1×(Khuyến nghị) Power Splitter for Arduino UNO R4 Amazon
1×(Khuyến nghị) Prototyping Base Plate & Breadboard Kit for Arduino UNO Amazon

Or you can buy the following kits:

1×DIYables STEM V4 IoT Starter Kit (Arduino included) Amazon
1×DIYables STEM V4B IoT Starter Kit (Arduino included) Amazon
1×DIYables Sensor Kit (18 sensors/displays) Amazon
Tiết lộ: Một số liên kết trong bài viết này là liên kết tiếp thị Amazon và có thể nhận hoa hồng theo chính sách của chương trình.
Arduino Uno R4 WiFi Compatible Boards

Giới Thiệu Về Cảm Biến Cảm Ứng

Sơ Đồ Chân

Cảm biến cảm ứng có ba chân:

  • Chân GND: kết nối với GND (0V)
  • Chân VCC: kết nối với VCC (5V hoặc 3.3V)
  • Chân SIGNAL: chân này xuất tín hiệu: LOW khi không được chạm, HIGH khi được chạm. Kết nối chân này với chân đầu vào của Arduino UNO R4.
cảm biến chạm sơ đồ chân

Cách Hoạt Động

  • Nếu cảm biến không được chạm, chân tín hiệu của cảm biến ở mức LOW.
  • Nếu cảm biến được chạm, chân tín hiệu của cảm biến ở mức HIGH.

Arduino UNO R4 - Cảm Biến Cảm Ứng

Chân SIGNAL của cảm biến cảm ứng được kết nối với một chân đầu vào trên Arduino UNO R4.

Bạn có thể biết được cảm biến cảm ứng có đang được chạm hay không bằng cách kiểm tra trạng thái của chân Arduino UNO R4 được cấu hình là chân đầu vào.

Sơ Đồ Kết Nối

Arduino UNO R4 cảm biến chạm sơ đồ đấu dây

This image is created using Fritzing. Click to enlarge image

Với dự án dùng lâu dài, cầu đấu vít giữ dây tốt hơn dây jumper. Hãy thử Screw Shield V2 hoặc Proto Screw Terminal Block Shield: nó gắn lên Arduino UNO R4, và mỗi chân có cầu đấu vít riêng. Bên dưới là sơ đồ nối dây với Screw Shield V2.

Arduino UNO R4 cảm biến chạm sơ đồ đấu dây (screw shield v2)

This image is created using Fritzing. Click to enlarge image

Cách Lập Trình Cho Cảm Biến Cảm Ứng

  • Cấu hình chân Arduino UNO R4 là đầu vào số (digital input), sử dụng hàm pinMode(). Ví dụ, cho chân số 7:
pinMode(7, INPUT_PULLUP);
  • Sử dụng hàm digitalRead() để kiểm tra trạng thái của chân Arduino UNO R4:
int inputState = digitalRead(7);

※ Lưu ý:

Có hai tình huống phổ biến:

  • Tình huống thứ nhất: Khi đầu vào là HIGH, thực hiện một hành động. Khi đầu vào là LOW, thực hiện hành động ngược lại.
  • Tình huống thứ hai: Khi đầu vào thay đổi từ LOW sang HIGH (hoặc HIGH sang LOW), thực hiện một hành động.

Chúng ta chọn tình huống phù hợp dựa trên nhu cầu của mình. Ví dụ, khi sử dụng cảm biến cảm ứng để điều khiển LED:

  • Để bật LED khi cảm biến được chạm và tắt khi không chạm, tình huống thứ nhất phù hợp.
  • Để bật và tắt LED mỗi lần chạm cảm biến, tình huống thứ hai phù hợp.

Code Arduino UNO R4 - Cảm Biến Cảm Ứng

Đọc giá trị từ cảm biến cảm ứng và in ra Serial Monitor

/* * Mã Arduino UNO R4 này được phát triển bởi newbiely.vn * Mã Arduino UNO R4 này được cung cấp để sử dụng công khai, không có ràng buộc. * Để xem hướng dẫn chi tiết và sơ đồ kết nối, vui lòng truy cập: * https://newbiely.vn/tutorials/arduino-uno-r4/arduino-uno-r4-touch-sensor */ #define SENSOR_PIN 7 // The Arduino UNO R4 pin connected to the touch sensor's SIGNAL pin void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); // initialize the Arduino's pin as aninput pinMode(SENSOR_PIN, INPUT); } void loop() { // read the state of the the input pin: int state = digitalRead(SENSOR_PIN); // print state to Serial Monitor Serial.println(state); }

Các Bước Thực Hiện

Thực hiện theo từng bước sau:

  • Nếu đây là lần đầu tiên bạn sử dụng Arduino Uno R4 WiFi/Minima, hãy tham khảo hướng dẫn Arduino UNO R4 - Cài Đặt Phần Mềm.
  • Kết nối cảm biến cảm ứng với Arduino Uno R4 theo sơ đồ đã cung cấp.
  • Kết nối bo mạch Arduino Uno R4 với máy tính bằng cáp USB.
  • Khởi động Arduino IDE trên máy tính của bạn.
  • Chọn bo mạch Arduino Uno R4 phù hợp (ví dụ: Arduino Uno R4 WiFi) và cổng COM.
  • Sao chép code ở trên và mở bằng Arduino IDE
  • Nhấp vào nút Upload trong Arduino IDE để tải code lên Arduino UNO R4
  • Đặt ngón tay lên cảm biến và sau đó nhấc ra.
  • Kiểm tra kết quả trên Serial Monitor.
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Uno R4 WiFi
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno R4 WiFi' on 'COM15')
New Line
9600 baud
0 0 1 1 1 1 1 0 0 0 0
Ln 11, Col 1
Arduino Uno R4 WiFi on COM15
2

Phát hiện khi cảm biến được chạm hoặc được thả

/* * Mã Arduino UNO R4 này được phát triển bởi newbiely.vn * Mã Arduino UNO R4 này được cung cấp để sử dụng công khai, không có ràng buộc. * Để xem hướng dẫn chi tiết và sơ đồ kết nối, vui lòng truy cập: * https://newbiely.vn/tutorials/arduino-uno-r4/arduino-uno-r4-touch-sensor */ #define SENSOR_PIN 7 // The Arduino UNO R4 pin connected to the touch sensor's SIGNAL pin int touch_state; // the current reading from the input pin int prev_touch_state = LOW; // the previous state from the input pin void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); // initialize the Arduino's pin as aninput pinMode(SENSOR_PIN, INPUT); } void loop() { // read the state of the the input pin: touch_state = digitalRead(SENSOR_PIN); if(prev_touch_state == LOW && touch_state == HIGH) Serial.println("The sensor is touched"); else if(prev_touch_state == HIGH && touch_state == LOW) Serial.println("The sensor is is released"); // save the the last state prev_touch_state = touch_state; }

Các Bước Thực Hiện

  • Sao chép code và mở bằng Arduino IDE
  • Nhấp vào nút Upload trong Arduino IDE để tải code lên Arduino UNO R4
  • Đặt ngón tay lên cảm biến và giữ nguyên.
  • Kiểm tra kết quả trên Serial Monitor.
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Uno R4 WiFi
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno R4 WiFi' on 'COM15')
New Line
9600 baud
The sensor is touched
Ln 11, Col 1
Arduino Uno R4 WiFi on COM15
2
  • Nhấc ngón tay khỏi cảm biến.
  • Kiểm tra kết quả trên Serial Monitor.
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Uno R4 WiFi
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno R4 WiFi' on 'COM15')
New Line
9600 baud
The sensor is touched The sensor is is released
Ln 11, Col 1
Arduino Uno R4 WiFi on COM15
2

Video Tutorial

Việc sản xuất video tốn rất nhiều thời gian. Nếu video hướng dẫn hữu ích cho việc học của bạn, hãy đăng ký kênh YouTube để ủng hộ. Nếu nhu cầu đủ cao, chúng tôi sẽ cố gắng làm thêm nhiều video.

Video demo bên dưới sử dụng đoạn mã bên dưới:

/* * Mã Arduino UNO R4 này được phát triển bởi newbiely.vn * Mã Arduino UNO R4 này được cung cấp để sử dụng công khai, không có ràng buộc. * Để xem hướng dẫn chi tiết và sơ đồ kết nối, vui lòng truy cập: * https://newbiely.vn/tutorials/arduino-uno-r4/arduino-uno-r4-touch-sensor */ // --- Hardware Pin Definitions --- #define BUZZER_PIN 8 #define TOUCH_1_PIN 2 // Happy Birthday trigger #define TOUCH_2_PIN 3 // Jingle Bells trigger #define LED_A_PIN 4 // First indicator LED (Active-Low) #define LED_B_PIN 5 // Second indicator LED (Active-Low) // --- Musical Note Frequencies (Hz) --- #define NOTE_C4 262 #define NOTE_D4 294 #define NOTE_E4 330 #define NOTE_F4 349 #define NOTE_G4 392 #define NOTE_A4 440 #define NOTE_A5 880 #define NOTE_B4 494 #define NOTE_C5 523 #define NOTE_D5 587 #define NOTE_E5 659 // --- Melody 1: Happy Birthday --- const int happyBirthdayMelody[] = { NOTE_C4, NOTE_C4, NOTE_D4, NOTE_C4, NOTE_F4, NOTE_E4, NOTE_C4, NOTE_C4, NOTE_D4, NOTE_C4, NOTE_G4, NOTE_F4, NOTE_C4, NOTE_C4, NOTE_C5, NOTE_A4, NOTE_F4, NOTE_E4, NOTE_D4, NOTE_B4, NOTE_B4, NOTE_A4, NOTE_F4, NOTE_G4, NOTE_F4 }; const int happyBirthdayDurations[] = { 8, 8, 4, 4, 4, 2, 8, 8, 4, 4, 4, 2, 8, 8, 4, 4, 4, 4, 4, 8, 8, 4, 4, 4, 2 }; const int happyBirthdayLength = sizeof(happyBirthdayMelody) / sizeof(happyBirthdayMelody[0]); // --- Melody 2: Jingle Bells --- const int jingleBellsMelody[] = { NOTE_E4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_G4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_F4, NOTE_F4, NOTE_F4, NOTE_F4, NOTE_F4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_E4, NOTE_D4, NOTE_G4 }; const int jingleBellsDurations[] = { 4, 4, 2, 4, 4, 2, 4, 4, 4, 4, 1, 4, 4, 4, 4, 4, 4, 4, 8, 8, 4, 4, 4, 4, 2 }; const int jingleBellsLength = sizeof(jingleBellsMelody) / sizeof(jingleBellsMelody[0]); // --- Function Prototypes --- void playSong(const int melody[], const int durations[], int songLength); void updateLeds(int noteIndex, bool isQuietNote); void turnOffBothLeds(); /** * @brief Initializes peripheral pins and system communication. */ void setup() { Serial.begin(115200); pinMode(TOUCH_1_PIN, INPUT); pinMode(TOUCH_2_PIN, INPUT); pinMode(BUZZER_PIN, OUTPUT); pinMode(LED_A_PIN, OUTPUT); pinMode(LED_B_PIN, OUTPUT); // For Active-Low LEDs, setting pins HIGH turns them OFF on startup turnOffBothLeds(); Serial.println(F("Active-Low LED Music Box Jukebox Ready.")); } /** * @brief Main execution loop checking for touch sensor triggers. */ void loop() { if (digitalRead(TOUCH_1_PIN) == HIGH) { Serial.println(F("Touch 1 detected: Playing Happy Birthday...")); playSong(happyBirthdayMelody, happyBirthdayDurations, happyBirthdayLength); } else if (digitalRead(TOUCH_2_PIN) == HIGH) { Serial.println(F("Touch 2 detected: Playing Jingle Bells...")); playSong(jingleBellsMelody, jingleBellsDurations, jingleBellsLength); } } /** * @brief Iterates through the provided melody arrays to play the full song with LED sync. * @param melody Array containing note frequencies. * @param durations Array containing corresponding note lengths. * @param songLength Total number of notes in the song. */ void playSong(const int melody[], const int durations[], int songLength) { for (int thisNote = 0; thisNote < songLength; thisNote++) { bool isQuietNote = (melody[thisNote] == 0); int noteDuration = 1000 / durations[thisNote]; // Trigger Active-Low LED effect updateLeds(thisNote, isQuietNote); tone(BUZZER_PIN, melody[thisNote], noteDuration); int pauseBetweenNotes = noteDuration * 1.30; delay(pauseBetweenNotes); noTone(BUZZER_PIN); turnOffBothLeds(); // Drive both pins HIGH to turn off the LEDs } Serial.println(F("Song finished. LEDs reset to standby (HIGH).")); } /** * @brief Logic switch designed for Active-Low configurations (LOW = ON, HIGH = OFF). * @param noteIndex Current position in the melody array. * @param isQuietNote Evaluation flag determining if the note produces no sound. */ void updateLeds(int noteIndex, bool isQuietNote) { if (isQuietNote) { turnOffBothLeds(); return; } // Alternating Active-Low pattern if (noteIndex % 2 == 0) { digitalWrite(LED_A_PIN, LOW); // LED A turns ON digitalWrite(LED_B_PIN, HIGH); // LED B turns OFF } else { digitalWrite(LED_A_PIN, HIGH); // LED A turns OFF digitalWrite(LED_B_PIN, LOW); // LED B turns ON } } /** * @brief Forces both LED control pins to HIGH, turning them OFF in Active-Low logic. */ void turnOffBothLeds() { digitalWrite(LED_A_PIN, HIGH); digitalWrite(LED_B_PIN, HIGH); }

Bài hướng dẫn liên quan