Harsha B MRajib_Kumar_Dey
Created April 20, 2018 © GPL3+

Organizational Automatic vending Machine

It is an institutional vending machine for vending the items to the persons, who are the members of that particular organization.

IntermediateFull instructions providedOver 4 days57
Organizational Automatic vending Machine

Things used in this project

Hardware components

RFID Module (Generic)
×1
WIZwiki-W7500
WIZnet WIZwiki-W7500
×1
WIZ750SR
WIZnet WIZ750SR
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1

Software apps and online services

MQTT
MQTT
PyCharm
arm mbed os

Hand tools and fabrication machines

Soldering iron (generic)
Soldering iron (generic)

Story

Read more

Schematics

W7500 Connection with sensors

Connection of RFID and Ultrasonic sensors with the W7500

W7500 Connection with LCD and Motor

Same Wizwiki W7500 is connected to LCD and Motor

W7500 and Wiz750SR Connection

The connection between W7500 and WIZ750SR using RS232 Serial cablefor serial communication between two boards

Code

Wizwiki-W7500 Code

C/C++
This is the code for sending the project data from Wizwiki-W7500 to WIZ750SR serially
//Connect as follows:
//RFID pins, motor         
//----------------------------------------
//RFID IRQ=pin5    ->   Not used. Leave open
//RFID MISO=pin4   ->   Nucleo SPI_MISO=PA_6=D12
//RFID MOSI=pin3   ->   Nucleo SPI_MOSI=PA_7=D11
//RFID SCK=pin2    ->   Nucleo SPI_SCK =PA_5=D13
//RFID SDA=pin1    ->   Nucleo SPI_CS  =PB_6=D10
//RFID RST=pin7    ->   Nucleo         =PA_9=D8
//3.3V and Gnd to the respective pins                              
// 1st Motor transistor  to Pin D9
// 2nd Motor transistor  to Pin D14
// Pin D0 to pin 2 of the serial Cable
// pin D1 to pin 3 of the serial cable
// pin A0 to the trigger of ultrasonic sensor 1
// pin A1 to the Echo of ultrasonic sensor 1                              
// pin D2 to RS pin of LCD
// pin D3 to E pin of LCD
// pin D4 to D4 pin of LCD
// pin D5 to D5 pin of LCD
// pin D6 to D6 pin of LCD
// pin D7 to D7 pin of LCD

//---------------------------------------------
#include "mbed.h"
#include "MFRC522.h"
#include "SPI.h"
#include "hcsr04.h"
#include "TextLCD.h"
#define ECHO_SERVER_PORT   7
#define SPI_MOSI D11
#define SPI_MISO D12
#define SPI_SCK D13
#define SPI_CS D10
#define MF_RESET D8
TextLCD lcd(D2, D3, D4, D5, D6, D7,TextLCD::LCD20x4); // rs, e, d4-d7
DigitalOut myled(D9);
DigitalOut myled1(D14);
//DigitalOut myled2(D15);    Can be enabled for 3rd motor slot.

HCSR04 sensor(A0,A1); // Trigger , Echo
HCSR04 sensor1(A2,A3); //Trigger , Echo
//HCSR04 sensor2(A4,A5); //Trigger , Echo   Can enable if needed for 3rd slot.

void distance();
void display();

//Serial connection to PC for output
Serial pc(USBTX, USBRX);
// Serial connection with WIZ750SR gateway for MQTT communication  
Serial serial(D1,D0);  //TX and RX
// Initializing RFID chip pins
MFRC522    RfChip   (SPI_MOSI, SPI_MISO, SPI_SCK, SPI_CS, MF_RESET);
    char c;
    int d;
int main(void) {
    pc.printf("starting...\n");
    myled=0;
    pc.printf("Wait a second...\r\n");
   
  //Init. RC522 Chip
  RfChip.PCD_Init();
 
  while (true) {
    pc.printf("enterd RFID reading loop...\n");
    // Look for new cards
    if ( ! RfChip.PICC_IsNewCardPresent())
    {
      wait_ms(500);
      continue;
    }
   // Select one of the cards
    if ( ! RfChip.PICC_ReadCardSerial())
    {
      wait_ms(500);
      continue;
    }
   
   char data[20]="";
   char data1[20]="";
    
    // Print Card UID
    pc.printf("Card UID: ");
    printf("Size of UID: %d \n",RfChip.uid.size);
    for (uint8_t i = 0; i < RfChip.uid.size; i++)
    {
      char temp[5];
      pc.printf(" %X02", RfChip.uid.uidByte[i]);
      sprintf(temp,"%X02", RfChip.uid.uidByte[i]);
      strcat(data,temp);
    }
    
    // Print Card type
    uint8_t piccType = RfChip.PICC_GetType(RfChip.uid.sak);
    pc.printf(" \nPICC Type: %s \n\r", RfChip.PICC_GetTypeName(piccType));
    wait_ms(1000);
    
    if(strcmp(data,"BA0211026102D302")==0)      //Comparing the stored data with the new data read by the RFID reader. 
    {   
        strcat(data1,"natsu");
        wait(1);
        serial.printf("%s",data1);
        wait(2);
        distance();
    }
    if(strcmp(data,"E8028002AC02E902")==0)
    {
        strcat(data1,"luffy");
        wait(1);
        serial.printf("%s",data1);
        wait(2);
        distance ();
    }
    pc.printf("The user name is :%s \n",data1);
   }
}


