Affichage des articles dont le libellé est Arduino. Afficher tous les articles
Affichage des articles dont le libellé est Arduino. Afficher tous les articles

lundi 7 octobre 2019

NodeMCU Episode 6 :DHT11 (humidité et temperature) Nano et NodeMcu(LoLin)


Voici un nouveau Projet.
Il fait froid chez moi et je voudrais savoir quand le chauffage va être mis en route.
J'ai besoin d'un NodeMCU branché sur mon Wifi qui enverra les informations d'humidité et de température sur via le Wifi sur une page PHP (base de donnée, jolie schéma etc...)
Déjà verifier que j'arrive à récupérer des données du DHT11 sur le NodeMCU.
Bon ca va faire 1h30 que je suis dessus.
Le satané cablage m'aura fait perdre pas mal de temps.

Branchements:
DHT11 - Nano
Plus (+) - 3,3V
OUT- D2
Moins (-) - GND

Branchements:
DHT11 - NodeMCU LoLin V0.1
Plus (+) - 3,3V
OUT- D4 (What The F....)
Moins (-) - GND

Librairie Utilisé:
DHT_Unified_Sensor

Modifié ainsi:
Comment la ligne du DHT22
decomment la ligne du DHT11
Ajout les librairies suivantes:
// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor

  ! Toujours bien penser à fermer ses fenêtres COM3 ou COM5 ou autre avant de téléverser. !
Mon LoLin est toujours considéré comme un NODEMCU 0.9 (ESP12 Module) dans Outils/ Type de Carte

Maintenant, il faut préparer une page PHP pour récupérer les données
mettre un client Web pour envoyer ces données.
et bien sûr espacer les délais de 1000 (1 seconde) à 900000 au minimum (15mn)

Page PHP: (le fichier "tempdht11_result.txt" doit déjà exister)
https://github.com/tumador/Sonde_DHT_Wifi_PHP
Voici le script Arduino pour l'ESP pour envoyer les données au fichier PHP
https://github.com/tumador/Sonde_DHT_Wifi_PHP

mardi 16 juillet 2019

Arduino Episode 19 : Projet Reveil (tout va bien)

Arduino Episode 19 : Projet Reveil (tout va bien)

J'ajoute juste mon code où le superflu est supprimé, et les effets me conviennent.
Prochaine étape : Le tilt

// Date and time functions using a DS3231 RTC connected via I2C and Wire lib
#include <Wire.h>
#include "RTClib.h"
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>
#include <stdint.h>

RTC_DS3231 rtc;
char str [20];
char joursemaine[12];
char daysOfTheWeek[7][12] = {"Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"};
char jourmois[12];
char anneefull[4];
char horaire[12];

#define HARDWARE_TYPE MD_MAX72XX::ICSTATION_HW
#define MAX_DEVICES 4
#define CLK_PIN 13
#define DATA_PIN 11
#define CS_PIN 10

// Hardware SPI connection
MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);
int j = 0;

void setup () {
P.begin();
P.setIntensity(0);
Serial.begin(9600);
delay(3000); // wait for console opening

if (! rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}

if (rtc.lostPower()) {
Serial.println("RTC lost power, lets set the time!");
// following line sets the RTC to the date & time this sketch was compiled
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
// This line sets the RTC with an explicit date & time, for example to set
// January 21, 2014 at 3am you would call:
rtc.adjust(DateTime(2019, 7, 15, 10, 01, 0));
}
}

