Différences entre versions de « Projets:ESP32 BLE variateur ampoule Led 220V »

De wikilab
Ligne 79 : Ligne 79 :
 
Code final pour recevoir les données reçues en BLE (Bluetooth Low Energy). Selon l'appareil utilisé, vous aurez besoin de personaliser le code.
 
Code final pour recevoir les données reçues en BLE (Bluetooth Low Energy). Selon l'appareil utilisé, vous aurez besoin de personaliser le code.
  
<code c++>
+
<code>
 
//triac related.Si l'ampoule s'allume au repos par erreur baisser un peu la valeur de 10500 dans le mapping
 
//triac related.Si l'ampoule s'allume au repos par erreur baisser un peu la valeur de 10500 dans le mapping
 
int mydelay = 0;
 
int mydelay = 0;

Version du 11 janvier 2021 à 11:35

Description du projet

L'objectif du projet est de fabriquer un variateur de lumière pour contrôler une ampoule LED OSRAM 220V avec un potentiomètre (pour tester) puis avec des données reçues en Bluetooth Low Energy

Cahier des charges

  • pouvoir faire varier la lumière de manière fluide
  • doit fonctionner avec les valeurs reçues en BLE

Analyse de l'existant

Equipe (Porteur de projet et contributeurs)

  • Porteurs du projet :Marie
  • Concepteurs/contributeurs :Delphine, Christian, Jean-jacques
  • Animateur (coordinateur du projet) :Delphine
  • Fabmanager référent:Delphine
  • Responsable de documentation:Delphine

Matériel nécessaire

Outils nécessaires

  • fer à souder
  • étain
  • fils à souder
  • pince coupante
  • pince à dénuder
  • cutter (pour couper un bout de perfboard)

Coût

Délai estimé

  • entre 4 et 6 heures

Fichiers source

Schéma électronique Kicad

Télécharger les sources du projet Kicad

Circuit esp32 variateur ampoule BLE.png

Etapes de fabrication pas à pas

Conception du circuit électronique

Explications

On redresse le courant avec les 4 diodes. On obtient une impulsion de synchronisation qui va servir de point de départ pour le délay de max 10ms (défini par le potentiomètre ou les données reçues en BLE). Une fois passé ce délai le triac s'enclenche jusqu'à la fin de la demi alternance (10ms) car le secteur donne une alternance de 20ms. Le triac attend une demi alternance (période definie par le potentiomètre), avant de s'enclencher pendant le reste de l'alternance (période).

Le potentiomètre va dimmer (faire varier) la lumière. Plus sa valeur est petite plus la lumière est forte.

Il faudra mettre du fil bien isolé pour le circuit 220 V.

Circuit électronique pour perfboard

Réaliser le circuit suivant sur de la plaque de prototypage à trou (perfboard)

Schema perfboard ESP32 DEV TOOL KIT AC DIMMER OK2.png


Programmation

Code final pour recevoir les données reçues en BLE (Bluetooth Low Energy). Selon l'appareil utilisé, vous aurez besoin de personaliser le code.

//triac related.Si l'ampoule s'allume au repos par erreur baisser un peu la valeur de 10500 dans le mapping int mydelay = 0; int myvalue = 0; int timer_step = 2; hw_timer_t *timer = NULL;

int counterA = 0; int counterB = 0; int counterC = 0; int counterD = 0;


const int interruption_pin = 21; const int pot_pin = 34;


//////////////////////////////end triac related

