issue106:arduino
Différences
Ci-dessous, les différences entre deux révisions de la page.
| Les deux révisions précédentesRévision précédenteProchaine révision | Révision précédente | ||
| issue106:arduino [2016/03/06 17:06] – d52fr | issue106:arduino [2016/04/08 16:30] (Version actuelle) – créée andre_domenech | ||
|---|---|---|---|
| Ligne 1: | Ligne 1: | ||
| - | === **!!ATTENTION | + | **WARNING: This month we’re heading into the big league with controlling household voltage devices. It should go without saying, but 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. | ||
| - | **So, with the basic plan thought out, it’s now time to actually pick up some components | + | **In previous articles, I used an LCD screen which, while 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 |
| - | 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:// |
| - | Temperature sensing is highly important | + | 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:// |
| - | Rather than use the old DHT11 module, I’m using a DHT22 module this time. These are more sensitive and give a more precise reading. I’m also going to use an Arduino MEGA for this project.** | + | Dans les articles précédents, j'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' |
| - | Maintenant que nous avons réfléchi | + | Ces nouveaux écrans LCD sont I2C ce qui signifie qu'ils ont une petite carte de pilotage |
| - | Température | + | Avant d' |
| - | 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' | + | I need to include that new library: |
| - | **Build 1 | + | #include < |
| - | I’ve connected the DHT22 module using the three pins. One wire to +5V, one to ground, and the other to pin 6 on the MEGA. | + | Define various pins (I2C stuff that you shouldn’t need to touch), but insert |
| - | Other than the serial monitor, there’s 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 |
| + | < | ||
| - | That’s the basic circuit for this first part. | + | #define BACKLIGHT_PIN |
| + | #define En_pin | ||
| + | #define Rw_pin | ||
| + | #define Rs_pin | ||
| + | #define D4_pin | ||
| + | #define D5_pin | ||
| + | #define D6_pin | ||
| + | #define D7_pin | ||
| - | The code for the DHT22 is pretty straightforward, so we’ll look at that next. The ESP8266 is more tricky, and is quite often prone to not responding. If you think your code is right, and the ESP8266 isn’t responding, try unplugging/ | + | LiquidCrystal_I2C |
| - | 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' | + | 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' |
| - | C'est le circuit de base de la première partie. | + | #include < |
| - | 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 | + | Définissez plusieurs picots (des éléments I2C que vous n' |
| - | **Code | + | #define I2C_ADDR |
| + | < | ||
| - | I’ll be adding all my code for this project to this Github gist: https:// | + | #define BACKLIGHT_PIN |
| + | #define En_pin | ||
| + | #define Rw_pin | ||
| + | #define Rs_pin | ||
| + | #define D4_pin | ||
| + | #define D5_pin | ||
| + | #define D6_pin | ||
| + | #define D7_pin | ||
| - | By the time you read this, there will be many revisions of the code added to the gist, but this is revision 2 that I’m discussing here. | + | LiquidCrystal_I2C |
| - | For the DHT22, I’m using the two libraries from here: http:// | + | Dans mon paramétrage, j' |
| - | You’ll need to copy/paste the text for the two files to new files, and name them accordingly. All the instructions for doing this are at that link. | + | **lcd.begin (16,2); |
| + | lcd.setBacklightPin(BACKLIGHT_PIN, | ||
| - | I start by including the DHT library and define the pin for the DHT22. I then define my wifi SSID and password.** | + | lcd.setBacklight(HIGH); |
| - | Code | + | lcd.home(); |
| - | J' | + | lcd.print(" |
| - | 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' | + | Most of those commands are pretty self explanatory. |
| - | Vous aurez besoin de copier/ | + | I now have my temperature, |
| - | Je commence par inclure la bibliothèque DHT et définir les picots pour le DHT22. Puis, je définis le SSID et le mot de passe de mon WiFi. | + | lcd.begin (16,2); |
| + | lcd.setBacklightPin(BACKLIGHT_PIN, | ||
| - | **Now we’re on to the main setup. I use two serial begin commands: | + | lcd.setBacklight(HIGH); |
| - | Serial.begin(115200); | + | lcd.home(); |
| - | Serial2.begin(9600); | + | lcd.print(" |
| - | 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); |
| - | < | + | La plupart de ces commandes sont explicites. |
| - | Serial2.println(" | + | |
| - | + | ||
| - | Serial.println(" | + | |
| - | + | ||
| - | delay(5000); | + | |
| - | + | ||
| - | char okcheck[]=" | + | |
| - | + | ||
| - | if(Serial2.find(okcheck)){ | + | |
| - | Serial.println(" | + | |
| - | connectWiFi(); | + | |
| - | Serial.println(" | + | |
| - | else{ | + | |
| - | Serial.println(" | + | |
| - | }</ | + | |
| - | Maintenant, | + | Maintenant, |
| - | Serial.begin(115200); | + | **lcd.setCursor(0,2); |
| - | Serial2.begin(9600); | + | lcd.print(" |
| - | Le Serial.begin sont pour le DHT22 ; de cette façon, j' | + | lcd.setCursor() is for placing the text at a particular position on the screen. |
| - | < | + | NOTE: if you don’t see anything on your screen on first run, try turning the potentiometer on the back of the LCD screen to adjust the brightness of the screen.** |
| - | Serial2.println(" | + | |
| - | + | ||
| - | Serial.println(" | + | |
| - | + | ||
| - | delay(5000); | + | |
| - | + | ||
| - | char okcheck[]=" | + | |
| - | + | ||
| - | if(Serial2.find(okcheck)){ | + | |
| - | Serial.println(" | + | |
| - | connectWiFi(); | + | |
| - | Serial.println(" | + | |
| - | else{ | + | |
| - | Serial.println(" | + | |
| - | }</ | + | |
| - | **When using Serial2, I’m talking to the ESP8266. When using just Serial, I’m talking | + | lcd.setCursor(0,2); |
| - | Connecting to a wifi router needs the SSID, password and several commands. | + | lcd.print(" |
| - | boolean connectWiFi(){ | + | lcd.setCursor() sert à positionner le texte à un endroit précis de l' |
| - | Serial2.println(" | + | |
| - | delay(2000); | + | |
| - | String cmd=" | + | |
| - | < | + | |
| - | 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' |
| - | char okcheck[]=" | + | |
| - | if(Serial2.find(okcheck)){ | + | |
| - | Serial.println(" | + | |
| - | return true; | + | |
| - | }else{ | + | |
| - | Serial.println(" | + | |
| - | return false; | + | |
| - | }</ | + | |
| - | Quand j' | + | **Solid State Relay |
| - | Pour se connecter au routeur WiFi, j'ai besoin d'un SSID, d'un mot de passe et de plusieurs commandes. | + | First, you can use a relay switch with this circuit, but 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. |
| - | < | + | Before I chop into the cable of my beloved heat mat, I want to make sure this circuit will work. So, instead, I’m going to chop into an unused desk lamp. |
| - | boolean connectWiFi(){ | + | |
| - | Serial2.println(" | + | |
| - | delay(2000); | + | |
| - | String cmd=" | + | |
| - | // 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 |
| - | char okcheck[]=" | + | |
| - | if(Serial2.find(okcheck)){ | + | |
| - | Serial.println(" | + | |
| - | return true; | + | |
| - | }else{ | + | |
| - | Serial.println(" | + | |
| - | return false; | + | |
| - | }</ | + | |
| - | **So, I send the command AT+CWMODE=1 to the ESP8266. Wait two seconds, create a string called cmd, and start with AT+CWJAP=\”, | + | Relais statique |
| - | For the main loop, I first jump to TempHum() to get my temperature info from the DHT22. | + | Disons d' |
| - | < | + | |
| - | Serial.print(" | + | |
| - | int chk = DHT.read22(DHT22_PIN); | + | |
| - | switch (chk) | + | |
| - | { | + | |
| - | … | + | |
| - | } | + | |
| - | | + | |
| - | Serial.print(DHT.humidity, | + | |
| - | Serial.print(", | + | |
| - | Serial.println(DHT.temperature, | + | |
| - | Donc, j' | + | 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' | + | Après l' |
| - | < | + | **The solid state relay (SSR for short) has two DC inputs |
| - | Serial.print("DHT22, \t"); | + | |
| - | int chk = DHT.read22(DHT22_PIN); | + | |
| - | switch | + | |
| - | { | + | |
| - | … | + | |
| - | } | + | |
| - | | + | |
| - | Serial.print(DHT.humidity, | + | |
| - | Serial.print(" | + | |
| - | Serial.println(DHT.temperature, 1);</nowiki> | + | |
| - | **This is simply creating an integer called chk, and reading the DHT22 pin. I check the status of the DHT22 (the switch, which I’ve snipped that code here to save space), and print the temperature and humidity to the serial monitor. | + | With those things in place it’s time to write some code. |
| - | String SendTempLevel = String((float)DHT.temperature, | + | To test the SSR I’ll flash the lamp on/off. The first new lines of code are: |
| - | String SendHumLevel = String((float)DHT.humidity, | + | #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(), | + | unsigned long previousMillis= 0; |
| - | < | + | const long interval= 1000;** |
| - | String cmd = " | + | |
| - | cmd += " | + | |
| - | cmd += " | + | |
| - | | + | |
| - | Ceci crée simplement un entier appelé chk qui lit le picot du DHT22. je vérifie l' | + | Le relais statique (RS pour faire court) a deux entrées en courant continu (sur la photo, en bas à gauche, |
| - | String SendTempLevel = String((float)DHT.temperature, 0); | + | Une fois tout ceci en place, le moment est venu d' |
| - | String SendHumLevel = String((float)DHT.humidity, 0); | + | Pour tester le RS, je vais faire clignoter la lampe. Les premières nouvelles lignes de code sont : |
| - | Les deux String mémorisent la température et l' | + | #define ssr1 53 |
| - | Je saute à updateTemp(), | + | int state = LOW; |
| - | < | + | unsigned long previousMillis= 0; |
| - | String cmd = " | + | |
| - | cmd += " | + | |
| - | cmd += " | + | |
| - | | + | |
| - | **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 there’s 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. I’m going to try and use millis rather than delays as millis is more preferable to the program halting delay command. |
| - | < | + | |
| - | String getStr = "GET / | + | |
| - | getStr += " | + | |
| - | getStr += "& | + | |
| - | getStr += String(SendTempLevel); | + | |
| - | getStr += "& | + | |
| - | getStr += String(SendHumLevel); | + | |
| - | getStr += " | + | |
| - | 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 words, off. This SSR is ‘low level trigger’ which means LOW is on, and HIGH is off. |
| - | String cmd is created again with an AT command, and the getStr.length will tell us now long the getStr is. This is required for sending to ThingSpeak and to the ESP8266.** | + | pinMode(ssr1, OUTPUT); |
| - | Comme la fois précédente, je crée une chaîne appelée cmd et lui envoie les codes AT, j' | + | digitalWrite(ssr1, state); |
| - | À nouveau, je vérifie s'il y a un erreur ou non. | + | In the setup I create: |
| - | < | + | unsigned long currentMillis |
| - | String getStr | + | |
| - | getStr += " | + | |
| - | getStr += "& | + | |
| - | getStr += String(SendTempLevel); | + | |
| - | getStr += "& | + | |
| - | getStr += String(SendHumLevel); | + | |
| - | getStr += " | + | |
| - | Une nouvelle chaîne, getStr, est créée avec la commande GET - avec ma clé API ThingSpeak, la température et l' | + | 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 | + | Ceci définit le picot 53 de l' |
| - | **Like previous sends, we check for a reply. The greater than character (>) means good. Anything else is bad, and we send AT+CIPCLOSE to close the connection. Again, info is sent to the serial monitor to tell us what’s happening. | + | Je commence avec l' |
| - | Uploading the gist code to the MEGA should be error-free, and, when running, the serial monitor will tell you what is happening. | + | pinMode(ssr1, OUTPUT); |
| - | If you’re seeing something like that shown in the serial monitor image here, then you’re good to go. ThingSpeak should be receiving your data. | + | digitalWrite(ssr1, state); |
| - | If you’ve gotten this far, then 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étrage, je 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), | ||
| + | |||
| + | Le if/else intérieur contrôle juste l' | ||
| + | • si l' | ||
| + | • si l' | ||
| + | |||
| + | Et, enfin, exécute le Allumé/ | ||
| + | |||
| + | 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:// | ||
| + | |||
| + | To check for a specific temperature, | ||
| + | |||
| + | 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:// | ||
| + | |||
| + | Pour surveiller une température particulière, | ||
| + | |||
| + | if (DHT.temperature > 24 ) { | ||
| + | state=LOW; | ||
| + | } | ||
| + | |||
| + | if (DHT.temperature < 24) { | ||
| + | state=HIGH; | ||
| + | } | ||
| + | |||
| + | Si la température dépasse 24 °C, la lampe s' | ||
| + | |||
| + | |||
| + | |||
| + | **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: | ||
| + | |||
| + | 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. | ||
| + | |||
| + | Vous pourriez avoir besoin de prévoir cet événement dans votre code ; autrement, votre code s' | ||
| + | |||
| + | **Temperature triggers: In the real world, your temp sensor might be “noisy”, | ||
| + | • 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' | ||
| + | • Dans le code d' | ||
| + | • Si la nouvelle température est à la valeur basse (ou en-dessous), | ||
| + | • Si la nouvelle température est à la valeur haute (ou au-dessus), et que l' | ||
| + | • Si vous pouvez lire l' | ||
| + | |||
| + | **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' | ||
| + | |||
| + | Par sécurité, le circuit du RS doit être placé dans une enveloppe protectrice adaptée. Si les relais deviennent chauds à l' | ||
| + | |||
| + | **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 " | ||
| + | |||
| + | 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, | ||
| + | |||
| + | L' | ||
| + | |||
| + | 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' | ||
issue106/arduino.1457280390.txt.gz · Dernière modification : 2016/03/06 17:06 de d52fr