void distance()
{
     
    pc.printf("Entered into distance loop \n");
    while(1){
        long distance = sensor.distance();
        wait(0.5); 
        long distance1 = sensor1.distance();
        wait(0.5);
    //  long distance2 = sensor2.distance();             //can be enabled if connected to 3rd Ultrasonic sensor
        pc.printf("distance  %d  \n",distance);
        pc.printf("distance  %d  \n",distance1);
    //  pc.printf("distance  %d  \n",distance2);         //can be enabled if connected to 3rd Ultrasonic sensor to enable it in the PC.
        wait(1);
        
        wait(1.0); // 1 sec  
        if(distance<=10){
            myled= 1;
            wait(3);
            myled=0;
            serial.printf("/drink");
            c = '\0';
            c = 'd';
            d=15;
            display();
            pc.printf("/ item drink /cost 15");
            break;
            }
        else if(distance1<=10){
            myled1= 1;
            wait(3);
            myled1=0;
            serial.printf("/snack");
            c = '\0';
            c = 's';
            d=10;
            display();
            pc.printf("/item snack /cost 10");
            break;
          }
 /* else if(distance2<=10){
            myled1= 1;
            wait(30);
            myled1=0;
            serial.printf("/choco");
            c = '\0';
            c = 's';
            d=10;
            display();
            pc.printf("/snack/10");
            break;
          } */                                    //Can be enabled when 3rd ultrasonic is connected.
         
          }   
       }
       
                                 //function for LCD display ....
       
void display(){                                  
    lcd.locate(3,0);
    lcd.printf("Vending Machine\n");
    lcd.locate(0,2);
    if(c=='d'){
    lcd.printf("ITEM NAME: drink");
    }
    else if(c=='s')
    {
     lcd.printf("ITEM NAME: Snack");
    }
    lcd.locate(0,3);
    lcd.printf("ITEM COST: %d",d);
    }

WIZ750SR MQTT Code

C/C++
This is the code for WIZ750SR to receive the data from Wizwiki-W7500 and publish that data to MQTT broker
#include "mbed.h"
#include "SPI.h"
#include "MQTTEthernet.h"
#include "MQTTClient.h"

#define ECHO_SERVER_PORT   7
 
Serial pc(USBTX, USBRX);   //Enabling the Serial transmission between WIZ750SR and PC.
Serial serial(D1,D0);      // Enabling Serial transmission betwenn Wiz750SR and W7500. 
char c[100]="";

//  for subscribing the data and sending it to the W7500   
//void messageArrived(MQTT::MessageData& md)
//{
//    MQTT::Message &message = md.message;
//    printf("Message arrived: qos %d, retained %d, dup %d, packetid %d\n", message.qos, message.retained, message.dup, message.id);
//    printf("Payload %.*s\n", message.payloadlen, (char*)message.payload);
//    a.printf("%.*s\n", message.payloadlen, (char*)message.payload);
//    pc.printf("%.*s\n", message.payloadlen, (char*)message.payload);
//    //a.printf("%s", (char*)message.payload);
////     pc.printf("%s\n", (char*)message.payload);
//    ++arrivedcount;
//}                                                                  


 
int main(void) {
    printf("Wait a second...\r\n");
    char* topic = "ack";                    //if we are subscribing the acknowledgement.
    MQTTEthernet ipstack = MQTTEthernet();
    
    MQTT::Client<MQTTEthernet, Countdown> client = MQTT::Client<MQTTEthernet, Countdown>(ipstack);
    
    char* hostname = "xxx.xx.xx.x";   //Give the IP Address of the MQTT Broker.
    int port = xxxx;                  // Port number of the MQTT broker.  
    
 
    int rc = ipstack.connect(hostname, port);
    if (rc != 0)
    printf("rc from TCP connect is %d\n", rc);
    printf("Topic: %s\r\n",topic);
    
    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;       
    data.MQTTVersion = 3;
    data.clientID.cstring = "parents";

    if ((rc = client.connect(data)) == 0)
    printf("rc from MQTT connect is %d\n", rc);
   
 //   if ((rc = client.subscribe(topic, MQTT::QOS1, messageArrived)) == 0)
//    printf("rc from MQTT subscribe is %d\n", rc); 
//    client.yield(600000);                                           //  if we need to subscribe acknowledgement
   
   while (true) {
    if (serial.readable()) // if anything available/ readable in Serial port 
    {
        int i;
        c[i]=0;
        for(i=0;i<=10;i++){
        char c1=serial.getc();
        c[i] = c1;
    } 
     pc.printf("The value returned is %s ",c);
     MQTT::Message message;
     char buf[100];
     sprintf(buf, "%s", c);
     message.qos = MQTT::QOS0;
         message.retained = false;
         message.dup = false;

         message.payload = (void*)c;
         message.payloadlen = strlen(c);

         rc = client.publish("balance", message);
         pc.printf("Rc result: %c \n ",rc);
         client.yield(60);
    }
}
}

