Nota

Ciao, benvenuto nella Community di SunFounder per appassionati di Raspberry Pi, Arduino e ESP32 su Facebook! Approfondisci Raspberry Pi, Arduino ed ESP32 insieme ad altri appassionati.

Perché unirsi?

  • Supporto Esperto: Risolvi problemi post-vendita e sfide tecniche con l’aiuto della nostra comunità e del nostro team.

  • Impara e Condividi: Scambia suggerimenti e tutorial per migliorare le tue competenze.

  • Anteprime Esclusive: Accedi in anteprima agli annunci dei nuovi prodotti e alle anticipazioni.

  • Sconti Speciali: Godi di sconti esclusivi sui nostri prodotti più recenti.

  • Promozioni e Giveaway Festivi: Partecipa a giveaway e promozioni festive.

👉 Pronto a esplorare e creare con noi? Clicca su [Qui] e unisciti oggi!

MPR121

Panoramica

In questa lezione, imparerai a usare il MPR121. È una buona opzione quando vuoi aggiungere molti interruttori touch al tuo progetto. L’elettrodo del MPR121 può essere esteso con un conduttore. Se colleghi un filo a una banana, puoi trasformare la banana in un interruttore touch, realizzando così progetti come il pianoforte di frutta.

Componenti Necessari

In questo progetto, abbiamo bisogno dei seguenti componenti.

È sicuramente conveniente acquistare un kit completo, ecco il link:

Nome

ELEMENTI IN QUESTO KIT

LINK

Elite Explorer Kit

300+

Elite Explorer Kit

Puoi anche acquistarli separatamente dai link seguenti.

INTRODUZIONE DEI COMPONENTI

LINK PER L’ACQUISTO

Arduino Uno R4 WiFi

-

Breadboard

ACQUISTA

Cavi Jumper

ACQUISTA

MPR121

-

Cablaggio

In questo esempio, inseriamo il MPR121 nella breadboard. Collega il GND del MPR121 a GND, 3.3V a 3V3, IRQ al pin digitale 2, SCL al pin SCL(A5) e SDA al pin SDA(A4). Ci sono 12 elettrodi per il rilevamento touch.

Nota

Il MPR121 è alimentato a 3.3V, non a 5V.

../_images/23-mpr121_bb.png

Schema Elettrico

../_images/23_mpr121_schematic.png

Codice

Nota

  • Puoi aprire direttamente il file 23-mpr121.ino nel percorso elite-explorer-kit-main\basic_project\23-mpr121.

  • La libreria Adafruit MPR121 viene utilizzata qui, puoi installarla dal Library Manager.

    ../_images/22_mpr121_lib.png
23-mpr121.ino
 1/*
 2  This Arduino code interfaces with the MPR121 Capacitive Touch Sensor 
 3  using the Adafruit_MPR121 library. It initializes the sensor, reads 
 4  the touch status of up to 12 pads, and prints messages to the Serial 
 5  Monitor indicating when a pad is touched or released.
 6  
 7  Board: Arduino Uno R4
 8  Component: MPR121
 9  Library: https://github.com/adafruit/Adafruit_MPR121 (Adafruit_MPR121 by Adafruit)
10*/
11
12#include <Wire.h>
13#include "Adafruit_MPR121.h"
14
15#ifndef _BV
16#define _BV(bit) (1 << (bit)) 
17#endif
18
19// You can have up to 4 on one i2c bus but one is enough for testing!
20Adafruit_MPR121 cap = Adafruit_MPR121();
21
22// Keeps track of the last pins touched
23// so we know when buttons are 'released'
24uint16_t lasttouched = 0;
25uint16_t currtouched = 0;
26
27void setup() {
28  Serial.begin(9600);
29
30  while (!Serial) { // needed to keep leonardo/micro from starting too fast!
31    delay(10);
32  }
33  
34  Serial.println("Adafruit MPR121 Capacitive Touch sensor test"); 
35  
36  // Default address is 0x5A, if tied to 3.3V its 0x5B
37  // If tied to SDA its 0x5C and if SCL then 0x5D
38  if (!cap.begin(0x5A)) {
39    Serial.println("MPR121 not found, check wiring?");
40    while (1);
41  }
42  Serial.println("MPR121 found!");
43  cap.setAutoconfig(true);
44}
45
46void loop() {
47  // Get the currently touched pads
48  currtouched = cap.touched();
49  
50  for (uint8_t i=0; i<12; i++) {
51    // it if *is* touched and *wasn't* touched before, alert!
52    if ((currtouched & _BV(i)) && !(lasttouched & _BV(i)) ) {
53      Serial.print(i); Serial.println(" touched");
54    }
55    // if it *was* touched and now *isn't*, alert!
56    if (!(currtouched & _BV(i)) && (lasttouched & _BV(i)) ) {
57      Serial.print(i); Serial.println(" released");
58    }
59  }
60
61  // reset our state
62  lasttouched = currtouched;
63
64  // comment out this line for detailed data from the sensor!
65  return;
66  
67  // debugging info, what
68  Serial.print("\t\t\t\t\t\t\t\t\t\t\t\t\t 0x"); Serial.println(cap.touched(), HEX);
69  Serial.print("Filt: ");
70  for (uint8_t i=0; i<12; i++) {
71    Serial.print(cap.filteredData(i)); Serial.print("\t");
72  }
73  Serial.println();
74  Serial.print("Base: ");
75  for (uint8_t i=0; i<12; i++) {
76    Serial.print(cap.baselineData(i)); Serial.print("\t");
77  }
78  Serial.println();
79  
80  // put a delay so it isn't overwhelming
81  delay(100);
82}

