Outils pour utilisateurs

Outils du site


issue106:arduino

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
Prochaine révision
Révision précédente
issue106:arduino [2016/03/06 17:06] d52frissue106:arduino [2016/04/08 16:30] (Version actuelle) – créée andre_domenech
Ligne 1: Ligne 1:
-=== **!!ATTENTION lors du scribagerechercher et éliminer les <nowiki> et </nowiki> !!** ===+**WARNINGThis month we’re heading into the big league with controlling household voltage devices. It should go without sayingbut I’ll say it anyway, you must make sure your 110/240V devices are unplugged before chopping cables, and double-check your wiring before you do put that plug back into the wall outlet.**
  
 +ATTENTION : ce mois-ci, nous passons en première division en pilotant des appareils sous tension domestique. Il va sans dire, mais je le dis quand même, que vous devez vous assurer que vos appareils sont débranchés avant de couper des câbles et vérifier deux fois votre câblage avant de remettre la fiche dans la prise murale.
  
-**Sowith the basic plan thought out, it’s now time to actually pick up some components and get building.+**In previous articlesI used an LCD screen whichwhile it worked, would need about a dozen wires and a potentiometer to control the screen brightness (see photo, top board). This time, I’ve managed to get some much simpler LCD screens that require only four wires (same photo, bottom board). The wires are VCC, GND, SDA and SCL. These should be marked on your Arduino, but on UNO boards, I believe it’s A4 and A5. On my MEGA, it’s 20 and 21 and they’re marked as such. But you need to put both those lines through a 4.7K resistor from 5V.
  
-Temperature+These newer LCD screens are I2C which means they have a little controller board on the back. It also means they require a newer LCD library (https://bitbucket.org/fmalpartida/new-liquidcrystal) in the code.
  
-Temperature sensing is highly important to this as it will determine when the heat mat should be switched on or off.+Before adding LCD code, we need to do a scan of the LCD screen to get its I2C address. Different models have different addresses. So, grab the code from: http://arduino.cc/playground/Main/I2cScanner and run it to see your LCD I2C address in the serial monitor. Mine is 0x3F.**
  
-Rather than use the old DHT11 moduleI’m using a DHT22 module this timeThese are more sensitive and give a more precise readingI’m also going to use an Arduino MEGA for this project.**+Dans les articles précédentsj'ai utilisé un écran LCD qui, quand il était en marche, nécessitait une douzaine de fils et un potentiomètre pour contrôler la luminosité (voir la carte en haut sur la photo)Cette fois, je me suis arrangé pour trouver des écrans LCD plus simples, qui n'utilisent que 4 fils (même photo, la carte du bas)Les fils sont VCC, GND, SDA et SCL. Ces derniers devraient être identifiés sur votre Arduino ; mais, sur les cartes UNO, je crois que c'est A4 et A5. Sur mon MEGA, c'est 20 et 21 et ils sont marqués ainsi. Mais vous devez raccorder ces deux lignes au 5V à travers une résistance de 4,7 k.
  
-Maintenant que nous avons réfléchi au plan de base, il est temps de choisir quelques composants pour commencer le montage.+Ces nouveaux écrans LCD sont I2C ce qui signifie qu'ils ont une petite carte de pilotage au dos. Cela signifie aussi qu'ils ont besoin d'une nouvelle bibliothèque (https://bitbucket.org/fmalpartida/new-liquidcrystal) dans le code.
  
-Température+Avant d'ajouter le code du LCD, nous devons faire un scan de l'écran LCD pour acquérir son adresse I2C. Des modèles différents ont des adresses différentes. Aussi, récupérez le code depuis : http://arduino.cc/playground/Main/I2cScanner et lancez-le pour voir l'adresse I2C de votre LCD sur le moniteur série. La mienne est 0x3F.
  
-La détection de température est très importante dans notre cas car elle déterminera quand la couverture chauffante doit être sous ou hors tension.+**LCD Code
  
-Plutôt que d'utiliser le vieux module DHT11, cette fois, j'utilise un module DHT22. Il est plus sensible et donne une meilleure lecture. Je vais aussi utiliser un Arduino MEGA pour ce projet. +I need to include that new library:
  
-**Build 1+#include <LiquidCrystal_I2C.h>
  
-Ive connected the DHT22 module using the three pins. One wire to +5Vone to ground, and the other to pin 6 on the MEGA.+Define various pins (I2C stuff that you shouldnt need to touch)but insert the correct I2C address:
  
-Other than the serial monitor, theres no way to see the temperature. I prefer visuals, so I’m going to hook up the ESP8266 (WiFi) module and send my results to ThingSpeak. The ESP8266 uses five of the eight pins that it has. One for +3.3V (NOT +5V or you will fry it) shown as a yellow wire in the diagram, one for the ground (black wire), one each for RX and TX (green and blue) and a reset pin (white wire) which also goes to +3.3V+#define I2C_ADDR    0x3F 
 +<nowiki>// you shouldnt need to touch the pin numbers below</nowiki>
  
-That’s the basic circuit for this first part.+#define BACKLIGHT_PIN     3 
 +#define En_pin 
 +#define Rw_pin 
 +#define Rs_pin 
 +#define D4_pin 
 +#define D5_pin 
 +#define D6_pin 
 +#define D7_pin  7
  
-The code for the DHT22 is pretty straightforwardso we’ll look at that next. The ESP8266 is more trickyand is quite often prone to not responding. If you think your code is rightand the ESP8266 isn’t respondingtry unplugging/plugging the two 3.3V wires from the breadboard. I find that gives a good reset to the module. When the code is running you’ll see the RX/TX lights flash on the Arduino and at that same time you should see a blue light on the ESP8266 flash.**+LiquidCrystal_I2C  lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);
  
