Kamis, 28 Oktober 2021

Raspi LCD 16x2

 import smbus
import time
 
# Define some device parameters
I2C_ADDR  = 0x27 # I2C device address
LCD_WIDTH = 16   # Maximum characters per line

# Define some device constants
LCD_CHR = 1 # Mode - Sending data
LCD_CMD = 0 # Mode - Sending command
LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line
LCD_LINE_2 = 0xC0 # LCD RAM address for the 2nd line
LCD_LINE_3 = 0x94 # LCD RAM address for the 3rd line
LCD_LINE_4 = 0xD4 # LCD RAM address for the 4th line
LCD_BACKLIGHT  = 0x08  # On
#LCD_BACKLIGHT = 0x00  # Off
ENABLE = 0b00000100 # Enable bit
# Timing constants
E_PULSE = 0.0005
E_DELAY = 0.0005
#Open I2C interface
#bus = smbus.SMBus(0)  # Rev 1 Pi uses 0
bus = smbus.SMBus(1) # Rev 2 Pi uses 1

def lcd_init():
  # Initialise display
  lcd_byte(0x33,LCD_CMD) # 110011 Initialise
  lcd_byte(0x32,LCD_CMD) # 110010 Initialise
  lcd_byte(0x06,LCD_CMD) # 000110 Cursor move direction
  lcd_byte(0x0C,LCD_CMD) # 001100 Display On,Cursor Off, Blink Off 
  lcd_byte(0x28,LCD_CMD) # 101000 Data length, number of lines, font size
  lcd_byte(0x01,LCD_CMD) # 000001 Clear display
  time.sleep(E_DELAY)

def lcd_byte(bits, mode):
  # Send byte to data pins
  # bits = the data
  # mode = 1 for data
  #        0 for command
  bits_high = mode | (bits & 0xF0) | LCD_BACKLIGHT
  bits_low = mode | ((bits<<4) & 0xF0) | LCD_BACKLIGHT
  # High bits
  bus.write_byte(I2C_ADDR, bits_high)
  lcd_toggle_enable(bits_high)
  # Low bits
  bus.write_byte(I2C_ADDR, bits_low)
  lcd_toggle_enable(bits_low)

def lcd_toggle_enable(bits):
  # Toggle enable
  time.sleep(E_DELAY)
  bus.write_byte(I2C_ADDR, (bits | ENABLE))
  time.sleep(E_PULSE)
  bus.write_byte(I2C_ADDR,(bits & ~ENABLE))
  time.sleep(E_DELAY)

def lcd_string(message,line):
  # Send string to display
  message = message.ljust(LCD_WIDTH," ")
  lcd_byte(line, LCD_CMD)
  for i in range(LCD_WIDTH):
    lcd_byte(ord(message[i]),LCD_CHR)

def main():
  # Main program block
  # Initialise display
  lcd_init()
  while True:
    # Send some test
    lcd_string("RPiSpy         <",LCD_LINE_1)
    lcd_string("I2C LCD        <",LCD_LINE_2)
    time.sleep(3)
  
    # Send some more text
    lcd_string(">         RPiSpy",LCD_LINE_1)
    lcd_string(">        I2C LCD",LCD_LINE_2)
    time.sleep(3)
if __name__ == '__main__':
  try:
    main()
  except KeyboardInterrupt:
    pass
  finally:
    lcd_byte(0x01, LCD_CMD)

Raspi Insatall dan Koneksi Database New

UPDATE:

sudo apt-get update && sudo apt-get upgrade


RASPI INSATLL DATABASE SERVER:

sudo apt-get install python3-dev libmysqlclient-dev
sudo pip3 install mysqlclient

ATAU

sudo apt-get install python3-dev **default-libmysqlclient-dev**

sudo pip3 install mysqlclient


INSTALL PIP3

sudo python3-pip


INSTALL CV2

sudo apt update

sudo apt install python3-opencv


CONFIG CAMERA DLL

sudo raspi-config
df -h
sudo reboot


LCD:

 sudo raspi-config

 sudo apt-get install i2c-tools

 sudo apt-get install python-smbus

 i2cdetect -y 1

 

import MySQLdb
from time import sleep
db = MySQLdb.connect("localhost","root","","2021_deteksicitra")
cursor = db.cursor()
sql = "UPDATE `tb_pengujian`  set `status`='1',`rekapitulasi`='%s',`bobot`='%s',`kategori`='%s' where id_pengujian='%s'" % (rekapitulasi,bobot,kategori,idx)
#print(sql)
try:
cursor.execute(sql)
db.commit()
v=1
except:
db.rollback()
    db.close() 

while (True):
    ada=0
    db = MySQLdb.connect("localhost","root","","2021_deteksikentang")
    cursor = db.cursor()
    
    cursor.execute("SELECT `id_pengujian`, `nama_pengujian`, `gambar`,`status` FROM `tb_pengujian` where status='0' order by id_pengujian desc")
    for row in cursor.fetchall():
        ada=1
        id_pengujian=row[0]
        nama_pengujian=row[1]
        gambar=row[2]
        status=row[3]
        
        lokasi = PATH_UJI+gambar  
        print(lokasi)
        LoadCNN(lokasi,id_pengujian,rekapitulasi,bobot)
    time.sleep(1)
    db.close()