/**

  A BLE client example that is rich in capabilities.
  There is a lot new capabilities implemented.
  author unknown
  updated by chegewara
  • /

//used with ESP32 and library ESP32

//ouvrir la macro openDaqCalc dans Calc libreoffice >Outils>Macro>executer la macro>menu gauche oppenDaqCalc>fichier racine-menu droite: Main //ajuster la plage de données au besoin : clic droit sur diagram>éditer X2>Plages de données type: $Feuille1.$A$1:$E$500 (feuille1: de colonne A ligne 1 à colonne E jusqu'à ligne 500 //clic sur connect //clic sur clear pour intégrer les données dans le diagram //https://electroniqueamateur.blogspot.com/2014/10/transmettre-les-donnees-darduino-vers.html

  1. include "BLEDevice.h"

//#include "BLEScan.h"

// The remote service we wish to connect to. static BLEUUID serviceUUID("0000aa40-0000-1000-8000-00805f9b34fb"); // The characteristic of the remote service we are interested in. static BLEUUID charUUID("0000aa41-0000-1000-8000-00805f9b34fb");

static boolean doConnect = false; static boolean connected = false; static boolean doScan = false; static BLERemoteCharacteristic* pRemoteCharacteristic; static BLEAdvertisedDevice* myDevice;

int perifit[] = {0, 0, 0, 0};

int w; int x; int y; int z; int pp; int ps;

//LED

const int ledPinPS = 5;//was 5 const int ledPinPP = 18;//was 18 int ledValuePS = 0; int ledValuePP = 0; const int freq = 5000; const int ledChannelPS = 0; const int resolutionPS = 8; const int ledChannelPP = 1; const int resolutionPP = 8;

///triac related//////////// void IRAM_ATTR rising_edge_isr() {

 if (timer_step == 2) {
   // No need to read anything : it is a rising edge
   // We just need to configure a timer interrupt
   // with current value of mydelay
   timer_step = 0;
   timerAlarmWrite(timer, myvalue, false);
   timerAlarmEnable(timer);
   timerRestart(timer);
   counterA = counterA + 1;
 } else {
   counterD = counterD + 1;
 }

}

void IRAM_ATTR timer_isr() {

 if (timer_step == 0) {
   // Activate triac
   digitalWrite(16, HIGH);
   timer_step = 1;
   // Configure the timer again to end the pulse
   // in 100 us
   timerAlarmWrite(timer, 100, false);
   //timerAlarmWrite(timer, 500,false);
   timerRestart(timer);
   timerAlarmEnable(timer);
   counterB = counterB + 1;
 } else if (timer_step == 1) {
   // End the pulse
   digitalWrite(16, LOW);
   timerStop(timer);
   counterC = counterC + 1;
   timer_step = 2;
 }

}

//////////End triac related

static void notifyCallback(

 BLERemoteCharacteristic* pBLERemoteCharacteristic,
 uint8_t* pData,
 size_t length,
 bool isNotify) {
 /*
   Serial.print("Notify callback for characteristic ");
   Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
   Serial.print(" of data length ");
   Serial.println(length);
 */
 /*
   Serial.print("data: ");
   Serial.println((char*)pData);
   //  Serial.print("data xxxxxxxxx: ");
 */

/*

 for (int i = 0; i < length; i++) {
   //Serial.println(char(pData[i]));
   //Serial.print("v");
   //Serial.print(i);
   //Serial.print(":");
   perifit[i] = int(char(pData[i]));//on prend le caractere, on le convertit en entier. le fait de le convertir en charactere a partir de 128 ca devient -128 jusqu'à 255 qui devient -1
   //Serial.println(perifit[i]);
   w = perifit[0];
   x = perifit[1];
   y = perifit[2];
   z = perifit[3];
  
       Serial.print("DATA,TIME,");  // envoi du temps et la mesure à Excel
       // Serial.println(ValeurMesuree);
       //visualiser les datas dans le traceur série
       Serial.print(w);
       Serial.print(", ");
       Serial.print(x);
       Serial.print(", ");
       Serial.print(y);
       Serial.print(", ");
       Serial.print(z);
       Serial.println();
   
 }
 */
 w = pData[0];//w = perifit[0];
 x = pData[1];
 y = pData[2];
 z = pData[3];
 ps = x + (256 * w);
 pp = z + (256 * y);
 myvalue = map(ps, 180, 2700, 10500, 1500);

}