-Assemblage n°1+In my setup, I initialise the screen as 16X2, turn on the backlight, print a message, and use a delay to allow it to be read.**
  
-J'ai connecté le module DHT22 en utilisant trois picots. Un fil au +5V, un à la masse et l'autre au picot 6 de MEGA.+Code LCD
  
-À part avec le moniteur série, il n'y a pas moyen de voir la température. Je préfère les visuels, aussi je vais brancher le module WiFi ESP8366 et envoyer mes résultats à ThingSpeak. Le ESP8266 utilise 5 des ses 8 picots. Un pour le +3,3V(PAS +5V ou vous le grillez),le fil jaune visible sur le schéma, un pour la masse (fil noir), un pour chaque RX et TX (vert et bleu) et un fil de r.a.z. (fil blanc) qui va aussi au + 3,3V.+J'ai besoin d'ajouter la nouvelle bibliothèque :
  
-C'est le circuit de base de la première partie.+#include <LiquidCrystal_I2C.h>
  
-Le code pour le DHT22 est assez évident ; aussi, nous le verrons au paragraphe suivant. Le ESP8266 est plus difficile et il lui arrive souvent de ne pas répondre. Si vous pensez que le code est bon et que le ESP8266 ne répond pas, essayez de débrancher les deux fils 3,3V de la plaque d'essais. Je trouve que ça fait une bonne r.a.z. du module. Quand le code tourne, vous verrez les voyants RX/TX qui flashent sur l'Arduino et, en même temps, une lampe bleue qui flashe sur le ESP8266.+Définissez plusieurs picots (des éléments I2C que vous n'aurez pas besoin de modifier)mais insérez la bonne adresse I2C :
  
-**Code+#define I2C_ADDR    0x3F 
 +<nowiki>// vous n'avez pas besoin de toucher aux numéros de picots ci-dessous</nowiki>
  
-I’ll be adding all my code for this project to this Github gist: https://gist.github.com/ronnietucker/7fc62df161107116cf93+#define BACKLIGHT_PIN     3 
 +#define En_pin 
 +#define Rw_pin 
 +#define Rs_pin 
 +#define D4_pin 
 +#define D5_pin 
 +#define D6_pin 
 +#define D7_pin  7
  
-By the time you read thisthere will be many revisions of the code added to the gistbut this is revision 2 that I’m discussing here.+LiquidCrystal_I2C  lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);
  
-For the DHT22I’m using the two libraries from here: http://playground.arduino.cc/Main/DHTLib+Dans mon paramétragej'initialise l'écran en 16x2, allume le rétro-éclairage, affiche un message et mets un tempo pour qu'on ait le temps de le lire.
  
-You’ll need to copy/paste the text for the two files to new filesand name them accordingly. All the instructions for doing this are at that link.+**lcd.begin (16,2);   
 +  lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE); 
  
-I start by including the DHT library and define the pin for the DHT22I then define my wifi SSID and password.**+lcd.setBacklight(HIGH);
  
-Code+lcd.home();  
  
-J'ajouerai tout mon code pour ce projet à ce gist Github : https://gist.github.com/ronnietucker/7fc62df161107116cf93+lcd.print("Screen OK");  
  
-Au moment où vous lisez ceci, il y aura eu beaucoup de révisions du code ajoutées sur gist, mais c'est la revision 2 que je présente ici.+delay(2000);
  