XRDP GUI Remote Control Raspi

 

1.Buat User baru yang memiliki password jika belum ada, misal

sudo adduser adi

sudo usermod adi -a -G pi,adm,dialout,cdrom,sudo,audio,video,plugdev,games,users,input,netdev,spi,i2c,gpio


2.Update Raspi, agar sehingga bisa kita remote jarak jauh secara FULL GUI

sudo apt update

sudo apt-get install raspberrypi-ui-mods xinit xserver-xorg

sudo reboot


3.Konfigurasi XRDP

sudo apt install xrdp 

systemctl show -p SubState --value xrdp

sudo adduser xrdp ssl-cert  


4.Jalankan RemoteControl Windows (ketik mstc)


5.Masukkan IP raspi (buat jadi satu jaringan ya...sama2 dalam router yang sama antara raspi dan laptop)







Rabu, 01 Juli 2020

OPENCV INSTALL



PYTHON OPENCV

pip install opencv-python
pip install opencv-contrib-python

atau

conda install opencv

TeSTING:
import cv2
print cv2.__version__

atau
python3 -c "import cv2"


ATAU CARA LAIN:
apt-get install -y libsm6 libxext6 libxrender-dev
pip3 install opencv-python
python3 -c "import cv2"


pip install PACKAGE_NAME
where PACKAGE_NAME can be
opencv-python (only contains main modules)
opencv-contrib-python (contains both main and contrib modules)
opencv-python-headless (same as opencv-python but without GUI functionality)
opencv-contrib-python-headless (same as opencv-contrib-python but without GUI functionality)

Perintah Dasar Mysql /UJI


PERINTAH DASAR MYSQL:

status;
select user();
SHOW VARIABLES WHERE Variable_name = 'port';
SHOW VARIABLES WHERE Variable_name = 'hostname';
select user(); 

SELECT system_user();

//PORT "mysql://user:pass@hostname:port/db"
SELECT @@port; //3306 is default

//HOSTNAME DB
SELECT @@hostname;

show variables like "%port%";

mysql -u root -p
GRANT ALL PRIVILEGES ON *.* TO 'username'@'localhost' IDENTIFIED BY 'password';
Atau
GRANT SELECT ON *.* TO 'username'@'localhost';


CREATE DATABASE dbname;
USE dbname;
CREATE TABLE example ( id smallint unsigned not null auto_increment, name varchar(20) not null, constraint pk_example primary key (id) );

INSERT INTO example ( id, name ) VALUES ( null, 'Sample data' );
DROP TABLE tablename;

PHPmyadmin di raspberry


Install cara ini:
https://www.howtoforge.com/tutorial/install-apache-with-php-and-mysql-lamp-on-debian-stretch/

JIKA ADA KENDALA...IKUTI LANGKAH SBB:

sudo apt install apache2
sudo apt install mariadb-server mariadb-client
sudo apt install php php-mysql
sudo apt install phpmyadmin

Harus disetting webserver phpmyadminnya:
PILIH apache2
BUAT phpmyadmin database =YES
HARUS KASIH password untuk phpmyadmin user DAN  strong password
JIKA DIKOSONGKAN AKAN GENERATE PASSWORD SENDIRI

UNTUK MEMAKAI phpMyAdmin GUNAKAN third user.
The root-user is not accessible to phpMyAdmin and the phpmyadmin-user doesn't have the required privileges, to administer MariaDB. 
SOLUSI:

sudo mysql

Atau kasih hak akses semua user:
sudo /usr/sbin/mysqld --skip-grant-tables

Atau update phpmyadminnya:
sudo apt update; 
sudo apt install apache2 phpmyadmin;


ATAU CARA REMOVE1 LALU INSTALL LG:
sudo apt remove mariadb-server mariadb-client phpmyadmin php --purge
sudo rm /var/www/html/phpmyadmin

CARA REMOVE2 LALU INSTALL LG:
sudo apt remove mariadb-server mariadb-client phpmyadmin php --purge
sudo apt autoremove --purge

HASILNYA SAMA ANTARA:
 /var/www/html/index.html
 /usr/share/doc/apache2/



Jika Gagal load phpmyadmin setelah install:

edit pakai nano:
nano /etc/apache2/apache2.conf

ketikkan kode sbb paling bawah:
Include /etc/phpmyadmin/apache.conf

Restart service:
sudo service apache2 restart
atau
sudo systemctl restart apache2

Jika gagal restart juga?
ln -s /etc/phpmyadmin/apache.conf /etc/apache2/sites-enabled/001-phpmyadmin
atau
sudo dpkg-reconfigure phpmyadmin


OMG JIKA TERJADI SBB:
ERROR 1045: Access denied for user: 'root@localhost' (Using
password: NO)

atau

ERROR 1045: Access denied for user: 'root@localhost' (Using
password: YES)

+++++++++++++++++++++++++
To reset your mysqld password just follow these instructions :