void loop () {
DateTime now = rtc.now();

int anneefull = now.year();
int annee= (now.year()-2000);
int mois = now.month();
int jour = now.day();
int heure = now.hour();
int minutes = now.minute();

if (P.displayAnimate())
{
sprintf(joursemaine,daysOfTheWeek[now.dayOfTheWeek()]);
sprintf(jourmois,"%02d/%02d",jour,mois);
sprintf(anneefull,"%02d",anneefull);
sprintf(horaire,"%02d:%02d",heure,minutes);

switch (j) {
case 0:
P.displayText(joursemaine, PA_CENTER, 25 , 2000, PA_DISSOLVE, PA_DISSOLVE);
break;
case 1:
P.displayText(jourmois, PA_CENTER, 25 , 2000, PA_DISSOLVE, PA_DISSOLVE);
break;
case 2:
P.displayText(anneefull, PA_CENTER, 25 , 2000, PA_DISSOLVE, PA_DISSOLVE);
break;
case 3:
P.displayText(horaire, PA_CENTER, 25 , 30000, PA_DISSOLVE, PA_DISSOLVE);
break;
default:
break;
}
j = j + 1;
if (j > 5) j = 0;
}

Serial.print(" (");
Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
Serial.print(") ");
Serial.print(now.day(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.year(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
Serial.print(j);
Serial.println();
}

dimanche 7 avril 2019

Arduino Episode 18 : Projet Reveil

Voici un projet qui s'impose à moi,
après un achat sur le bon coin, je me retrouve avec quelques éléments qui ne m'interesse pas vraiment.
-arduino
-matrice 7219
-une horloge temps réel ds3231m


et l'idée à germée.
 Je vais faire un reveil,  juste ajouter un buzzer un tilt et je pourrais faire une horloge qui affiche l'heure, sonne, et s'éteint lorsqu'on lui met la tête en bas.
on pourra toujours changer l'arduino nano par un esp8266 pour le mettre sur Internet.

Voici rapidement les branchements
Max7219 - Nano
VCC - 5V
GND - GND
DIN - PIN 11
CS -  PIN 10
CLK - PIN 13

DS3231M - Nano
VCC - 3V
GND - GND
SCL - SCL or A5
SDA - SDA or A4


Pour la librairie du DS3231M, j'opte pour RTCLib, plus rapide que DS3231M  ou DS3231 ou DS3231F
Il configure l'heure tout seul, l'affiche, et fait meme un test de prévision (ici ca ne marche pas)

2019/4/8 (Monday) 18:10:47
 since midnight 1/1/1970 = 1554714647s = 17994d
 now + 7d + 30s: 2019/4/16 06:40:53

Voici la partie code pour le RTC :
// Date and time functions using a DS3231 RTC connected via I2C and Wire lib
#include
#include "RTClib.h"

RTC_DS3231 rtc;

char daysOfTheWeek[7][12] = {"Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"};

void setup () {

#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  Serial.begin(9600);

  delay(3000); // wait for console opening

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
}

void loop () {
    DateTime now = rtc.now();

    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");

    Serial.print(now.day(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.year(), DEC);
    Serial.print(' ');
   
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
   
    Serial.print(" Depuis le 1/1/1970 minuit = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");
   
    // calculate a date which is 7 days and 30 seconds into the future
    DateTime future (now + TimeSpan(7,12,30,6));
   
    Serial.print(" Maintenant + 7d + 12h + 30minutes +6s: ");
    Serial.print(future.day(), DEC);
    Serial.print('/');
    Serial.print(future.month(), DEC);
    Serial.print('/');
    Serial.print(future.year(), DEC);
    Serial.print(' ');
    Serial.print(future.hour(), DEC);
    Serial.print(':');
    Serial.print(future.minute(), DEC);
    Serial.print(':');
    Serial.print(future.second(), DEC);
    Serial.println();
   
    Serial.println();
    delay(5000);
}

lundi 1 avril 2019

Arduino Episode 17 : Tilt Module






Rien de bien compliqué sur ce module, le module Tilt est une bille de métal qui fait rentre en contact 2 connecteurs.

Branchements :

NANO <-> Emetteur IR
GND --- Signe -
5V --- Centre (rien de noté)
D3 -- S


Code:

int Led = 13 ;
int Shock = 3 ;
int val ;
void setup ()
{
  pinMode (Led, OUTPUT);
  pinMode (Shock, INPUT);
}
void loop ()
{
  val = digitalRead (Shock);
  if (val == HIGH)
  {
    digitalWrite (Led, LOW);
  }
  else
  {
    digitalWrite (Led, HIGH);
  }
}


samedi 23 mars 2019

Arduino Episode 16 : Emetteur InfraRouge, InfraRed et TV LG





Voici ce que j'ai trouvé pour commander ma TV LG:

Source:
https://www.kzenjoy.net/2015/votre-telecommande-universelle-grace-a-arduino/


#include <irremote>

IRsend ir_send; // crée une instance

void setup()
{
}

void loop()
{
   ir_send.sendNEC(0x20DFC03F, 32);
   delay(3000);
}

Et voici quelques code pour la Tv LG
ON    20DF10EF
Input    20DFD02F
Vol+     20DF40BF
Vol-    20DFC03F
Mute    20DF906F

Pour le NAD
OFF  E13E13EC
ON   E13EA45B
VOL +   E13E11EE
VOL -    E13E31CE










vendredi 15 mars 2019

Arduino Episode 15 : Emetteur InfraRouge, InfraRed

Pour voir si une LED infrarouge fonctionne, bah, on peut pas voir avec ses yeux, il est recommandé d'utiliser l'appareil photo de son smartphone. Ce que j'ai fait.... ca marchait pas, un code capricieux, je me suis dis je vais brancher le 5V sur la LED pour la faire fonctionner en continu...
(Pour info, à partir de l'iPhone 5, les iPhone filtrent les infrarouges, donc on ne peux pas les voir)

Bon j'ai fait une bêtise, j'ai branché la pate S de ma LED infrarouge  sur le 5V de mon arduino...
un mauvaise odeur et une LED grillé...

J'ai récupéré une vieille télécommande, récupéré la LED et ressoudé à la place de ma LED grillé: youpi ca marche !!!

Branchements :

NANO <-> Emetteur IR
GND --- Signe -
5V --- Centre (rien de noté)
D3 -- S


Code: https://github.com/z3t0/Arduino-IRremote
IRsendDemo:
#include
IRsend irsend;
void setup()
{
}

void loop() {
    for (int i = 0; i < 3; i++) {
        irsend.sendSony(0xa90, 12);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

vendredi 22 février 2019

Arduino Episode 14 : Tiny RTC Module (Real Time Clock) Horloge temps réel

Arduino Episode 14 : Tiny RTC Module (Real Time Clock) Horloge temps réel

1er problème, je n'ai pas de broche et de kit de soudure pour tester le matériel.
J'utilise alors des câbles durant glissé dans les trous sans être retenu, et calé sur le bureau sans le bouger, le résultat fonctionne directement.
Attention aux achats car je vais devoir souder ceci pour que ce soit pérènne.

Branchements :

On pourra déjà remarquer que nous avons 2 serie de brochage
A gauche, DS, SCL, SDA, VCC, GND
A droite , SQ,DS, SCL, SDA, VCC, GND, BAT

A gauche pour être branché directement à un arduino
A droite pour être branché en plus qu'a gauche en arduino, sur un autre périphérique IC2 (ici pas utile)


NANO <-> Tiny RTC
GND --- GND
5V --- VCC
A4 --- SDA
A5 --- SCL

Code: 
Croquis, Inclure une Bibliothèque, Gerer les bibliothèques, "RTClib" by Adafruit
https://github.com/adafruit/RTClib
Fichier; exemple, RTClib, DS1307

Résultat:
Dans la console COM à 57600bauds :
2019/2/22 (Friday) 16:2:5
 since midnight 1/1/1970 = 1550851325s = 17949d
 now + 7d + 30s: 2019/3/2 4:32:11



Sources:
https://www.elecrow.com/wiki/index.php?title=Tiny_RTC
https://www.hobbyist.co.nz/?q=real_time_clock 
https://www.youtube.com/watch?v=OmVoR3mTP00

mardi 19 février 2019

Arduino Episode 13 : recepteur InfraRouge, InfraRed


Arduino Episode 13 : recepteur InfraRouge, InfraRed  

Branchements :

NANO <-> Recepteur IR
GND --- Signe -
5V --- Centre (rien de noté)
D11 -- S


Code: https://github.com/z3t0/Arduino-IRremote (IRrecvDemo)

#include < boarddefs.h >
#include <irremote .h>
#include <irremoteint .h>
#include <ir_lego_pf_bitstreamencoder .h>

int RECV_PIN = 11;
IRrecv irrecv (RECV_PIN);
decode_results results;
void setup ()
{
Serial.begin (9600);
irrecv.enableIRIn ();
}
void loop () {
if (irrecv.decode (& results)) {
Serial.println (results.value, HEX);
irrecv.resume ();
}
}

Arduino Episode 12 : Faisceau LASER (ky-008)

 

Arduino Episode 12 : Faisceau LASER (KY-008)

Branchement:
NANO <-> <-->Laser
GND --- au moins
5V --- centre (sans annotation)
D8 -- S

Code: (rien de plus qu'allumer le LASER)

const int Laser=8;
void setup() {
   pinMode(Laser,OUTPUT);
  digitalWrite(Laser,HIGH);
}

void loop() {
}

Si vous ne voulez qu'un laser sans code :

Branchement:
NANO <-->Laser
GND --- au moins
3.3V --- S

lundi 18 février 2019

Arduino Episode 11 : Bouton Poussoir et 433






Branchements Emetteur:

NANO1 <-> Emetteur
GND --- GND
5V --- VCC
D10 -- DATA

NANO1 <-> Emetteur
D2 --- une PIN du bouton d'un côté
GND --- 'autre PIN du bouton du même côté

Branchements Recepteur:

NANO2 <-> 433 recepteur
GND --- GND
DATA --- D2 (pour l'interruption)
5V --- VCC


Code Emetteur:


#include
#include
RCSwitch mySwitch = RCSwitch();


void setup() {
  // Transmitter is connected to Arduino Pin #10 
  mySwitch.enableTransmit(10);
 
  pinMode(2, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
  attachInterrupt(0,balance,RISING);
}

void loop() {
LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
  }


void balance()
{

  digitalWrite(LED_BUILTIN, HIGH);
  mySwitch.send(5396, 24);
  delay(1000); 
  digitalWrite(LED_BUILTIN, LOW);
  }

 

Code Recepteur : (identique à la bibliothèque RC-SWITCH)

/*
  Example for receiving
 
  https://github.com/sui77/rc-switch/
 
  If you want to visualize a telegram copy the raw data and
  paste it into http://test.sui.li/oszi/
*/

#include

RCSwitch mySwitch = RCSwitch();

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
}

void loop() {
  if (mySwitch.available()) {
    output(mySwitch.getReceivedValue(), mySwitch.getReceivedBitlength(), mySwitch.getReceivedDelay(), mySwitch.getReceivedRawdata(),mySwitch.getReceivedProtocol());
    mySwitch.resetAvailable();
  }
}

jeudi 24 janvier 2019

Arduino Episode 10 : Bouton Poussoir

Arduino Épisode 10 : Bouton Poussoir
Quoi de plus simple qu'un bouton poussoir.Et bah non !
Pour des raisons de retour d’électricité et avoir un comportement cohérent avec ce que l'on veut, il faut utiliser une résistance, mais je n'en n'ai pas sous la main.
Il y a une fonction qui utilise une résistance intégré:
INPUT_PULL UP
seulement le résultat est inversé
retourne 1 si non appuyé et
retourne 0 si appuyé.
d'où le changement d'état par la ligne etatBouton = !etatBouton
(Voir le résultat dans la console Série en 9600 baud)

Branchements:

NANO <-> Bouton
GND --- une PIN du bouton d'un côté
D10 --- l'autre PIN du bouton du même côté


Code: 


int pinBouton;

void setup() {
  Serial.begin(9600);
  pinBouton = 10;
  pinMode(pinBouton, INPUT_PULLUP);
}

void loop() {
  boolean etatBouton = digitalRead(pinBouton);
  etatBouton = !etatBouton;
  Serial.println(etatBouton);
}

et pour allumer la LED interne :

void setup() {
  Serial.begin(9600);
  pinMode(10, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  boolean etatBouton = digitalRead(10);
  etatBouton = !etatBouton;
  digitalWrite(LED_BUILTIN, etatBouton);
  Serial.println(etatBouton);
}

mardi 8 janvier 2019

Arduino Episode 9 : NFC (PN532 + LCD)





Projet sympa et presque complétement abouti.

Ici, un lecteur de tag NFC connecté sur un Arduino Nano + écran LCD pour afficher l'UID du tag (en Hexa, en Décimal et en mode MSB (reverse HEXA ou reverse Decimal).

Branchements:

NANO - LCD ou PN532
GND -- (LCD) GND

5V -- (LCD) VCC
A5-- (LCD) SCL
A4-- (LCD) SDA

3V3-- (PN532) 5V

GND --(PN532) GND
D9 -- (PN532) (non connecté)
D10 -- (PN532) SCL
D11 -- (PN532) MOSI
D12 -- (PN532) MISO
D13 -- (PN532) SCK

La boite :
-Une boite en carton
-une ouverture pour l'écran (tient tout seul)
-une ouverture pour le cable d'alimentation
-le lecteur NFC fixé à la paroi avant de la boite
et le reste (cables, arduino, rallonge de cable USB) jeté en vrac


Code: 
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_PN532.h>
#include <LiquidCrystal_I2C.h>
#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();
LiquidCrystal_I2C lcd(0x27, 20, 4);

// If using the breakout with SPI, define the pins for SPI communication.
#define PN532_SCK (13)
#define PN532_MOSI (12)
#define PN532_SS (10)
#define PN532_MISO (11)

// If using the breakout or shield with I2C, define just the pins connected
// to the IRQ and reset lines. Use the values below (2, 3) for the shield!
#define PN532_IRQ (2)
#define PN532_RESET (3) // Not connected by default on the NFC Shield

// Uncomment just _one_ line below depending on how your breakout or shield
// is connected to the Arduino:

// Use this line for a breakout with a SPI connection:
//Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);

// Use this line for a breakout with a hardware SPI connection. Note that
// the PN532 SCK, MOSI, and MISO pins need to be connected to the Arduino's
// hardware SPI SCK, MOSI, and MISO pins. On an Arduino Uno these are
// SCK = 13, MOSI = 11, MISO = 12. The SS line can be any digital IO pin.
Adafruit_PN532 nfc(PN532_SS);

// Or use this line for a breakout or shield with an I2C connection:
//Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

void setup(void) {
Serial.begin(115200);
Serial.println("Hello!");

lcd.init();

nfc.begin();

uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata) {
Serial.print("Didn't find PN53x board");
while (1); // halt
}

// Got ok data, print it out!
Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

// Set the max number of retry attempts to read from a card
// This prevents us from waiting forever for a card, which is
// the default behaviour of the PN532.
nfc.setPassiveActivationRetries(0xFF);

// configure board to read RFID tags
nfc.SAMConfig();

Serial.println("Waiting for an ISO14443A card");
lcd.backlight();
}

void loop(void) {
boolean success;
uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID
uint8_t uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

lcd.clear();
lcd.setCursor(5,1);
lcd.print("DISPONIBLE");
lcd.setCursor(5,2);
lcd.print("==========");



// Wait for an ISO14443A type cards (Mifare, etc.). When one is found
// 'uid' will be populated with the UID, and uidLength will indicate
// if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);

if (success) {

Serial.println("Found a card!");
Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
String cardIDH = "";
String cardIDRH = "";
uint32_t cardIDD;
uint32_t cardIDRD;


for (uint8_t i=0; i < uidLength; i++)
{
//Serial.print(" 0x");Serial.print(uid[i], HEX);
cardIDH += String(uid[i], HEX);
cardIDRH = String(uid[i], HEX) + cardIDRH;

cardIDRD += (uint32_t) uid[i] << (i*8);
cardIDD += (uint32_t) uid[int(uidLength)-i-1] << (i*8);

}

//cardIDD = (uint32_t) uid[3] << 0 | (uint32_t) uid[2] << 8 | (uint32_t) uid[1] << 16 | (uint32_t) uid[0] << 24;
//cardIDRD = (uint32_t) uid[0] << 0 | (uint32_t) uid[1] << 8 | (uint32_t) uid[2] << 16 | (uint32_t) uid[3] << 24;

Serial.println("");
Serial.print("UID HexaDecimal : ");Serial.println(cardIDH);
Serial.print("UID Reverse HexaDecimal : ");Serial.println(cardIDRH);
Serial.print("UID Decimal : ");Serial.println(cardIDD);
Serial.print("UID Reverse Decimal : ");Serial.println(cardIDRD);
Serial.println("");Serial.println("");

lcd.clear();

lcd.setCursor(0,0);
lcd.print("HEX :"+cardIDH);

lcd.setCursor(0,1);
lcd.print("DEC :");
lcd.setCursor(5,1);
lcd.print(cardIDD);

lcd.setCursor(0,2);
lcd.print("RHEX:"+cardIDRH);

lcd.setCursor(0,3);
lcd.print("RDEC:");
lcd.setCursor(5,3);
lcd.print(cardIDRD);

// Wait 1 second before continuing
delay(10000);
lcd.clear();
}
else
{
// PN532 probably timed out waiting for a card
Serial.println("Timed out waiting for a card");
}
}


.

jeudi 3 janvier 2019

Arduino Episode 8 : RFID (RC522 + LCD)





Arduino nano et LCD et RFID

J'ai vu chez ma Veto un super truc pour lire la puce electronique de mon chat.
Je me suis dis je vais faire pareil, j'ai un écran LCD, un arduino et un lecteur RFID.
(Mauvaise fréquence pour le lecteur RFID mais c'est pas grave)
(Je voulais utiliser mon nouveau MAX7219, mais le lecteur RFID utilise les mêmes ports I2C donc il aurait fallu acheter une carte d'entrée sortie, donc je me suis rabatu sur l'écran LCD qui intégre un module arduino qui gère l'I2C(si j'ai bien compris) de plus, les pins sont différentes, et les alimentations également :D )

Branchements:

NANO / LCD
 GND sur GND
5V sur 5V
A4 sur SDA
A5 sur SCL

NANO / RFID-RC522
D10 sur SDA
D13 sur SCK
D11 sur MOSI
D12 sur MISO
ne pas brancher l'IRQ du RC522
GND<> GND
D9 sur RST
3.3V<> 3.3V

Code:
#include <LiquidCrystal_I2C.h>
#include <RCSwitch.h>
#include <SPI.h>
#include <MFRC522.h>


#define SS_PIN 10
#define RST_PIN 9
 
MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class

MFRC522::MIFARE_Key key; 

// Init array that will store new NUID 
byte nuidPICC[4];

//config ecran
RCSwitch mySwitch = RCSwitch();
LiquidCrystal_I2C lcd(0x27, 20, 4);


void setup() { 
  Serial.begin(9600);
  lcd.init();
  SPI.begin(); // Init SPI bus
  rfid.PCD_Init(); // Init MFRC522 

  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;
  }

  Serial.println(F("This code scan the MIFARE Classsic NUID."));
  Serial.print(F("Using the following key:"));
  printHex(key.keyByte, MFRC522::MF_KEY_SIZE);
}
 
void loop() {

lcd.backlight();




  // Look for new cards
  if ( ! rfid.PICC_IsNewCardPresent())
    return;

  // Verify if the NUID has been readed
  if ( ! rfid.PICC_ReadCardSerial())
    return;

  Serial.print(F("PICC type: "));
  MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
  Serial.println(rfid.PICC_GetTypeName(piccType));

  // Check is the PICC of Classic MIFARE type
  if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&  
    piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
    piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
    Serial.println(F("Your tag is not of type MIFARE Classic."));
    return;
  }

  if (rfid.uid.uidByte[0] != nuidPICC[0] || 
    rfid.uid.uidByte[1] != nuidPICC[1] || 
    rfid.uid.uidByte[2] != nuidPICC[2] || 
    rfid.uid.uidByte[3] != nuidPICC[3] ) {
    Serial.println(F("A new card has been detected."));

    // Store NUID into nuidPICC array
    for (byte i = 0; i < 4; i++) {
      nuidPICC[i] = rfid.uid.uidByte[i];
    }
   
    Serial.println(F("The NUID tag is:"));
    Serial.print(F("In hex: "));
    printHex(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
    Serial.print(F("In dec: "));
    printDec(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
  }
  else Serial.println(F("Card read previously."));

  // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();
}


/**
 * Helper routine to dump a byte array as hex values to Serial. 
 */
void printHex(byte *buffer, byte bufferSize) {
  String cardID = "";
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
    cardID += String(buffer[i], HEX);

  }
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(cardID);
}

/**
 * Helper routine to dump a byte array as dec values to Serial.
 */
void printDec(byte *buffer, byte bufferSize) {
  
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], DEC);
    
  }
}

Un code plus simple que le mien:
https://www.hackster.io/ravee-tansangworn/reading-rfid-card-or-key-ring-and-display-on-lcd-b2f70d

#include "LiquidCrystal_I2C.h"
#include "RFID.h"

#define SS_PIN      A2
#define RST_PIN     D3

int led1 = D7;

MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
LiquidCrystal_I2C lcd(0x27,20,4);

void setup()
{ 
  lcd.init();
  lcd.backlight();
    SPI.begin();
    SPI.setClockDivider(SPI_CLOCK_DIV8);
 pinMode(led1, OUTPUT);
    mfrc522.PCD_Init();
}

void loop() {
    
    digitalWrite(led1, LOW);
    // Look for new cards, if nothing found, quit
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
     return;
    
    }
    
    // Select one of the cards, if nothing found, quit
    if ( ! mfrc522.PICC_ReadCardSerial()) {
     return;
    }
    
    String cardID = "";
    
    for (byte i = 0; i < mfrc522.uid.size; i++) {
        cardID += String(mfrc522.uid.uidByte[i] < 0x10 ? "0" : "");
        cardID += String(mfrc522.uid.uidByte[i], HEX);
    }
    digitalWrite(led1, HIGH);
    lcd.print(cardID);
    mfrc522.PICC_HaltA();
    delay(10000);
    lcd.clear();
}

vendredi 28 décembre 2018

NodeMCU Episode 6 :Matrice à LED 4x1088AS et Max7219


NodeMCU Episode 6 :Matrice à LED 4x1088AS et Max7219

Après l'arduino Nano, encore plus interessant avec l'ESP8266...
J'ai trouvé ce petit script, qui se connecte à un Wifi, lance un serveur, affiche l'ip sur l'afficheur LED, avec une page html et un formulaire qui inscrit sur l'affichage LED ce que l'on à saisi dans le formulaire.
Top tout est déjà fait :)

Branchements:

Max7219 - Nano
VCC - 3V
GND - G
DIN - D7
CS -  D8
CLK - D5


Librairie:(Croquis / Inclure une bibliothèque / Gérer les bibliothèques)
Ajoutez les librairies :
MD_MAX72XX by majicDesigns


Code:
Pour changer le sens du texte :

#define HARDWARE_TYPE MD_MAX72XX::ICSTATION_HW

 Sources:
http://www.etechpath.com/how-to-control-max7219-led-matrix-with-esp8266-wifi-module/

Code Adapté :
// IP address for the ESP8266 is displayed on the scrolling display
// after startup initialisation and connected to the WiFi network.
//
// Connections for ESP8266 hardware SPI are:
// Vcc 3v3 LED matrices seem to work at 3.3V
// GND GND GND
// DIN D7 HSPID or HMOSI
// CS or LD D8 HSPICS or HCS
// CLK D5 CLK or HCLK
//

#include <ESP8266WiFi.h>
#include <MD_MAX72xx.h>
#include <SPI.h>

#define PRINT_CALLBACK 0
#define DEBUG 0
#define LED_HEARTBEAT 0

#if DEBUG
#define PRINT(s, v) { Serial.print(F(s)); Serial.print(v); }
#define PRINTS(s) { Serial.print(F(s)); }
#else
#define PRINT(s, v)
#define PRINTS(s)
#endif


#if LED_HEARTBEAT
#define HB_LED D2
#define HB_LED_TIME 500 // in milliseconds
#endif

// Define the number of devices we have in the chain and the hardware interface
// NOTE: These pin numbers will probably not work with your hardware and may
// need to be adapted
#define MAX_DEVICES 4

#define CLK_PIN D5 // or SCK
#define DATA_PIN D7 // or MOSI
#define CS_PIN D8 // or SS

// SPI hardware interface
//MD_MAX72XX mx = MD_MAX72XX(CS_PIN, MAX_DEVICES);
#define HARDWARE_TYPE MD_MAX72XX::ICSTATION_HW //edit this as per your LED matrix hardware type
MD_MAX72XX mx = MD_MAX72XX(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);
// Arbitrary pins
//MD_MAX72XX mx = MD_MAX72XX(DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

// WiFi login parameters - network name and password
const char* ssid = "ssid_wifi"; // edit your wifi SSID here
const char* password = "mdp_wifi"; // edit your wifi password here

// WiFi Server object and parameters
WiFiServer server(80);

// Global message buffers shared by Wifi and Scrolling functions
const uint8_t MESG_SIZE = 255;
const uint8_t CHAR_SPACING = 1;
const uint8_t SCROLL_DELAY = 75;

char curMessage[MESG_SIZE];
char newMessage[MESG_SIZE];
bool newMessageAvailable = false;

char WebResponse[] = "HTTP/1.1 200 OK\nContent-Type: text/html\n\n";

char WebPage[] =
"<!DOCTYPE html>" \
"<html>" \
"<head>" \
"<title>ESP8266</title>" \
"<style>" \
"html, body" \
"{" \
"width: 600px;" \
"height: 400px;" \
"margin: 0px;" \
"border: 0px;" \
"padding: 10px;" \
"background-color: white;" \
"}" \
"#container " \
"{" \
"width: 100%;" \
"height: 100%;" \
"margin-left: 200px;" \
"border: solid 2px;" \
"padding: 10px;" \
"background-color: #b3cbf2;" \
"}" \
"</style>"\
"<script>" \
"strLine = \"\";" \
"function SendText()" \
"{" \
" nocache = \"/&nocache=\" + Math.random() * 1000000;" \
" var request = new XMLHttpRequest();" \
" strLine = \"&MSG=\" + document.getElementById(\"txt_form\").Message.value;" \
" request.open(\"GET\", strLine + nocache, false);" \
" request.send(null);" \
"}" \
"</script>" \
"</head>" \
"<body>" \
"<div id=\"container\">"\
"<H1><b>WiFi MAX7219 LED Matrix Display</b></H1>" \
"<form id=\"txt_form\" name=\"frmText\">" \
"<label>Msg:<input type=\"text\" name=\"Message\" maxlength=\"255\"></label><br><br>" \
"</form>" \
"<br>" \
"<input type=\"submit\" value=\"Send Text\" onclick=\"SendText()\">" \
"</div>" \
"</body>" \
"</html>";

char *err2Str(wl_status_t code)
{
switch (code)
{
case WL_IDLE_STATUS: return("IDLE"); break; // WiFi is in process of changing between statuses
case WL_NO_SSID_AVAIL: return("NO_SSID_AVAIL"); break; // case configured SSID cannot be reached
case WL_CONNECTED: return("CONNECTED"); break; // successful connection is established
case WL_CONNECT_FAILED: return("CONNECT_FAILED"); break; // password is incorrect
case WL_DISCONNECTED: return("CONNECT_FAILED"); break; // module is not configured in station mode
default: return("??");
}
}

uint8_t htoi(char c)
{
c = toupper(c);
if ((c >= '0') && (c <= '9')) return(c - '0');
if ((c >= 'A') && (c <= 'F')) return(c - 'A' + 0xa);
return(0);
}

boolean getText(char *szMesg, char *psz, uint8_t len)
{
boolean isValid = false; // text received flag
char *pStart, *pEnd; // pointer to start and end of text

// get pointer to the beginning of the text
pStart = strstr(szMesg, "/&MSG=");

if (pStart != NULL)
{
pStart += 6; // skip to start of data
pEnd = strstr(pStart, "/&");

if (pEnd != NULL)
{
while (pStart != pEnd)
{
if ((*pStart == '%') && isdigit(*(pStart+1)))
{
// replace %xx hex code with the ASCII character
char c = 0;
pStart++;
c += (htoi(*pStart++) << 4);
c += htoi(*pStart++);
*psz++ = c;
}
else
*psz++ = *pStart++;
}

*psz = '\0'; // terminate the string
isValid = true;
}
}

return(isValid);
}

void handleWiFi(void)
{
static enum { S_IDLE, S_WAIT_CONN, S_READ, S_EXTRACT, S_RESPONSE, S_DISCONN } state = S_IDLE;
static char szBuf[1024];
static uint16_t idxBuf = 0;
static WiFiClient client;
static uint32_t timeStart;

switch (state)
{
case S_IDLE: // initialise
PRINTS("\nS_IDLE");
idxBuf = 0;
state = S_WAIT_CONN;
break;

case S_WAIT_CONN: // waiting for connection
{
client = server.available();
if (!client) break;
if (!client.connected()) break;

#if DEBUG
char szTxt[20];
sprintf(szTxt, "%03d:%03d:%03d:%03d", client.remoteIP()[0], client.remoteIP()[1], client.remoteIP()[2], client.remoteIP()[3]);
PRINT("\nNew client @ ", szTxt);
#endif

timeStart = millis();
state = S_READ;
}
break;

case S_READ: // get the first line of data
PRINTS("\nS_READ");
while (client.available())
{
char c = client.read();
if ((c == '\r') || (c == '\n'))
{
szBuf[idxBuf] = '\0';
client.flush();
PRINT("\nRecv: ", szBuf);
state = S_EXTRACT;
}
else
szBuf[idxBuf++] = (char)c;
}
if (millis() - timeStart > 1000)
{
PRINTS("\nWait timeout");
state = S_DISCONN;
}
break;


case S_EXTRACT: // extract data
PRINTS("\nS_EXTRACT");
// Extract the string from the message if there is one
newMessageAvailable = getText(szBuf, newMessage, MESG_SIZE);
PRINT("\nNew Msg: ", newMessage);
state = S_RESPONSE;
break;

case S_RESPONSE: // send the response to the client
PRINTS("\nS_RESPONSE");
// Return the response to the client (web page)
client.print(WebResponse);
client.print(WebPage);
state = S_DISCONN;
break;

case S_DISCONN: // disconnect client
PRINTS("\nS_DISCONN");
client.flush();
client.stop();
state = S_IDLE;
break;

default: state = S_IDLE;
}
}

void scrollDataSink(uint8_t dev, MD_MAX72XX::transformType_t t, uint8_t col)
// Callback function for data that is being scrolled off the display
{
#if PRINT_CALLBACK
Serial.print("\n cb ");
Serial.print(dev);
Serial.print(' ');
Serial.print(t);
Serial.print(' ');
Serial.println(col);
#endif
}

uint8_t scrollDataSource(uint8_t dev, MD_MAX72XX::transformType_t t)
// Callback function for data that is required for scrolling into the display
{
static enum { S_IDLE, S_NEXT_CHAR, S_SHOW_CHAR, S_SHOW_SPACE } state = S_IDLE;
static char *p;
static uint16_t curLen, showLen;
static uint8_t cBuf[8];
uint8_t colData = 0;

// finite state machine to control what we do on the callback
switch (state)
{
case S_IDLE: // reset the message pointer and check for new message to load
PRINTS("\nS_IDLE");
p = curMessage; // reset the pointer to start of message
if (newMessageAvailable) // there is a new message waiting
{
strcpy(curMessage, newMessage); // copy it in
newMessageAvailable = false;
}
state = S_NEXT_CHAR;
break;

case S_NEXT_CHAR: // Load the next character from the font table
PRINTS("\nS_NEXT_CHAR");
if (*p == '\0')
state = S_IDLE;
else
{
showLen = mx.getChar(*p++, sizeof(cBuf) / sizeof(cBuf[0]), cBuf);
curLen = 0;
state = S_SHOW_CHAR;
}
break;

case S_SHOW_CHAR: // display the next part of the character
PRINTS("\nS_SHOW_CHAR");
colData = cBuf[curLen++];
if (curLen < showLen)
break;

// set up the inter character spacing
showLen = (*p != '\0' ? CHAR_SPACING : (MAX_DEVICES*COL_SIZE)/2);
curLen = 0;
state = S_SHOW_SPACE;
// fall through

case S_SHOW_SPACE: // display inter-character spacing (blank column)
PRINT("\nS_ICSPACE: ", curLen);
PRINT("/", showLen);
curLen++;
if (curLen == showLen)
state = S_NEXT_CHAR;
break;

default:
state = S_IDLE;
}

return(colData);
}

void scrollText(void)
{
static uint32_t prevTime = 0;

// Is it time to scroll the text?
if (millis() - prevTime >= SCROLL_DELAY)
{
mx.transform(MD_MAX72XX::TSL); // scroll along - the callback will load all the data
prevTime = millis(); // starting point for next time
}
}

void setup()
{
#if DEBUG
Serial.begin(115200);
PRINTS("\n[MD_MAX72XX WiFi Message Display]\nType a message for the scrolling display from your internet browser");
#endif

#if LED_HEARTBEAT
pinMode(HB_LED, OUTPUT);
digitalWrite(HB_LED, LOW);
#endif

// Display initialisation
mx.begin();
mx.control(MD_MAX72XX::INTENSITY, 0);
mx.setShiftDataInCallback(scrollDataSource);
mx.setShiftDataOutCallback(scrollDataSink);

curMessage[0] = newMessage[0] = '\0';

// Connect to and initialise WiFi network
PRINT("\nConnecting to ", ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED)
{
PRINT("\n", err2Str(WiFi.status()));
delay(500);
}
PRINTS("\nWiFi connected");

// Start the server
server.begin();
PRINTS("\nServer started");

// Set up first message as the IP address
sprintf(curMessage, "%03d:%03d:%03d:%03d", WiFi.localIP()[0], WiFi.localIP()[1], WiFi.localIP()[2], WiFi.localIP()[3]);
PRINT("\nAssigned IP ", curMessage);
}

void loop()
{
#if LED_HEARTBEAT
static uint32_t timeLast = 0;

if (millis() - timeLast >= HB_LED_TIME)
{
digitalWrite(HB_LED, digitalRead(HB_LED) == LOW ? HIGH : LOW);
timeLast = millis();
}
#endif

handleWiFi();
scrollText();
}