class MyClientCallback : public BLEClientCallbacks {

   void onConnect(BLEClient* pclient) {
   }
   void onDisconnect(BLEClient* pclient) {
     connected = false;
     Serial.println("onDisconnect");
   }

};

bool connectToServer() {

 Serial.print("Forming a connection to ");
 Serial.println(myDevice->getAddress().toString().c_str());
 BLEClient*  pClient  = BLEDevice::createClient();
 Serial.println(" - Created client");
 pClient->setClientCallbacks(new MyClientCallback());
 // Connect to the remove BLE Server.
 pClient->connect(myDevice);  // if you pass BLEAdvertisedDevice instead of address, it will be recognized type of peer device address (public or private)
 Serial.println(" - Connected to server");
 // Obtain a reference to the service we are after in the remote BLE server.
 BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
 if (pRemoteService == nullptr) {
   Serial.print("Failed to find our service UUID: ");
   Serial.println(serviceUUID.toString().c_str());
   pClient->disconnect();
   return false;
 }
 Serial.println(" - Found our service");


 // Obtain a reference to the characteristic in the service of the remote BLE server.
 pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
 if (pRemoteCharacteristic == nullptr) {
   Serial.print("Failed to find our characteristic UUID: ");
   Serial.println(charUUID.toString().c_str());
   pClient->disconnect();
   return false;
 }
 Serial.println(" - Found our characteristic");
 // Read the value of the characteristic.
 if (pRemoteCharacteristic->canRead()) {
   std::string value = pRemoteCharacteristic->readValue();
   Serial.print("The characteristic value was: ");
   //Serial.println(value.c_str());
   Serial.println(value.c_str());
 }
 if (pRemoteCharacteristic->canNotify())
   pRemoteCharacteristic->registerForNotify(notifyCallback);
 connected = true;
 return 0;//not necessary before but added when happened this error whereas no change was made in the code: control reaches end of non-void function [-Werror=return-type]

} /**

  Scan for BLE servers and find the first one that advertises the service we are looking for.
  • /

class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {

   /**
       Called for each advertising BLE server.
   */
   void onResult(BLEAdvertisedDevice advertisedDevice) {
     Serial.print("BLE Advertised Device found: ");
     Serial.println(advertisedDevice.toString().c_str());
     // We have found a device, let us now see if it contains the service we are looking for.
     if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) {
       BLEDevice::getScan()->stop();
       myDevice = new BLEAdvertisedDevice(advertisedDevice);
       doConnect = true;
       doScan = true;
     } // Found our server
   } // onResult

}; // MyAdvertisedDeviceCallbacks

/////////For ESP32:https://lastminuteengineers.com/handling-esp32-gpio-interrupts-tutorial/