Stop the mysql demon process using this command :
   sudo /etc/init.d/mysql stop

Start the mysqld demon process using the --skip-grant-tables option with this command
   sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &

Because you are not checking user privs at this point, it's safest to disable networking. In Dapper, /usr/bin/mysqld... did not work. However, mysqld --skip-grant-tables did.

+++++++++++++++++++
start the mysql client process using this command
   mysql -u root
from the mysql prompt execute this command to be able to change any password
   FLUSH PRIVILEGES;
Then reset/update your password
   SET PASSWORD FOR root@'localhost' = PASSWORD('password');
If you have a mysql root account that can connect from everywhere, you should also do:
   UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';

++++++++++++++++++
Alternate Method:
   USE mysql
   UPDATE user SET Password = PASSWORD('newpwd')   WHERE Host = 'localhost' AND User = 'root';
 
And if you have a root account that can access from everywhere:
   USE mysql
   UPDATE user SET Password = PASSWORD('newpwd')   WHERE Host = '%' AND User = 'root';
 
For either method, once have received a message indicating a successful query (one or more rows affected), flush privileges:

FLUSH PRIVILEGES;
Then stop the mysqld process and relaunch it with the classical way:

sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start

When you have completed all this steps ,you can easily access to your mysql server with the password you have set in the step before.
An easy way to have a full control of your mysql server is phpmyadmin (www.phpmyadmin.net), software made in php that can give you a web interface that can be very usefull to people that havent got a lot of confidence with bash .

To install phpmyadmin on you server you will need to have 4 things:

web server apache
php
mysql server/mysql client installed
php_mysql support for apache
All packages can be found browsing synaptic.

JIKA MASIH GATOT:
sudo apt-get --purge remove mysql-server mysql-common mysql-client
sudo apt-get install mysql-server mysql-common mysql-client

In the next step be sure to chance the your-new-password with the password you want!

mysqladmin -u root password your-new-password
sudo /etc/init.d/mysql restart

mysql -u root -p
You should now be logged in as root. Make sure to notedown your password! Thanks to Illuvator for posting this method in the ubuntu forum.

The Easiest Method

sudo dpkg-reconfigure mysql-server-N.N



+++++++++++++++++

JIKA LOOP ERROR:

You have to reconfigure phpmyadmin, reset MySQL password.

Reconfigure phpmyadmin
Ctrl + Alt + T to launch terminal
sudo dpkg-reconfigure phpmyadmin
Connection method for MySQL database for phpmyadmin: unix socket
Name of the database's administrative user: root
Password of the database's administrative user: mysqlsamplepassword
MySQL username for phpmyadmin: root
MySQL database name for phpmyadmin: phpmyadmin
Web server to reconfigure automatically: apache2
ERROR 1045
ignore
sudo dpkg-reconfigure mysql-server-5.5
New password for the MySQL "root" user: mysqlsamplepassword
Repeat password for the MySQL "root" user: mysqlsamplepassword


SOLUSI:
mysql -u root -p

Entered the root password Created a new user using the following command:

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'some_very_complex_password';

Granted all permissions to newuser:

GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';
FLUSH PRIVILEGES;

CEK ULANG:
By "rootuser" you mean the MySQL root user, not the system root user, right?

During the installation of mysql-server, the MySQL root account is created and its password is stored in /etc/mysql/debian.cnf.

The configuration files of phpMyAdmin are stored in /etc/phpmyadmin.


echo "UPDATE mysql.user SET plugin = 'mysql_native_password' WHERE user = 'root' AND plugin = 'unix_socket';FLUSH PRIVILEGES;" | mysql -u root -p


I installed MySQL using synaptic manager. Didn't have to enter a root password. The command:

mysqladmin -u root password NEWPASSWORD

Edit:
/etc/phpmyadmin/config.inc.php
Not:
/usr/share/phpmyadmin/config.inc.php

echo "UPDATE mysql.user SET plugin = 'mysql_native_password' WHERE user = 'root' AND plugin = 'unix_socket';
FLUSH PRIVILEGES;" | mysql -u root -p



https://www.raspberrypi.org/forums/viewtopic.php?t=216346
https://help.ubuntu.com/community/MysqlPasswordReset
https://askubuntu.com/questions/34409/unable-to-login-to-phpmyadmin-with-the-root-user

Selasa, 06 November 2018

Raspi sebagai LCD Proyektor

Ceritanya

Dosen login....dia scan semua PC di jaringannya...muncullah ip ip computer para siswanya
trus dia piih salah satu untuk presentasi....
maka pc yang dia klik akan tertuju di layar utama...

Konsepnya adalah sama dengan remote desktop...hanya ini di modif seakan2:
LCD proyektor,.........

++++++++++++++++++++++++++++++++++++++++++++++++++


metode u aplikasi Impelemantasi share desktop raspberry PI untuk LCD projector adalah menggunakan metode pencocokan content atau biasa di sebut dgn sequential search