Dopo aver caricato il codice sulla scheda UNO, lo stato di tocco dei pin MPR121 «1» e «0» verrà registrato in un array booleano a 12 bit. Questo array verrà quindi stampato sul monitor seriale.

Analisi del Codice

Questo codice facilita la comunicazione e il funzionamento del sensore touch MPR121. Può rilevare lo stato degli elettrodi touch e stampare informazioni sugli elettrodi toccati o rilasciati sull’interfaccia seriale. Se sono necessari dati dettagliati del sensore, il codice pertinente può essere decommentato.

Ecco un’analisi del codice:

  1. Importa Librerie:

    #include <Wire.h>
    #include "Adafruit_MPR121.h"
    
    • Wire.h: Utilizzata per la comunicazione I2C.

    • Adafruit_MPR121.h: La libreria Adafruit per il funzionamento del sensore touch MPR121.

  2. Definisci la Macro _BV:

    #ifndef _BV
    #define _BV(bit) (1 << (bit))
    #endif
    

    _BV(bit) definisce una macro che converte un dato bit nel valore binario corrispondente, simile a 1 << bit.

  3. Inizializza l’istanza della classe Adafruit_MPR121:

    Adafruit_MPR121 cap = Adafruit_MPR121();
    

    Crea un’istanza della classe Adafruit_MPR121 chiamata cap. L’oggetto cap verrà utilizzato per comunicare e operare con il sensore touch MPR121.

  4. Funzione setup():

    Inizializza la comunicazione seriale a un baud rate di 9600. poi inizializza il sensore touch MPR121 con l’indirizzo I2C predefinito di 0x5A. Se l’inizializzazione fallisce, stampa un messaggio di errore ed entra in un ciclo infinito.

    void setup() {
        Serial.begin(9600);
    
        while (!Serial) { // necessario per evitare che leonardo/micro partano troppo velocemente!
            delay(10);
        }
    
        Serial.println("Adafruit MPR121 Capacitive Touch sensor test");
    
        // L'indirizzo predefinito è 0x5A, se collegato a 3.3V è 0x5B
        // Se collegato a SDA è 0x5C e se a SCL è 0x5D
        if (!cap.begin(0x5A)) {
            Serial.println("MPR121 not found, check wiring?");
            while (1);
        }
        Serial.println("MPR121 found!");
    }
    
  5. Funzione loop():

    • Ottieni lo stato attuale del tocco, restituito come intero a 16 bit.

      currtouched = cap.touched();
      
    • Itera attraverso lo stato di 12 elettrodi (numerati da 0 a 11).

      for (uint8_t i=0; i<12; i++) {
          // se *è* toccato e *non era* toccato prima, avvisa!
          if ((currtouched & _BV(i)) && !(lasttouched & _BV(i)) ) {
              Serial.print(i); Serial.println(" touched");
          }
          // se *era* toccato e ora *non è*, avvisa!
          if (!(currtouched & _BV(i)) && (lasttouched & _BV(i)) ) {
              Serial.print(i); Serial.println(" released");
          }
      }
      
      • Se un elettrodo è toccato e non era toccato prima, stampa «x toccato,» dove x è il numero dell’elettrodo.

      • Se un elettrodo era toccato prima ma non è toccato ora, stampa «x rilasciato.»

    • Aggiorna lasttouched per memorizzare lo stato attuale del tocco per il confronto nella prossima iterazione.

      lasttouched = currtouched;
      
    • Informazioni di Debug (Sezione Opzionale):

      // informazioni di debug, cosa
      Serial.print("\t\t\t\t\t\t\t\t\t\t\t\t\t 0x"); Serial.println(cap.touched(), HEX);
      Serial.print("Filt: ");
      for (uint8_t i=0; i<12; i++) {
          Serial.print(cap.filteredData(i)); Serial.print("\t");
      }
      Serial.println();
      Serial.print("Base: ");
      for (uint8_t i=0; i<12; i++) {
          Serial.print(cap.baselineData(i)); Serial.print("\t");
      }
      Serial.println();
      
      // metti un ritardo per non sovraccaricare
      delay(100);