void setup() {

 //////////triac related/////////////
 Serial.begin(115200);
 Serial.println("init setup triac");
 // Zero crossing detection
 // Rising edge is enough : it should generate 100 interrupts per second.
 pinMode(21, INPUT_PULLUP);
 attachInterrupt(21, rising_edge_isr, RISING);
 // Output configuration
 pinMode(16, OUTPUT);
 // Timer prescaler configuration
 // with a 80 prescaler value, timer value is
 // directly expressed in microseconds
 timer = timerBegin(0, 80, true); // croissant
 timerStop(timer);
 timerAttachInterrupt(timer, &timer_isr, true);
 //timerAttachInterrupt(timer, &timer_isr, false);
 ///end of triac related
 Serial.println("Starting Arduino BLE Client application...");
 BLEDevice::init("");
 // Retrieve a Scanner and set the callback we want to use to be informed when we
 // have detected a new device.  Specify that we want active scanning and start the
 // scan to run for 5 seconds.
 BLEScan* pBLEScan = BLEDevice::getScan();
 pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
 pBLEScan->setInterval(1349);
 pBLEScan->setWindow(449);
 pBLEScan->setActiveScan(true);
 pBLEScan->start(5, false);
 Serial.println("CLEARDATA");  // on efface les données déjà présentes, s'il y a lieu
 Serial.println("LABEL,Temps,W,X,Y,Z");
 // configure LED PWM functionalitites
 // ledcSetup(ledChannelPS, freq, resolutionPS);
 // ledcSetup(ledChannelPP, freq, resolutionPP);
 // attach the channel to the GPIO to be controlled
 // ledcAttachPin(ledPinPS, ledChannelPS);
 // ledcAttachPin(ledPinPP, ledChannelPP);
 //triac related
 /*
     Port registers allow for lower-level and faster manipulation of the i/o pins of the microcontroller on an Arduino board.
     The chips used on the Arduino board (the ATmega8 and ATmega168) have three ports:
     -B (digital pin 8 to 13)
     -C (analog input pins)
     -D (digital pins 0 to 7)
   //All Arduino (Atmega) digital pins are inputs when you begin...
 */
 //A changer !!! à actualiser pour ESP32
 // PCICR |= (1 << PCIE0);    //enable PCMSK0 scan
 // PCMSK0 |= (1 << PCINT0);  //Set pin D21 (nano:D8) trigger an interrupt on state change. Input from optocoupler


} // End of setup.


// This is the Arduino main loop function. void loop() {


 // If the flag "doConnect" is true then we have scanned for and found the desired
 // BLE Server with which we wish to connect.  Now we connect to it.  Once we are
 // connected we set the connected flag to be true.
 if (doConnect == true) {
   if (connectToServer()) {
     Serial.println("We are now connected to the BLE Server.");
   } else {
     Serial.println("We have failed to connect to the server; there is nothin more we will do.");
   }
   doConnect = false;
 }
 // If we are connected to a peer BLE Server, update the characteristic each time we are reached
 // with the current time since boot.
 Serial.println("coucou");
 if (connected) {
   String newValue = "Time since boot: " + String(millis() / 1000);
   Serial.println("Setting new characteristic value to \"" + newValue + "\"");
   // Set the characteristic's value to be the array of bytes that is actually a string.
   // pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length());
   pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length());
   //LED (à enlever pour le triac)
   //la valeur du capteur perifit sera utilisé pour le delay du triac
   //  ledValuePS = map(ps, 180, 2500, 0, 255);
   //  ledValuePP = map(pp, 180, 2500, 0, 255);
   /*
     Serial.print ("x : ");
      Serial.println (x);
      Serial.print ("led : ");
      Serial.println (ledValuePS);
   */
   //  ledcWrite(ledChannelPS, ledValuePS);// turn on the LED mapped on X value (périnée profond)
   //analogWrite (ledPinPS, ledValuePS);
   //  ledcWrite(ledChannelPP, ledValuePP);
   ///fin de la partie à enlever
   //début de la partie à ajouter/actualiser (done)
   //Read the value of the perifit and map it from 10 to 10.000 us. AC frequency is 50Hz, so the period is 20ms. We want to control the power
   //of each half period, so the maximum is 10ms or 10.000us. In my case, I've mapped it up to 7.200us since 10.000 was too much
   // ledValuePS = map(ps,0,2500,7200,10);


   // myvalue = map(x, 180, 250, 7200, 10);
   /*
     Serial.println(myvalue);
     Serial.print("counterA :");
     Serial.println(counterA);
     Serial.print("counterB :");
     Serial.println(counterB);
     Serial.print("counterC :");
     Serial.println(counterC);
     Serial.print("counterD :");
     Serial.println(counterD);
   */
   //fin de la partie à actualiser
 } else if (doScan) {
   BLEDevice::getScan()->start(0);  // this is just eample to start scan after disconnect, most likely there is better way to do it in arduino
 }
 delay(1000); // Delay a second between loops.

} // End of loop

Durée de fabrication du prototype final

Journal de bord