cara kerjanya:
1.admin/dosen/moderator dosen akan menscan IP di jaringan kelas tsb
sehingga akan ketahuan IP mana saja yang aktif dan yang tidak aktif
2.admin/dosen/moderator memilih ip yang akan di munculkan layar desktopnya ke monitor
3.disini diperlukan admin/moderator/dosen agar tidak terjadi rebutan klik ip yang akan aktif
4.konsep koneknya adalah, dengan terlebih dahulu mendiskonek perangkat /laptop sebelumnya baru autokonek ip laptop terpilih
5.ada tombol juga reset all yang artinya diskonesi ke semua pc client dari layar monitor
6.semua aktivitas akan tercatat di tabel log

keterbatasan:
1.aplikasi hanya bisa diterapkan dalam 1 jaringan network/satu subnetmask
2.pengenalan antar laptop adalah menggunakan ip address sehingga setiap laptop agar mudah dikenali siapa pemiliknya maka harus di daftarkan dahulu
3.harus install library apliaksi di client juga

novelty/nilai kebaruan aplikasi ini dari sebelumnya:
1.aplikasi berbasis cient server sehingga mudah memantaunya bisa berbasis desktop, mobile(android), web
2.adanya tabel .log u menyimpan semua aktivitas
3.adanya fitur scan sehingga pc/laptop bisa ditambah atau dikurangkan secara dinamis


Nah ino code veri dosennya:


 <?php

if(isset($_GET["scan"])){
$sql="insert into tb_command values('scan')";
process($conn,$sql);
                echo "<script>alert('Please wait 30 seconds then press OK button')</script>";
                //sleep(30);
                die("<script>location.href='?mnu=controlpanel'</script>");
}

if(isset($_GET["close"])){
  $sql="update tb_status set status='standby'";// where ip='$ip'
        process($conn,$sql);

  $sql="insert into tb_command values('close')";
process($conn,$sql);
die("<script>location.href='?mnu=controlpanel'</script>");
}

if(isset($_GET["st"])){
$kode_status=$_GET["kode"];
$ip=$_GET["id"];
$st=$_GET["st"];

$sql="update tb_status set status='$st' where ip='$ip'";
process($conn,$sql);

if($st=="on"){
//$sql="insert into tb_close values('close')";
$sql="update tb_status set status='$st' where ip='$ip'";
                process($conn,$sql);

$sql="insert into tb_command values('on#$ip')";
process($conn,$sql);
                echo "<script>alert('Your session will expire in 15 minutes')</script>";
die("<script>location.href='?mnu=controlpanel'</script>");
}
else{//standby
$sql="insert into tb_command values('close')";
process($conn,$sql);
die("<script>location.href='?mnu=controlpanel'</script>");
}
}
?>

<div id="accordion">
  <h3>Data</h3>
  <div><p style="text-align:left;">

    <a href="tightvnc-2.8.8-gpl-setup-32bit.msi">Download software presentasi (Win32)</a></span></p>
    <span style="float:right;"> <a href="tightvnc-2.8.8-gpl-setup-64bit.msi">Download software presentasi (Win64)</a></span>
  <br>

<table width="50%" class="table table-bordered table-striped table-hover js-basic-example dataTable">
  <tr bgcolor="#036">
    <th width="3%"><center>No</th>
    <th width="30%"><center>IP</th>
    <th width="15%"><center>Status</th>
    <th width="10%"><center>Jam</th> 
    <th width="10%"><center>PLAY</th> 
  </tr>
<?php
  $sql="select * from `$tbstatus` order by `kode_status` desc";
  $jum=getJum($conn,$sql);
if($jum > 0){
$no=1;
$arr=getData($conn,$sql);
foreach($arr as $d) {
$kode_status=$d["kode_status"]; ;
$jam=$d["jam"];
$ip=$d["ip"];
$status=$d["status"];
$color="#dddddd";
if($no %2==0){$color="#eeeeee";}
echo"<tr bgcolor='$color'>
<td>$no</td>
<td align='center'>$ip</td>
<td align='center'>$status</td>
<td align='center'>$jam</td>";

if($status=="on"){
echo"<td align='center'>
<a href='?mnu=controlpanel&st=standby&kode=$kode_status&id=$ip'><input type='button' value='$status'></a>
</td>";
}
else{
echo"<td align='center'><a href='?mnu=controlpanel&st=on&kode=$kode_status&id=$ip'><input type='button' value='$status'></a></td>";
}

echo"</tr>";

$no++;
}//while
}//if
else{echo"<tr><td colspan='7'><blink>Maaf, Data status belum tersedia...</blink></td></tr>";}
?>
</table>
</div>


</div>
<a href='?mnu=controlpanel&scan=scan'><input type='button' value='SCAN IP'></a>
<a href='?mnu=controlpanel&close=close'><input type='button' value='CLOSE ALL'></a>

Sedang di raspinya:


import MySQLdb
from time import gmtime, strftime
from random import randint
import time
import subprocess
import os
import os, sys

data1=""
data2=""
data3=""

start=0
kon=1
paketimer=False

