engineering – Blog eTechPath https://blog.etechpath.com Tue, 03 Jan 2023 12:41:13 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.4 https://blog.etechpath.com/wp-content/uploads/2017/08/BrandLogo12-150x150.png engineering – Blog eTechPath https://blog.etechpath.com 32 32 How to interface RFID read/write module RFID-RC522 with Arduino and read RFID tags with it. https://blog.etechpath.com/how-to-interface-rfid-readwrite-module-rfid-rc522-with-arduino-and-read-rfid-tags-with-it/ https://blog.etechpath.com/how-to-interface-rfid-readwrite-module-rfid-rc522-with-arduino-and-read-rfid-tags-with-it/#comments Sat, 19 May 2018 04:16:00 +0000 https://blog.etechpath.com/?p=591 About:

In this project i will explain how to interface MFRC522 based RFID read/write module RC522 with Arduino (arduino uno in my case). The example code is designed to read RFID tag unique number and identify the desired tag among’s them. A piezo buzzer and neopixel is also used in this project for visual and audible indication. Serial port is also programmed to view output in arduino IDE serial monitor.




Components: 

  1. RFID-RC522 13.56MHz read/write module           
  2. Arduino Uno           
  3. Neopixel           
  4. Piezo Buzzer       





Circuit Diagram:






Description:

    • RFID-RC522: This RFID module is designed to work on 3.3v (voltage level 2.5v to 3.3v). So, do not connect this module to arduino’s 5.0v supply. Other that power supply, connect all SPI interface pins to arduino as shown in the circuit diagram or refer bellow table.
      .
      RFID Pins     Arduino Pins
         SDA           10
         SCK           13
         MOSI          11
         MISO          12
         IRQ           NC
         GND           GND
         RST           8
         3.3v          3.3v

 

    • NeoPixel: Neopixel can work on both 5.0v or 3.3v. But 5.0v is better option to drive neopixel to obtain maximum brightness (in this project i have connected it with 3.3v for ease of circuit). So, connect neopixel power and ground with arduino and connect data line to arduino pin 5 as shown in the circuit diagram.                                                    Note: Here in this project i am using 12 pixels neopixel ring. You will need to update the code for number of pixel used, if you are using different that 12 pixels.

 

  • Piezo Buzzer: Pay attention while connecting piezo buzzer to your arduino, in my case i am using buzzer witch is specially designed for arduino and consumes safe current from arduino pin without frying it out. Arduino (ATmega168P – ATmega328P) IO pin can supply maximum 40ma per pin. So you need to check your piezo buzzer data sheet before connecting it with arduino, if it suppose to consume more current than the maximum limit then its a good choice to add one resistor in series with the buzzer.
    Let’s suppose if buzzer datasheet details are as bellow,
    Operating voltage: 5.0V
    Coil resistance: 50ΩThen, using Ohms law,
    V = IR
    5v = I x 50Ω
    I = 0.100Atheoretically we can see, this buzzer coil will consume 100mA current from arduino pin which probably can fry your arduino IO pin if you connect it without any current limiting resistance. So we need to reduce this current using current limiting resistance.

    As i mentioned above, arduino can supply 40mA maximum current per IO pin, but we will calculate our limiting resistance value according to 20mA limit to stay within safe condition.

    Again, using Ohms law,
    V = IR
    R = 5v/20mA
    R = 250Ω

    The buzzer coil already stated 50Ω resistance, so we will need to add 200Ω resistance in series with buzzer coil resistance which becomes 250Ω in total that exactly we want.





Code:

/* 
 *  Project: Interfacing MFRC522 based RFID Module RC522 with Arudino Uno 
 *  Author: Pranay Sawarkar
 *  Website: www.etechpath.com
 *  MFRC522 Library : https://github.com/ljos/MFRC522 
*/

#include <MFRC522.h>
#include <SPI.h>
#include <Adafruit_NeoPixel.h>
#define led_pin 5
Adafruit_NeoPixel strip = Adafruit_NeoPixel(12, led_pin, NEO_GRB + NEO_KHZ800);
#define SDAPIN 10 
#define RESETPIN 8 
#define Buzzer 3 

//variables to store data
byte FoundTag; 
byte ReadTag; 
byte TagData[MAX_LEN]; 
byte TagSerialNumber[5]; 
byte GoodTagSerialNumber[5] = {0x4C, 0x3B, 0xA0, 0x59}; //Good Tag Number (may different in your case)

MFRC522 nfc(SDAPIN, RESETPIN);

void setup() 
{
pinMode(Buzzer, OUTPUT); 
digitalWrite(Buzzer, LOW);
SPI.begin();
Serial.begin(115200);

//NEO Pixel LED strip setup
strip.begin();
strip.show();

// Start searching RFID Module
Serial.println("Searching for RFID Reader");
nfc.begin();
byte version = nfc.getFirmwareVersion(); // store the reader version in variable

// If can not find RFID Module 
if (! version) { 
Serial.print("Failed to search RC522 board, please check the hardware.");
while(1); //Wait until a RFID Module is found
}

// If found, print the information of detected RFID Module in serial monitor.
Serial.print("RC522 Module Found ");
Serial.println();
Serial.print("Firmware version: 0x");
Serial.println(version, HEX);
Serial.println();
}