Server Code

Python
It is the python code used in the server, which is created using Pycharm to subscribe the data of the project from the MQTT broker and then publish acknowledgment with database values of the user
from flask import Flask, render_template
from flask_socketio import SocketIO
from flask_mqtt import Mqtt
from con_class import PostgresConnection

app = Flask(__name__)
app.config['SECRET'] = 'my secret key'
app.config['TEMPLATES_AUTO_RELOAD'] = True
# app.config['MQTT_BROKER_URL'] = 'broker.hivemq.com'
app.config['MQTT_BROKER_URL'] = '172.16.73.4'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = ''
app.config['MQTT_PASSWORD'] = ''
app.config['MQTT_KEEPALIVE'] = 5
app.config['MQTT_TLS_ENABLED'] = False


mqtt = Mqtt(app)
socketio = SocketIO(app)

test = 'balance'
mqtt.subscribe(test)

balance = 'balance1'

@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
    data = dict(
        topic=message.topic,
        payload=message.payload.decode()
    )
    print(data)
    if data['topic'] == test:
        user, cost = data['payload'].split('/')
        obj1 = PostgresConnection()
        cur = obj1.con.cursor()
        cur.execute("SELECT balance FROM public.hello WHERE name=(%s)", (user,))
        res = cur.fetchone()
        print(res[0])
        if cost == 'snack':
            cst = 10
        elif cost == 'drink':
            cst = 15
        else:
            cst = 20
        bal = int(res[0]) - cst
        cur.execute("UPDATE hello SET balance=(%s)  WHERE name=(%s)", (bal, user))
        obj1.con.commit()
        mqtt.publish('ack', 1)
        dat = 'Previous :' + str(res[0]) + '       Cost :' + str(cst) + '            Current :' + str(bal)
        mqtt.publish(balance, dat)


@app.route('/')
def getData():
    obj1 = PostgresConnection()
    cur = obj1.con.cursor()
    cur.execute("SELECT * FROM public.hello")
    res = cur.fetchall()
    return render_template('hello.html', data=res)


if __name__ == '__main__':
    app.run(debug=True, use_reloader=False)

Connection to database code

Python
This code connects the data to PostgreSQL database to access the previous data
from flask import Flask, render_template, request
import psycopg2
import psycopg2.extras
import pprint

app = Flask(__name__)


class PostgresConnection(object):

    instance = None
    con = None

    def __new__(cls):
        if PostgresConnection.instance is None:
            PostgresConnection.instance = object.__new__(cls)
        return PostgresConnection.instance

    def __init__(self):
        if PostgresConnection.con is None:
            try:
                PostgresConnection.con = psycopg2.connect("dbname=wiznet user=postgres password=postgres")
                print('Database connection opened.')
            except psycopg2.DatabaseError as db_error:
                print("Error :(0)".format(db_error))
        else:
            print(PostgresConnection.con)

    def __del__(self):
        if PostgresConnection.con is not None:
            PostgresConnection.close()
            print('Database connection closed.')


# obj1=PostgresConnection()
# cur=obj1.con.cursor()
# cur.execute("CREATE TABLE student(id serial PRIMARY KEY, name varchar(20), age integer NOT NULL)")
# cur.execute("SELECT * FROM VOTE")
# row= cur.fetchall()
# print(row)

HTML user interface code

HTML
This is the code to create a local HTML User Interface page to view the balance of all the users for the administrator.
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- meta -->
	<meta http-equiv="content type" content="text/html; charset=utf-8"/>

	<!-- title -->
	<title>Balance</title>

	<!-- css -->
	<!--<link rel="stylesheet" href="main.css" type="text/css" media="screen, projection"/>-->
<!--&lt;!&ndash; Latest compiled and minified CSS &ndash;&gt;-->
    <script>
	document.getElementById("demo").innerHTML = "Update";
</script>
<style>
    ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #cfcfcf;
}

li {
    float: left;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover:not(.active) {
    background-color: #cfcfcf;
}

.active {
    background-color: #4CAF50;
}
</style>
</head>
<ul>
  <li><a class="active" href="#home">HOME</a></li>
  <li><a href="#profile">PROFILE</a></li>
  <li><a href="#add_money">ADD TO BALANCE</a></li>
 </ul>

<h1><center>Organisational Vending machine</center></h1>
<h2><center>Balance Check</center></h2>
<h2><center>Administrator View</center></h2>
<br> </br>
<br> </br>
<table align="center" width="400" cellpadding="20" border="solid black">
    <tr bgcolor=#5a589c>
        <th>User Name</th>
        <th> Current Balance</th>
    </tr>
    {% for item in data %}
    <tr>
        <td align="center">{{item[0]}}</td>
        <td align="center">{{item[1]}}</td>
    </tr>
    {% endfor %}
</table>
</body>
</html>

Credits

Harsha B M

Harsha B M

1 project • 0 followers
I am a Engineering student. I have been developing from 3 years
Rajib_Kumar_Dey

Rajib_Kumar_Dey

0 projects • 0 followers

Comments