while kon==1:

    sql="SELECT * FROM tb_command"
    db = MySQLdb.connect("localhost","dian","12345","db_matakuliah")
    cursor = db.cursor()
    proses=0

    cursor.execute(sql)
    res = cursor.fetchall()
    mdata=""
    time.sleep(1)

    if paketimer==True:
      if time.time() > start + 900:
        os.system("pkill vncviewer")
        sql = "UPDATE tb_status set status='standby', keterangan='-' where status='on'"
        try:
           cursor.execute(sql)
           db.commit()
        except:
           db.rollback() 

    for row in res :
        mdata =row[0]

        print(mdata)
        data = mdata.split("#")

        if len(data)==1:
            data1=data[0]
        elif len(data)==2:
            data1=data[0]
            data2=data[1]
        elif len(data)==3:
            data1=data[0]
            data2=data[1]
            data3=data[2]
         
        proses =0
        if len(data)==1: 
            if data1 == "scan": #scan
                print "SCAN"
                proses=1
                #SCAN

                sql="Truncate tb_status"
                try:
                     cursor.execute(sql)
                     db.commit()
               
                except:
                     db.rollback()
               
                with open(os.devnull, "wb") as limbo:
                    for n in xrange(100, 150):
                        ip="192.168.1.{0}".format(n)
                        result=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "1", ip],
                        stdout=limbo, stderr=limbo).wait()
                        if result:
                            print ip, "offline"
                        else:
                            print ip, "online"
                            tanggal=strftime("%Y-%m-%d", gmtime())
                            jam=strftime("%H:%M:%S", gmtime())
                            sql="INSERT INTO `tb_status` (`tanggal` ,`jam` ,`ip` ,`status` ,`keterangan`) VALUES('%s','%s','%s','%s','%s')" % (tanggal,jam,ip,'standby','-')
                            print sql
                            try:
                                cursor.execute(sql)
                                db.commit()
                            except:
                                db.rollback()
            elif data1 == "close":
                  proses=1
                  print "CLOSE"
                  os.system("pkill vncviewer")
                  paketimer=False

        elif len(data)<=3: 
            if data1 == "on": #on#192.168
                proses=1

                ip=data2
                tanggal=strftime("%Y-%m-%d", gmtime())
                jam=strftime("%H:%M:%S", gmtime())
                keterangan=data1

                sql="Truncate tb_command"
                try:
                     cursor.execute(sql)
                     db.commit()

                except:
                     db.rollback()


                sql ="UPDATE `tb_status` set `status`='%s', `jam`='%s', `tanggal`='%s', `keterangan`='%s' where ip='%s'" % ('on',jam,tanggal,keterangan,ip)
                #print (sql)
                try:
                     cursor.execute(sql)
                     db.commit()
                except:
                     db.rollback()

                #AL = os.system("./vnc2.sh "+ ip)
                subprocess.Popen(["./vnc2.sh", ip])
                paketimer=True
                start = time.time()

             
        print "OK-LOPS----"
        if proses==1:
            sql="Truncate tb_command"
            try:
                 cursor.execute(sql)
                 db.commit()
               
            except:
                 db.rollback()
    cursor.close ()
    db.close () 



+++++++++++++
sedang Bash Shell nya sbb: vnc2.sh

#!/bin/bash

ssvnc -cmd -viewer -scale 0.75  -fullscreen $1

+++++++++++++
tabelnya sbb:

CREATE TABLE `tb_command` (
  `command` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


CREATE TABLE `tb_status` (
  `kode_status` int(15) NOT NULL,
  `tanggal` date NOT NULL,
  `jam` time NOT NULL,
  `ip` varchar(20) NOT NULL,
  `status` varchar(15) NOT NULL,
  `keterangan` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `tb_status` (`kode_status`, `tanggal`, `jam`, `ip`, `status`, `keterangan`) VALUES
(1, '2018-10-30', '15:50:51', '192.168.1.8', 'standby', '-'),
(2, '2018-10-30', '15:50:51', '192.168.1.9', 'standby', '-'),
(3, '2018-10-30', '15:59:49', '192.168.1.10', 'on', 'on'),
(4, '2018-10-30', '15:50:52', '192.168.1.11', 'standby', '-');



Ok mudah yaaaaaaaaaaaaaaaaaaaaaaaaaa

 




Rabu, 03 Januari 2018

Aplikasi Counter Bank GUI

Teman-teman sy ingin berbagi tentang penerapan raspberry untuk aplikasi counter di RS, Bank dll
cara kerjanya adalah: sistem raspberry menerima data serial dari PC operator
msial operator2 mengirimkand data antrian U77

maka secara background : PC tsb akan mengirimkan data serialnya ke raspberry
dan raspberry akan meresponnya dengan menampilkannya secara Realtime ke display moitornya
Sederhana namun bobot dari koding ini adalah sbb:
+Realtime GUI
+Realtime Serial Event
+Python Berbasis GUI

Harapannya semoga aplikasi ini bisa menambah kecintaan kita pada raspberry PI....CMIIw :-)


from PyQt5 import QtCore, QtGui, QtWidgets
import serial
import time, threading
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtWidgets
global ser
ser = serial.Serial('/dev/ttyUSB0', baudrate=1200, timeout=10,
                    parity=serial.PARITY_NONE,
                    stopbits=serial.STOPBITS_ONE,
                    bytesize=serial.EIGHTBITS
                    )



class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        desktop = QDesktopWidget()
     
        screenwidth = desktop.screen().width()+100
        screenheight = desktop.screen().height()+100
        top=screenheight/7
        bottom=screenheight-top-top-100
   
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(screenwidth, screenheight)
        MainWindow.setStyleSheet("background-color: #003366;")
     
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.lbl = QtWidgets.QLabel(self.centralwidget)
        self.lbl.setGeometry(QtCore.QRect(-5, top-100, screenwidth, 80))
        self.lbl.setStyleSheet("color: #FFFFFF;font:Bold")
        self.lbl.setFont(QFont('Xtreme Chrome',60))
        self.lbl.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl.setObjectName("lbl")
     
        self.lblCounter = QtWidgets.QLabel(self.centralwidget)
        self.lblCounter.setGeometry(QtCore.QRect(-5, top+30, screenwidth, 300))
        self.lblCounter.setStyleSheet("background-color: #000000; color: #FFFF00;font:Bold")
        self.lblCounter.setFixedHeight(300)
        self.lblCounter.setAlignment(QtCore.Qt.AlignCenter)
        self.lblCounter.setFont(QFont('Xtreme Chrome',250))
        self.lblCounter.setObjectName("lblCounter")

        self.lblLoket = QtWidgets.QLabel(self.centralwidget)
        self.lblLoket.setGeometry(QtCore.QRect(-5, bottom, screenwidth, 130))
        self.lblLoket.setStyleSheet("background-color: #cccccc; color: #ff0000;font:Bold")
        self.lblLoket.setFixedHeight(150)
        self.lblLoket.setAlignment(QtCore.Qt.AlignCenter)
        self.lblLoket.setFont(QFont('Xtreme Chrome',130))
        self.lblLoket.setObjectName("lblLoket")
     
    ##################
     
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 259, 21))
        self.menubar.setObjectName("menubar")
     
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "   "))
        self.lblCounter.setText(_translate("MainWindow", "A000"))
        self.lblLoket.setText(_translate("MainWindow", "Loket X"))
        self.lbl.setText(_translate("MainWindow", "NOMOR ANTRIAN"))
     
        # User Code
        self.timeout = 0
        self.check_serial_event()

    def check_serial_event(self):
        serial_thread = threading.Timer(1, self.check_serial_event)
        if ser.is_open == True:
            serial_thread.start()
            distance=""
            char1='T' #Loket 1
            char2='B'
     
            if ser.in_waiting:
                while True:
                    try:
                        msg = ser.readline().decode('ascii')
                        distance=distance+msg  
                        if distance.index(char2):
                            break
                     
                    except:
                        pass
                 
                print (distance)  
                ser.flush()
                #ser.close()
                l1=distance.index(char1)
                #l2=distance.index(char2)
                l2=distance.find(char2, l1+5)

                H1=distance[l1:l2-2] #l1+7
                H2=distance[l2:l2+4]

                print ('H1='+H1)
                print ('H2='+H2)
             
                self.lblLoket.setText(H1)
                self.lblCounter.setText(H2)
                distance=""
             
         
        #ser.close()
if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())



Implementasinya:
OK ...In Sya Allah Mudah....

Kamis, 09 Februari 2017

raspberry PI Fingerprint


https://www.sparkfun.com/products/11792
https://github.com/the-AjK/GT-511C3
https://www.raspberrypi.org/forums/viewtopic.php?f=36&t=84572
http://devnotes.fabioluiz.de/spring-boot-libfprint
http://sergeplay.blogspot.co.id/2016/01/cheap-usb-fingerprint-reader-from.html

sudo apt-get install libfprint


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <libfprint/fprint.h>

struct fp_dscv_dev *discover_device(struct fp_dscv_dev **discovered_devs)
{
   struct fp_dscv_dev *ddev = discovered_devs[0];
   struct fp_driver *drv;
   if (!ddev)
      return NULL;
 
   drv = fp_dscv_dev_get_driver(ddev);
   printf("Found device claimed by %s driver\n", fp_driver_get_full_name(drv));
   return ddev;
}

struct fp_print_data *enroll(struct fp_dev *dev) {
   struct fp_print_data *enrolled_print = NULL;
   int r;

   printf("You will need to successfully scan your finger %d times to "
      "complete the process.\n", fp_dev_get_nr_enroll_stages(dev));