//NeoPixel LED animation script 
void colorWipe(uint32_t c, uint8_t wait) 
{
  for(uint16_t i=0; i<strip.numPixels(); i++) 
  {
    strip.setPixelColor(i, c);
    strip.show();
    delay(wait);
  }
}

void loop() {

//Searching for RFID Tag indication.
colorWipe(strip.Color(0, 0, 255), 50); // Blue
colorWipe(strip.Color(0, 0, 0), 50); //OFF

//Detecting good Tag
String GoodTag="False";
FoundTag = nfc.requestTag(MF1_REQIDL, TagData);

if (FoundTag == MI_OK) {
delay(200);

ReadTag = nfc.antiCollision(TagData);
memcpy(TagSerialNumber, TagData, 4);

Serial.println("Tag detected.");
Serial.print("Serial Number: ");
// Loop for printing serial number in serial monitor
for (int i = 0; i < 4; i++) {
Serial.print(TagSerialNumber[i], HEX);
Serial.print(", ");
}
Serial.println("");
Serial.println();


// Check the detected tag number is matching with good tag number or not.
for(int i=0; i < 4; i++){
if (GoodTagSerialNumber[i] != TagSerialNumber[i]) 
{
break; // if not equal, then break out of the "for" loop
}
if (i == 3) { // if we made it to 4 loops then the Tag Serial numbers are matching
GoodTag="TRUE";
} 
}
if (GoodTag == "TRUE"){
Serial.println("TAG Matched ... !");
Serial.println();
//Tag matching indication
colorWipe(strip.Color(0, 255, 0), 50); // Green
colorWipe(strip.Color(0, 0, 0), 50); // OFF
//loop for buzzer tone
for (int y = 0; y < 3; y++){
digitalWrite (Buzzer, HIGH) ;
delay (50) ; 
digitalWrite (Buzzer, LOW) ;
delay (50) ;
}
delay(500);
}
else {
Serial.println("TAG does not Matched .....!");
Serial.println();
//Tag not matching indication
colorWipe(strip.Color(255, 0, 0), 50); // RED
colorWipe(strip.Color(0, 0, 0), 50); // OFF
//loop for buzzer tone
for (int y = 0; y < 3; y++){
digitalWrite (Buzzer, HIGH) ;
delay (300) ;
digitalWrite (Buzzer, LOW) ;
delay (400) ;
}
delay(500); 
}
}
}





Working video:





Downloads:

MFRC522 IC datasheet

Circuit Digram

Code.ino


]]>
https://blog.etechpath.com/how-to-interface-rfid-readwrite-module-rfid-rc522-with-arduino-and-read-rfid-tags-with-it/feed/ 1
How to Control MAX7219 LED Matrix with ESP8266 WiFi Module https://blog.etechpath.com/how-to-control-max7219-led-matrix-with-esp8266-wifi-module/ https://blog.etechpath.com/how-to-control-max7219-led-matrix-with-esp8266-wifi-module/#comments Sat, 02 Dec 2017 00:40:20 +0000 https://blog.etechpath.com/?p=496 About this Project:
In this project we will learn how to interfacing ESP8266 module with MAX7219 matrix display to scrolling text message from web user interface. We will use Arduino IDE to program ESP module in this project. I am using MajicDesigns MD_MAX72xx library for running this project, also the code is very similar to included example in the library with some improvements in web user interface html code.




Components:

  1. MAX7219 8×8 LED Matrix
  2. ESP8266 Node MCU
  3. USB Cable for programming and power

Circuit Diagram:

Steps: 

      1. Connect the circuit as shown above.
      2. Install Arduino IDE form arduino website. After that install ESP8266 board and library in Arduino IDE.
      3. Download and install MD_MAX7219 Library from download section for driving MAX7219 matrix. For using this library you will need to edit MAX72xx.h file for configure the type of LED matrix you are using. In this project we are using FC-16 Chinese module.
      4. Download code ino file from download section and open it with Arduino IDE.
      5. You will need to edit WiFi network SSID and Password inside your code before flashing it in ESP module.
        const char* ssid = "your SSID";                   // edit your wifi SSID here
        const char* password = "your Password";            // edit your wifi password here
      6. Select board to NodeMCU and flash the code in ESP module.
      7. Power up the circuit and you will see IP address of your ESP module allocated by your WiFi network on Matrix display. (watch video)



    1. Now open that IP address in any browser connected in same network. And you will see web user interface to enter text.
    2. For detailed procedure of configuring WiFi module with your home network and using web interface, please watch embedded YouTube video linked at the bottom of this page.

Code:

//Link: https://blog.etechpath.com

#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	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::PAROLA_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 = "your SSID";                   // edit your wifi SSID here
const char* password = "your Password";            // 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>eTechPath MAX7219 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()\">" \
"<p><b>Visit Us at</b></p>" \ 
"<a href=\"http://www.eTechPath.com\">www.eTechPath.com</a>" \
"</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.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();
}

Downloads:

  1. Arduino IDE
  2. ESP8266 Arduino Library
  3. MajicDesigns MD_MAX7219 Library
  4. Code.ino

Video:

How to solve mirror image and orientation problems of matrix display if you are using old MD_MAX72xx library.

]]>
https://blog.etechpath.com/how-to-control-max7219-led-matrix-with-esp8266-wifi-module/feed/ 34