-Pour le DHT22, j'utilise deux bibliothèques d'ici : http://playground.arduino.cc/Main/DHTLib+Most of those commands are pretty self explanatory.
  
-Vous aurez besoin de copier/coller le texte des deux fichiers dans des nouveaux fichiers et de les nommer respectivementToutes les instructions pour le faire sont sur le lien.+I now have my temperature, humidity, and some of my serial monitor outputs going to the LCD screen using the lcd.print() command.**
  
-Je commence par inclure la bibliothèque DHT   et définir les picots pour le DHT22Puisje définis le SSID et le mot de passe de mon WiFi.+lcd.begin (16,2);   
 +  lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE); 
  
-**Now we’re on to the main setupI use two serial begin commands:+lcd.setBacklight(HIGH);
  
-Serial.begin(115200);+lcd.home();  
  
-Serial2.begin(9600);+lcd.print("Screen OK");  
  
-The Serial.begin is for the DHT22, so that I could get results to the serial monitor before I added the wifi module. The Serial2.begin is for the wifi module. If you’re using an Arduino other than the Mega, then you may have only one serial RX/TX and need to modify the code accordingly. Now I set up the ESP8266.+delay(2000);
  
-<nowiki>//WiFi setup  +La plupart de ces commandes sont explicites.
-Serial2.println("AT"); +
-      +
-Serial.println("AT sent - checking..."); +
-       +
-delay(5000); +
-       +
-char okcheck[]="OK"; +
-       +
-if(Serial2.find(okcheck)){ +
-    Serial.println("OK, found. Connecting"); +
-    connectWiFi(); +
-    Serial.println("Yay! Should be connected now.");+
-else{ +
-    Serial.println("NOT CONNECTED TO WIFI"); +
-}</nowiki>**+
  
-Maintenant, nous en venons au réglage principal. J'utilise des commandes serial begin :+Maintenant, j'ai la température, l'humidité et quelques-unes des sorties de mon moniteur série qui vont vers l'écran LCD en utilisant la commande lcd.print().
  
-Serial.begin(115200);+**lcd.setCursor(0,2);
  
-Serial2.begin(9600);+lcd.print("Checking... ");
  
-Le Serial.begin sont pour le DHT22 ; de cette façon, j'obtenais les résultats sur le moniteur série avant que j'ajoute le module Wifi. Le Serial2.begin est pour le module WiFi. Si vous utilisez un autre Arduino que le Mega, vous n'aurez alors qu'un seul RX/TX et vous aurez besoin de modifier le code en conséquence. Maintenant, je paramètre le ESP8266+lcd.setCursor() is for placing the text at a particular position on the screen.
  
-<nowiki>//WiFi setup  +NOTE: if you don’t see anything on your screen on first runtry turning the potentiometer on the back of the LCD screen to adjust the brightness of the screen.**
-Serial2.println("AT"); +
-      +
-Serial.println("AT sent - checking..."); +
-       +
-delay(5000); +
-       +
-char okcheck[]="OK"; +
-       +
-if(Serial2.find(okcheck)){ +
-    Serial.println("OKfound. Connecting"); +
-    connectWiFi(); +
-    Serial.println("Yay! Should be connected now.");+
-else{ +
-    Serial.println("NOT CONNECTED TO WIFI"); +
-}</nowiki>+
  
-**When using Serial2, I’m talking to the ESP8266When using just Serial, I’m talking (or printing to) the serial monitor. I’m sending the command AT to the ESP8266 and printing text to the serial monitor to show me what is happening in the background. I wait five secondsthen run a Serial2.find to see if I got a reply of OK. If I did, then I’m going to try and connect (by jumping to connectWiFi(). If not, then I display the text to say ‘not connected’.+lcd.setCursor(0,2);
  
-Connecting to a wifi router needs the SSID, password and several commands.+lcd.print("Checking... ");
  
-boolean connectWiFi(){ +lcd.setCursor() sert à positionner le texte à un endroit précis de l'écran.
-  Serial2.println("AT+CWMODE=1")+
-  delay(2000); +
-  String cmd="AT+CWJAP=\""; +
-  <nowiki>// add SSID and password +
-  cmd+=SSID; +
-  cmd+="\",\""; +
-  cmd+=PASS; +
-  cmd+="\""; +
-  // send string +
-  Serial2.println(cmd); +
-  delay(5000);+
  
-  // was the login accepted? +NOTE : si, au premier démarrage, vous ne voyez rien sur votre écran, essayez de tourner le potentiomètre au dos de l'écran LCD pour ajuster sa luminosité.
-  char okcheck[]="OK"; +
-  if(Serial2.find(okcheck)){ +
-    Serial.println("Login accepted"); +
-    return true; +
-  }else{ +
-    Serial.println("Login not accepted."); +
-    return false; +
-  }</nowiki>**+
  
-Quand j'utilise Serial2, je suis en conversation avec ESP8266. Quand j'utilise simplement Serial, je discute avec le moniteur série (ou j'imprime dessus). J'envoie la commande AT au ESP8266 imprime un texte sur le moniteur série pour me montrer ce qui se passe en arrière-plan. J'attends cinq secondes puis je lance un Serial.find pour voir si l'obtiens une réponse OK. Si oui, alors j'essaie de me connecter (en sautant à connectWiFi()). Sinon, j'affiche alors le texte qui indique « non connecté ».+**Solid State Relay
  
-Pour se connecter au routeur WiFij'ai besoin d'un SSIDd'un mot de passe et de plusieurs commandes.+Firstyou can use a relay switch with this circuitbut you’ll get a physical clicking sound as the relay switches back and forth. No big deal, but a solid state relay is digital and without sound. Be absolutely sure that the relay switch (solid state or not) is rated to do 110/240V.
  
-<nowiki> +Before I chop into the cable of my beloved heat mat, I want to make sure this circuit will workSo, insteadI’m going to chop into an unused desk lamp.
-boolean connectWiFi(){ +
-  Serial2.println("AT+CWMODE=1"); +
-  delay(2000); +
-  String cmd="AT+CWJAP=\""; +
-  // add SSID and password +
-  cmd+=SSID; +
-  cmd+="\",\""; +
-  cmd+=PASS; +
-  cmd+="\""; +
-  // send string +
-  Serial2.println(cmd); +
-  delay(5000);+
  
-  // was the login accepted? +With it unplugged, I chopped through the cable and paired off the two inner cables (live and neutral). I then twisted the two live cables together and left the two neutral cables detachedI also put some electrical tape over that twist to cover it up and keep things somewhat safe.**
-  char okcheck[]="OK"; +
-  if(Serial2.find(okcheck)){ +
-    Serial.println("Login accepted"); +
-    return true; +
-  }else{ +
-    Serial.println("Login not accepted."); +
-    return false; +
-  }</nowiki>+
  
-**So, I send the command AT+CWMODE=1 to the ESP8266. Wait two seconds, create a string called cmd, and start with AT+CWJAP=\”, then add to the string with the SSID, password, then send the completed string to the ESP8266. Again, I check for a reply of OK (or not) with an appropriate message to the serial monitor.+Relais statique
  
-For the main loopI first jump to TempHum() to get my temperature info from the DHT22. +Disons d'abord que vous pourriez utiliser un relais électromécanique pour ce circuitmais vous entendriez un bruit de contact à chaque commutation du relaisCe n'est pas un problème ; cependantun relais statique est électronique et ne fait pas de bruitAssurez-vous absolument que ce relais (statique ou nonest dimensionné pour supporter 110/240 V AC.
-<nowiki> +
-Serial.print("DHT22\t"); +
-  int chk = DHT.read22(DHT22_PIN)+
-  switch (chk) +
-  { +
-… +
-  } +
-  // DISPLAY DATA +
-  Serial.print(DHT.humidity, 1); +
-  Serial.print(",\t\t"); +
-  Serial.println(DHT.temperature, 1);</nowiki>**+
  
-Donc, j'envoie la commande AT+CWMODE=1 au ESP8266. J'attends deux secondes, je crée une chaîne nomme cmd, la commence avec AT+CWJAP=\”, puis la complète avec le SSID et le mot de passe ; ensuitej'envoie la chaîne terminée au ESP8266. À nouveau, je vérifie si la réponse est OK (ou pas) avec le message approprié au moniteur série.+Avant de couper le câble de ma chère couverture chauffante, je veux être sûr que le circuit fonctionne. Aussià la place, je vais sacrifier une lampe de bureau inutilisée.
  
-Pour la boucle principale, je passe d'abord à TempHum() pour obtenir l'information de température du DHT22.+Après l'avoir débranchée, je coupe le câble et je sépare les deux conducteurs internes (phase et neutre). Puis, je relie les deux phases ensemble et je laisse les deux neutres séparés. Je met aussi un peu de ruban isolant autour de l'épissure pour la couvrir et la mettre en sécurité (plus ou moins).
  
-<nowiki> +**The solid state relay (SSR for short) has two DC inputs (in the photoat the bottom left, is the red +5v and blue ground). It also has (depending on your SSRone or more channels. My SSR has two channels. This is where your Arduino (yellow wire in the photowill tell the SSR to go HIGH or LOW. The final two inputs are for the cable you wish to open/closeIn this case the live (top wires in the photofrom my lampNowit didn’help that my inputs are labelled wronglyThe one marked ‘Ch1’ is actually for SSR channel twoSo if you try this and it doesn’t worktry switching your wire from Ch1 to Ch2. You should see a light come on on the SSR to show which channel is HIGH/LOW.
-Serial.print("DHT22\t")+
-  int chk = DHT.read22(DHT22_PIN)+
-  switch (chk) +
-  { +
-… +
-  } +
-  // DISPLAY DATA +
-  Serial.print(DHT.humidity, 1)+
-  Serial.print(",\t\t"); +
-  Serial.println(DHT.temperature1);</nowiki>+
  
-**This is simply creating an integer called chk, and reading the DHT22 pin. I check the status of the DHT22 (the switch, which Ive snipped that code here to save space), and print the temperature and humidity to the serial monitor.+With those things in place its time to write some code.
  
-String SendTempLevel = String((float)DHT.temperature, 0);+To test the SSR I’ll flash the lamp on/offThe first new lines of code are:
  
-String SendHumLevel = String((float)DHT.humidity, 0);+#define ssr1 53
  
-The two Strings are holders for the temperature and humidity and are what I’ll send to ThingSpeak.+int state = LOW;
  
-I jump to updateTemp(), taking those two strings with me. Now it’s time to send to ThingSpeak. You’ll obviously need to create a free account with ThingSpeak, create a channel, have two fields (for temperature and humidity), and obtain your API key.+unsigned long previousMillis= 0;
  
-<nowiki> +const long interval1000;**
-String cmd "AT+CIPSTART=\"TCP\",\""; +
- cmd += "184.106.153.149"; // api.thingspeak.com +
- cmd += "\",80"; +
- Serial2.println(cmd);</nowiki>**+
  
-Ceci crée simplement un entier appelé chk qui lit le picot du DHT22je vérifie l'état du DHT22 (l'inter, dont j'ai coupé le code ici pour gagner de la place) et j'imprime la température et l'humidité sur le moniteur série.+Le relais statique (RS pour faire court) a deux entrées en courant continu (sur la photo, en bas à gauche, le +5V est rouge et la masse bleue)Il comporte aussi (suivant votre RS) un ou plusieurs canaux. Le mien en a deux. C'est par ici que votre Arduino (fil jaune sur la photo) alimentera ou non votre RS. Les deux dernières entrées sont pour le câble que vous souhaitez ouvrir/fermer. Dans ce cas, la phase (les fils du haut sur la photovient de la lampe. Là, ça n'a pas aidé que mes entrées soient mal étiquetées. Celle marquée « Ch1 » est en fait le canal 2 du RS. Aussi, si vous essayez le montage et que ça ne marche pas, tentez d'inverser les canaux 1 et 2. Vous devriez voir une lampe s'allumer pour vous montrer quel canal est alimenté ou non.
  
-String SendTempLevel = String((float)DHT.temperature0);+Une fois tout ceci en placele moment est venu d'écrire un peu de code.
  
-String SendHumLevel = String((float)DHT.humidity0);+Pour tester le RSje vais faire clignoter la lampe. Les premières nouvelles lignes de code sont :
  
-Les deux String mémorisent la température et l'humidité ; je les enverrai à ThingSpeak.+#define ssr1 53
  
-Je saute à updateTemp(), emportant ces deux chaînes avec moi. Maintenant, c'est le moment de l'envoi à ThingSpeak. Vous aurez évidemment l'obligation de vous créer un compte sur ThingSpeak, de créer un canal, d'avoir deux champs (pour la température et l'humidité) et d'obtenir votre clé API.+int state = LOW;
  
-<nowiki> +unsigned long previousMillis0;
-String cmd "AT+CIPSTART=\"TCP\",\""; +
- cmd += "184.106.153.149"; // api.thingspeak.com +
- cmd += "\",80"; +
- Serial2.println(cmd);</nowiki>+
  
-**Like last time, I create a string called cmd and send it AT codes, add the ThingSpeak IP and port, then send it to the ESP8266.+const long interval= 1000;
  
-Again, I do a check to see if theres an error or not. +**This defines pin 53 on the Arduino as the control pin for the SSR. The state is to keep track of whether the lamp is currently on/off. The previousMillis and interval are for the flash. Im going to try and use millis rather than delays as millis is more preferable to the program halting delay command.
-<nowiki> +
-String getStr = "GET /update?api_key="; +
-  getStr += "8KS0CVMQ12XXD817"; +
-  getStr += "&field1="; +
-  getStr += String(SendTempLevel); +
-  getStr += "&field2="; +
-  getStr += String(SendHumLevel); +
-  getStr += "\r\n\r\n";</nowiki>+
  
-A new string, getStr, is created with a GET command – with my ThingSpeak API key, and temperature and humidity.+I begin with the usual pinMode and then set the SSR to the initial state of LOW. In other wordsoff. This SSR is ‘low level trigger’ which means LOW is on, and HIGH is off.
  
-String cmd is created again with an AT commandand the getStr.length will tell us now long the getStr is. This is required for sending to ThingSpeak and to the ESP8266.**+pinMode(ssr1OUTPUT); 
  
-Comme la fois précédenteje crée une chaîne appelée cmd et lui envoie les codes AT, j'ajoute l'IP et le port de ThingSpeak, puis je l'envoie à ThingSpeak.+digitalWrite(ssr1state);
  
-À nouveau, je vérifie s'il y a un erreur ou non.+In the setup I create:
  
-<nowiki> +unsigned long currentMillis millis();
-String getStr "GET /update?api_key="; +
-  getStr += "8KS0CVMQ12XXD817"; +
-  getStr += "&field1="; +
-  getStr += String(SendTempLevel); +
-  getStr += "&field2="; +
-  getStr += String(SendHumLevel); +
-  getStr += "\r\n\r\n";</nowiki>+
  
-Une nouvelle chaîne, getStr, est créée avec la commande GET - avec ma clé API ThingSpeak, la température et l'humidité.+as this will be used in the if/then to switch on/off the lamp.**
  
-La chaîne cmd est créée à nouveau avec une commande AT, et la commande getStr.length nous dira maintenant quelle est la longueur de la chaîneCeci est obligatoire pour un envoi à ThingSpeak et au ESP8266.+Ceci définit le picot 53 de l'Arduino comme le picot de commande du RSLe « state » sert à conserver une trace de la lampe actuellement allumée/éteinte« PreviousMillis » et « interval » sont pour le clignotement. J'essaie  d'utiliser millis plutôt que delays parce que millis est meilleur pour la commande de tenue d'un tempo dans le programme.
  
-**Like previous sendswe check for a reply. The greater than character (>) means good. Anything else is badand we send AT+CIPCLOSE to close the connectionAgaininfo is sent to the serial monitor to tell us what’s happening.+Je commence avec l'habituel pinModepuis place le relais à l'état BAS, c'est-à-direéteintCe RS est de type « à ouverture »ce qui signifie que le contact est fermé hors tension et ouvert sous tension.
  
-Uploading the gist code to the MEGA should be error-freeand, when running, the serial monitor will tell you what is happening.+pinMode(ssr1OUTPUT); 
  
-If you’re seeing something like that shown in the serial monitor image herethen you’re good to go. ThingSpeak should be receiving your data.+digitalWrite(ssr1state);
  
-If you’ve gotten this farthen you’ve done great. As getting the ESP8266 to work, and sending data to ThingSpeak, are probably the most difficult parts of this project. The rest should be a breeze.**+Dans le paramétrageje crée :
  
-**Famous last words!+unsigned long currentMillis = millis();
  
-I should add that I’m currently sending data to ThingSpeak every 20-25 seconds. This is obviously for testing at the moment. Before I use the Brewduino, I will change the delays to maybe every 30 minutes or so.+car il sera utilisé dans la boucle si/alors pour commuter la lampe.
  
-Next month we’ll add an LCD screen, and test the relay switch.**+**The only other additional code of note is the switching (top right). CurrentMillis and previousMillis will keep track of how many milliseconds the loop is running for. When it reaches the interval (set up at the start) then the loop ends. Note that this means the code never grinds to a halt like it would with a delay. I can still put stuff to do inside that HIGH/LOW if statement. 
 + 
 +The inner if/else is just checking to execute: 
 +• if it’s currently off, let’s put it on, 
 +• if it’s currently on, let’s put it off. 
 + 
 +And, finally, do the on/off. 
 + 
 +With the interval set at 1000 this means the lamp will turn on/off every second.** 
 + 
 +La seule addition notable de code est la commutation (en haut à droite). CurrentMillis et PreviousMillis conservent les durées en millisecondes de parcours de la boucle. Quand « interval » est atteint (fixé au début),  la boucle s'arrête. Notez que ça signifie que le code ne comporte aucun arrêt, comme ce serait le cas avec un delay. Je peux encore ajouter des choses à faire à l'intérieur de cette boucle Allumé/éteint, si besoin est. 
 + 
 +Le if/else intérieur contrôle juste l'exécution suivante : 
 +• si l'état est actuellement allumé, alors éteindre, 
 +• si l'état est actuellement éteint, alors allumer. 
 + 
 +Et, enfin, exécute le Allumé/éteint. 
 + 
 +Avec un intervalle réglé à 1000, ça signifie que la lampe va clignoter chaque seconde. 
 + 
 +**The only downside of removing the delays is that I’m now hammering ThingSpeak every minute or less, but I’ll fix that later. It’s working. That’s the main thing! 
 + 
 +The code for this is a gist on my Github at: https://gist.github.com/ronnietucker/7fc62df161107116cf93. The code referred to above is marked as revision number 4. 
 + 
 +To check for a specific temperature, it’s as simple as putting in two if statements. 
 + 
 +if (DHT.temperature > 24 ) {  
 +state=LOW; 
 +
 + 
 +if (DHT.temperature < 24) { 
 +state=HIGH; 
 +
 + 
 +If the temperature goes above 24, the lamp comes on. If the temperature falls below 24, the lamp goes off.** 
 + 
 +Le seul inconvénient de retirer les délais est que je vais maintenant solliciter ThingSpeak toutes les minutes ou moins, mais je le réglerai plus tard. Ça marche. C'est le principal ! 
 + 
 +Le code correspondant est un gist sur mon Github à : https://gist.github.com/ronnietucker/7fc62df161107116cf93. Le code dont on parle ci-dessus est la révision n° 4. 
 + 
 +Pour surveiller une température particulière, rien de plus simple. Ajoutez les deux déclarations :  
 + 
 +if (DHT.temperature > 24 ) {  
 +state=LOW; 
 +
 + 
 +if (DHT.temperature < 24) { 
 +state=HIGH; 
 +
 + 
 +Si la température dépasse 24 °C, la lampe s'allume. Si la température tombe sous les 24 °C, la lampe s'éteint. 
 + 
 + 
 + 
 +**Mike K. - qualified electrical engineer (true!); and who has an uncle who was electrocuted notes: 
 + 
 +Ronnie says: listen to this man. He knows FAR more than me! 
 + 
 +Timer-overflow: In the real world, you’d might need to find out the maximum value of that “currentMillis” variable, because, sooner-or-later, it’ll reset back to 0. It’s defined here as an “Unsigned Long”, but I don’t know how many bytes is assigned (2/4/8/?), and I don’t know if each unit in that var is an actual millisec, or a multiple of one (eg, each unit might be a microsec?). 
 + 
 +You may need to allow for that event in your code, otherwise, your code will stop working when it occurs. For example. if a “long” is 4 bytes, and if the time unit is actual millisecs, then this code will fail after 49 days operation (at most!).** 
 + 
 +Notes de Mike K., ingénieur qualifié en électricité (vrai !) et dont un oncle a été électrocuté : 
 + 
 +Ronnie écrit : écoutez ce gars. Il en connaît beaucoup plus que moi ! 
 + 
 +Dépassement de la temporisation : dans le monde réel, vous ne devriez pas avoir besoin de déterminer la valeur maximale de la variable « currentMillis » parce que, tôt ou tard, elle sera remise à zéro.  Elle est définie ici comme un « entier long non signé », mais je ne sais pas combien de bits lui sont attribués (2/4/8/?) et je ne sais pas si chaque unité de cette variable est une vraie milliseconde ou un de ses multiples (par exemple, chaque unité vaudrait une microseconde ?). 
 + 
 +Vous pourriez avoir besoin de prévoir cet événement dans votre code ; autrement, votre code s'arrêtera de fonctionner si ça se produit. Par exemple : si un « entier long » est sur 4 bits, et si le temps est en vraies millisecondes, ce le code sera en défaut après 49 jours de fonctionnement (au mieux !). 
 + 
 +**Temperature triggers: In the real world, your temp sensor might be “noisy”, and, in your case, when the temp is “around 24”, the reading might be hovering around 23/24/25, but changing a lot. If that happens, the code might get into a frenzy - switching the device on/off rapidly. To avoid that, one would use two thresholds just outside this frenzy-range, maybe 22-degrees, and 26-degrees. Then, the general approach would be: 
 +• In the initialisation code,set the Device to OFF, and set the “Device_State” to OFF (for simplicity). 
 +• If the new temperature is at/below the lower value, and the Device_State is currently OFF, then set it ON, and set Device_State to ON. 
 +• If the new temperature is at/above the upper value, and the Device_State is currently ON, then set it OFF, and set Device_State to OFF. 
 +• If we can read the current state of the device, then the above “Device_State” variable is not needed. And, reverse the above references to ON/OFF, if appropriate.** 
 + 
 +Seuils de température : dans le monde réel, votre détecteur de température pourrait être « bruité » et, dans ce cas, quand la température est « autour de 24 », la lecture pourrait tourner autour de 23/24/25, avec de nombreux changements. Si ça arrive, le code pourrait devenir fou, commutant le relais à toute vitesse. Pour éviter cela, on peut utiliser deux seuils, juste en dehors de cette zone perturbée ; peut-être 22 et 26 degrés. L'approche générale deviendrait alors : 
 +• Dans le code d'initialisation, mettre l'appareil à Éteint ainsi que «l'état de l'appareil » (par simplicité). 
 +• Si la nouvelle température est à la valeur basse (ou en-dessous), et que l'état de l'appareil est actuellement Éteint, alors l'allumer et mettre l'état de l'appareil à Allumé. 
 +• Si la nouvelle température est à la valeur haute (ou au-dessus), et que l'état de l'appareil est actuellement Allumé, alors l'éteindre et mettre l'état de l'appareil à Éteint. 
 +• Si vous pouvez lire l'état actuel de l'appareil, alors la variable « état de l'appareil » ci-dessus n'est pas nécessaire. Et inversez les références Allumé/Éteint ci-dessus, si c'est approprié. 
 + 
 +**Wiring: When cutting the mains cable, strip back the outer insulation very slowly and carefully, and do not damage or cut into the wires which are not used by the relay circuit. If there is an earth cable, and if there is an earthing connector in the SSR circuit, then, do not cut the earth cable, but strip about 1-2 cm of it, fold it, and insert it into the earth connector. 
 + 
 +For safety, the SSR circuit must be enclosed in a suitable protective box. If the relays get hot when being used, then ensure there is adequate ventilation in the box, and ensure the box is not placed on soft surfaces such as carpets, duvets, etc - which would inhibit ventilation.** 
 + 
 +Câblage : Quand vous coupez les câbles d'alimentation, retirez l'isolation extérieure lentement et avec précaution, et ne détériorez ni coupez les fils qui ne sont pas utilisés par le circuit du relais. S'il y a un câble de terre, et s'il y a une borne de terre sur le circuit du RS, ne coupez pas le câble de terre, mais dénudez-le sur environ 1 à 2 cm, pliez-le et insérez-le dans le connecteur de terre. 
 + 
 +Par sécurité, le circuit du RS doit être placé dans une enveloppe protectrice adaptée. Si les relais deviennent chauds à l'utilisation, assurez-vous qu'il y a une ventilation adaptée dans le boîtier, et vérifiez que le boîtier n'est pas placé sur des surfaces molles telles que des tapis, duvets, etc., qui pourraient gêner la ventilation. 
 + 
 +**A user might install two relays - one on the positive and one on the negative lines. If a single relay is used - as in this project - it must be connected into the LIVE wire, so that, when the device (lamp, etc) is "off", no mains voltage is reaching the device. 
 + 
 +Rating of Relays: Ensure that the relay can easily handle the mains voltage (110V AC or 240V AC), and the maximum current that will be used by the devices. For example, a light bulb might use 1.0 Amp current, whereas an electric room heater might use 20+ Amps. 
 + 
 +Overall, we should expect that Arduino fans might have kits in their bedrooms, and might decide to control the mains heating, lighting, ventilation, etc, with the Arduino. In this case, they are messing with lethal devices - which could easily lead to major fires, or injury, or death.** 
 + 
 +L'utilisateur peut installer deux relais, un sur la phase, un autre sur le neutre. Si un seul relais est utilisé - comme dans mon projet - il doit être connecté sur la PHASE, de sorte que, quand l'appareil (lampe ou autre) est éteint, aucune tension secteur n'atteint cet appareil. 
 + 
 +Caractéristiques du relais : Assurez-vous que le relais peut facilement supporter la tension secteur (110 V AC ou 240 V AC), ainsi que la courant maximal absorbé par les appareils. Par exemple, une lampe à incandescence pourrait absorber 1 A, alors qu'un radiateur électrique pourrait utiliser 20 A ou plus. 
 + 
 +En général, vous pouvez vous attendre à ce que des fans d'Arduino puissent avoir des kits dans leurs chambres et puissent décider de piloter le chauffage, l'éclairage, la ventilation, etc. avec l'Arduino. Dans ce cas, ils tripatouillent des appareils très dangereux, qui peuvent conduire facilement à un incendie, des blessures ou à la mort.
issue106/arduino.1457280390.txt.gz · Dernière modification : 2016/03/06 17:06 de d52fr