   do {
      struct fp_img *img = NULL;
 
      sleep(1);
      printf("\nScan your finger now.\n");

      r = fp_enroll_finger_img(dev, &enrolled_print, &img);
      if (img) {
         fp_img_save_to_file(img, "enrolled.pgm");
         printf("Wrote scanned image to enrolled.pgm\n");
         fp_img_free(img);
      }
      if (r < 0) {
         printf("Enroll failed with error %d\n", r);
         return NULL;
      }

      switch (r) {
      case FP_ENROLL_COMPLETE:
         printf("Enroll complete!\n");
         break;
      case FP_ENROLL_FAIL:
         printf("Enroll failed, something wen't wrong :(\n");
         return NULL;
      case FP_ENROLL_PASS:
         printf("Enroll stage passed. Yay!\n");
         break;
      case FP_ENROLL_RETRY:
         printf("Didn't quite catch that. Please try again.\n");
         break;
      case FP_ENROLL_RETRY_TOO_SHORT:
         printf("Your swipe was too short, please try again.\n");
         break;
      case FP_ENROLL_RETRY_CENTER_FINGER:
         printf("Didn't catch that, please center your finger on the "
            "sensor and try again.\n");
         break;
      case FP_ENROLL_RETRY_REMOVE_FINGER:
         printf("Scan failed, please remove your finger and then try "
            "again.\n");
         break;
      }
   } while (r != FP_ENROLL_COMPLETE);

   if (!enrolled_print) {
      fprintf(stderr, "Enroll complete but no print?\n");
      return NULL;
   }

   printf("Enrollment completed!\n\n");
   return enrolled_print;
}

int main(void)
{
   int r = 1;
   struct fp_dscv_dev *ddev;
   struct fp_dscv_dev **discovered_devs;
   struct fp_dev *dev;
   struct fp_print_data *data;

   printf("This program will enroll your right index finger, "
      "unconditionally overwriting any right-index print that was enrolled "
      "previously. If you want to continue, press enter, otherwise hit "
      "Ctrl+C\n");
   getchar();

   r = fp_init();
   if (r < 0) {
      fprintf(stderr, "Failed to initialize libfprint\n");
      exit(1);
   }
   fp_set_debug(3);

   discovered_devs = fp_discover_devs();
   if (!discovered_devs) {
      fprintf(stderr, "Could not discover devices\n");
      goto out;
   }

   ddev = discover_device(discovered_devs);
   if (!ddev) {
      fprintf(stderr, "No devices detected.\n");
      goto out;
   }

   dev = fp_dev_open(ddev);
   fp_dscv_devs_free(discovered_devs);
   if (!dev) {
      fprintf(stderr, "Could not open device.\n");
      goto out;
   }

   printf("Opened device. It's now time to enroll your finger.\n\n");
   data = enroll(dev);
   if (!data)
      goto out_close;

   r = fp_print_data_save(data, RIGHT_INDEX);
   if (r < 0)
      fprintf(stderr, "Data save failed, code %d\n", r);

   fp_print_data_free(data);
out_close:
   fp_dev_close(dev);
out:
   fp_exit();
   return r;
}

===========

Cheap USB fingerprint reader (from Laptop) works with Raspberry Pi

sudo apt-get install libpam-fprintd

And then testing:

> sudo fprintd-enroll 
Using device /net/reactivated/Fprint/Device/0
Enrolling right-index-finger finger.
Enroll result: enroll-stage-passed
Enroll result: enroll-stage-passed
Enroll result: enroll-completed

> sudo fprintd-verify
Using device /net/reactivated/Fprint/Device/0
Listing enrolled fingers:
 - #0: right-index-finger
Verify result: verify-match (done)


Minggu, 15 Januari 2017

Raspberry PI to Arduino Uno Serial GPIO

python code
import serial

ser = serial.Serial('/dev/ttyACM0',9600)
s = [0,1]
while True:
read_serial=ser.readline()
s[0] = str(int (ser.readline(),16))
print s[0]
print read_serial

arduino code:
char dataString[50] = {0};
int a =0; 

void setup() {
Serial.begin(9600);              //Starting serial communication
}
  
void loop() {
  a++;                          // a value increase every loop
  sprintf(dataString,"%02X",a); // convert a value to hexa 
  Serial.println(dataString);   // send the data
  delay(1000);                  // give the loop some break
}





One way to connect the Raspberry Pi and Arduino is by connecting the GPIO on the Raspberry Pi and the Serial Pins on the Arduino.
Because there is a voltage difference between the two device on these interface, a voltage divider or logic level converter would be required.
Check my article about connecting the two using I2C if you haven’t already seen it. Before we start, we need to set up the Raspberry Pi so it’s ready for serial communication.

Raspberry Pi Serial GPIO Configuration

0. if you have not seen my article on how to remote access your Raspberry Pi, take a look here:
1. In order to use the Raspberry Pi’s serial port, we need to disable getty (the program that displays login screen) by find this line in file /etc/inittab
T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
And comment it out by adding # in front of it
#T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
2. To prevents the Raspberry Pi from sending out data to the serial ports when it boots, go to file /boot/cmdline.txt and find the line and remove it
console=ttyAMA0,115200 kgdboc=ttyAMA0,115200
3. reboot the Raspberry Pi using this command: sudo reboot
4. Now, Install minicom
sudo apt-get install minicom
And that’s the end of the software configuration.

Connect Serial Pins and GPIO with a Voltage Level Converter

Load this program on your Arduino first:
[sourcecode language=”cpp”]
byte number = 0;
void setup(){
Serial.begin(9600);
}
void loop(){
if (Serial.available()) {
number = Serial.read();
Serial.print(“character recieved: “);
Serial.println(number, DEC);
}
}
[/sourcecode]
Then connect your Arduino, Raspberry Pi and Logic Level Converter like this:

arduino-raspberry-pi-serial-gpio-connect-schematics
This is how the wires are connected.
arduino-raspberry-pi-serial-gpio-connect-wiring
And this is the GPIO pins on the Raspberry Pi. Make sure you connect the correct pin otherwise you might damage your Pi.
GPIOs

A Simple Example with Minicom

Now to connect to the Arduino via serial port using this command in putty or terminal
minicom -b 9600 -o -D /dev/ttyAMA0
When you type a character into the console, it will received by the Arduino, and it will send the corresponding ASCII code back. Check here for ASCII Table. And there it is, the Raspberry Pi is talking to the Arduino over GPIO serial port.
arduino-raspberry-pi-serial-gpio-connect-minicom
To exit, press CTRL + A release then press Q

Example with Python Program

Using Python programming language, you can make Raspberry Pi do many fascinating stuff with the Arduino when they are connected. Install Py-Serial first:
sudo apt-get install python-serial
Here’s a simple application that sends the string ‘testing’ over the GPIO serial interface
[sourcecode language=”python”]
import serial
ser = serial.Serial(‘/dev/ttyAMA0’, 9600, timeout=1)
ser.open()
ser.write(“testing”)
try:
while 1:
response = ser.readline()
print response
except KeyboardInterrupt:
ser.close()
[/sourcecode]
Raspberry Pi and Arduino Connected Over Serial GPIO python-serial-program-output
To exit, press CTRL + C

Connect Raspberry Pi and Arduino with a Voltage Divider

Apart from replacing the Login Level Converter with a voltage divider, the way it works is the same as above. Anyway, I will show you a different example to demonstrate this. A voltage divider is basically just two resistors.
There is something you should be aware of before we continue. The RX pin on the Arduino is held at 5 Volts even when it is not initialized. The reason could be that the Arduino is flashed from the Arduino IDE through these pins when you program it, and there are weak external pull-ups to keep the lines to 5 Volts at other times. So this method might be risky. I recommend using a proper level converter, if you insist on doing it this way, try adding a resistor in series to the RX pin, and never connect the Raspberry Pi to Arduino RX pin before you flash the program to Arduino, otherwise you may end up with a damaged Pi!
arduino-raspberry-pi-serial-gpio-connect-schematics
The Arduino serial pin is held at 5 volts and Raspberry Pi’s at 3.3 volts. Therefore a voltage divider would be required, it’s basically just two resistors.
arduino-raspberry-pi-serial-connect-schematics
Here is the program you need to write to the Arduino board.
[sourcecode language=”cpp”]
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
int incoming = Serial.read();
Serial.print(“character recieved: “)
Serial.print(incoming, DEC);
}
}
[/sourcecode]
Now you can connect directly from your computer to the Raspberry Pi on the tty-device of the Arduino, just like we described above. (type below into your putty)
minicom -b 9600 -o -D /dev/ttyAMA0
And as you type in characters in the console, you should see something like this:
arduino-raspberry-pi-serial-gpio-connect-minicom
And that’s the end of this Raspberry Pi and Arduino article. There are other ways of connecting, if you don’t already know, you can also use a Micro USB cable. Check out this post: https://oscarliang.com/connect-raspberry-pi-and-arduino-usb-cable/
Reff:
http://www.instructables.com/id/Raspberry-Pi-Arduino-Serial-Communication/?ALLSTEPS
http://www.seeed.cc/project_detail.html?id=168

FInishing Code:


import serial

import MySQLdb
from time import gmtime, strftime
from random import randint


db = MySQLdb.connect("localhost","root","123456","monitoring" )
cursor = db.cursor()

def mtrim(s):
    if s.endswith(" "): s = s[:-1]
    if s.startswith(" "): s = s[1:]
    return s



read_serial0=""
ser = serial.Serial('/dev/ttyACM0',9600)
s = [0,1]
while True:
 read_serial=ser.readline()
 print read_serial
 read_serial=mtrim(read_serial)

 if len(read_serial) >6:
     if read_serial!=read_serial0:
         c=read_serial.split("#")
         read_serial0=read_serial
         I=c[0]
         V=c[1]
         W=c[2]
         P=c[3]
         Q=c[4]
         R=c[5]
         S=c[6]
         
         print "I=",I
         print "V=",V
         print "P=",W
         print "1=",P
         print "2=",Q
         print "3=",R
         print "4=",S

         tgl=strftime("%Y-%m-%d", gmtime())
         jam=strftime("%H:%M:%S", gmtime())

         sql = 'INSERT INTO `tb_history` ( `tanggal`, `jam`, `arus`, `tegangan`, `daya`,`L1`,`L2`,`L3`,`L4`) VALUES ("%s", "%s", "%s","%s","%s", "%s", "%s", "%s", "%s")' % (tgl, jam, I,V,W,P,Q,R,S)
         try:
           cursor.execute(sql)
           db.commit()
         except:
           db.rollback()
          
     
         print"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"





#$sudo -i
#cd /home/pi/Desktop/py
#python Help.py

#ls /dev/tty*