Arquivo da categoria: Programação

Auto-run LXTerminal from LXDE desktop at startup

The script may be running to completion and the terminal closes before you see it. Test to see if it works using a script that waits for input, so the terminal will stay open until you close it.

Create a test script. I just named it “test.sh”, make it executable.

Code:

#!/bin/bash

pause(){
 read -n1 -rsp $'Press any key to close the terminal...\n'
}

echo Script is running

pause

Then edit the autostart file

Code:

nano ~/.config/lxsession/LXDE-pi/autostart

Add this line at the bottom

Code:

lxterminal -e /path/to/test.sh

Then log out and back in, or reboot. When the desktop starts you should see the terminal open in the middle of the screen, waiting for you to press a key. That will confirm everything’s working, then edit the autostart file and replace “/path/to/test.sh” with the script you want to use.

inspirational quotes:  https://www.raspberrypi.org/forums/viewtopic.php?t=65607

Linux commands

LS

The ls command lists the content of the current directory (or one that is specified). It can be used with the -l flag to display additional information (permissions, owner, group, size, date and timestamp of last edit) about each file and directory in a list format. The -a flag allows you to view files beginning with . (i.e. dotfiles).

CD

Using cd changes the current directory to the one specified. You can use relative (i.e. cd directoryA) or absolute (i.e. cd /home/pi/directoryA) paths.

PWD

The pwd command displays the name of the present working directory: on a Raspberry Pi, entering pwd will output something like /home/pi.

MKDIR

You can use mkdir to create a new directory, e.g. mkdir newDir would create the directory newDir in the present working directory.

RMDIR

To remove empty directories, use rmdir. So, for example, rmdir oldDir will remove the directory oldDir only if it is empty.

RM

The command rmremoves the specified file (or recursively from a directory when used with -r). Be careful with this command: files deleted in this way are mostly gone for good!

CP

Using cp makes a copy of a file and places it at the specified location (this is similar to copying and pasting). For example, cp ~/fileA /home/otherUser/would copy the file fileA from your home directory to that of the user otherUser (assuming you have permission to copy it there). This command can either take FILE FILE (cp fileA fileB), FILE DIR(cp fileA /directoryB/) or -r DIR DIR (which recursively copies the contents of directories) as arguments.

MV

The mv command moves a file and places it at the specified location (so where cp performs a ‘copy-paste’, mv performs a ‘cut-paste’). The usage is similar to cp. So mv ~/fileA /home/otherUser/ would move the file fileA from your home directory to that of the user otherUser. This command can either take FILE FILE (mv fileA fileB), FILE DIR (mv fileA /directoryB/) or DIR DIR (mv /directoryB /directoryC) as arguments. This command is also useful as a method to rename files and directories after they’ve been created.

TOUCH

The command touch sets the last modified time-stamp of the specified file(s) or creates it if it does not already exist.

CAT

You can use cat to list the contents of file(s), e.g. cat thisFile will display the contents of thisFile. Can be used to list the contents of multiple files, i.e. cat *.txt will list the contents of all .txt files in the current directory.

HEAD

The head command displays the beginning of a file. Can be used with -n to specify the number of lines to show (by default ten), or with -c to specify the number of bytes.

TAIL

The opposite of headtail displays the end of a file. The starting point in the file can be specified either through -b for 512 byte blocks, -c for bytes, or -n for number of lines.

CHMOD

You would normally use chmod to change the permissions for a file. The chmodcommand can use symbols u (user that owns the file), g (the files group) , and o (other users) and the permissions r (read), w (write), and x (execute). Using chmod u+x *filename* will add execute permission for the owner of the file.

CHOWN

The chown command changes the user and/or group that owns a file. It normally needs to be run as root using sudo e.g. sudo chown pi:root *filename* will change the owner to pi and the group to root.

SSH

ssh denotes the secure shell. Connect to another computer using an encrypted network connection. For more details see SSH (secure shell)

SCP

The scp command copies a file from one computer to another using ssh. For more details see SCP (secure copy)

SUDO

The sudo command enables you to run a command as a superuser, or another user. Use sudo -s for a superuser shell. For more details see Root user / sudo

DD

The dd command copies a file converting the file as specified. It is often used to copy an entire disk to a single file or back again. So, for example, dd if=/dev/sdd of=backup.img will create a backup image from an SD card or USB disk drive at /dev/sdd. Make sure to use the correct drive when copying an image to the SD card as it can overwrite the entire disk.

DF

Use df to display the disk space available and used on the mounted filesystems. Use df -h to see the output in a human-readable format using M for MBs rather than showing number of bytes.

UNZIP

The unzip command extracts the files from a compressed zip file.

TAR

Use tar to store or extract files from a tape archive file. It can also reduce the space required by compressing the file similar to a zip file.

To create a compressed file, use tar -cvzf *filename.tar.gz* *directory/* To extract the contents of a file, use tar -xvzf *filename.tar.gz*

PIPES

A pipe allows the output from one command to be used as the input for another command. The pipe symbol is a vertical line |. For example, to only show the first ten entries of the ls command it can be piped through the head command ls | head

TREE

Use the tree command to show a directory and all subdirectories and files indented as a tree structure.

&

Run a command in the background with &, freeing up the shell for future commands.

WGET

Download a file from the web directly to the computer with wget. So wget https://www.raspberrypi.org/documentation/linux/usage/commands.mdwill download this file to your computer as commands.md

CURL

Use curl to download or upload a file to/from a server. By default, it will output the file contents of the file to the screen.

MAN

Show the manual page for a file with man. To find out more, run man man to view the manual page of the man command.

Search

GREP

Use grep to search inside files for certain search patterns. For example, grep "search" *.txt will look in all the files in the current directory ending with .txt for the string search.

The grep command supports regular expressions which allows special letter combinations to be included in the search.

AWK

awk is a programming language useful for searching and manipulating text files.

FIND

The find command searches a directory and subdirectories for files matching certain patterns.

WHEREIS

Use whereis to find the location of a command. It looks through standard program locations until it finds the requested command.

Networking

PING

The ping utility is usually used to check if communication can be made with another host. It can be used with default settings by just specifying a hostname (e.g. ping raspberrypi.org) or an IP address (e.g. ping 8.8.8.8). It can specify the number of packets to send with the -c flag.

NMAP

nmap is a network exploration and scanning tool. It can return port and OS information about a host or a range of hosts. Running just nmap will display the options available as well as example usage.

HOSTNAME

The hostname command displays the current hostname of the system. A privileged (super) user can set the hostname to a new one by supplying it as an argument (e.g. hostname new-host).

IFCONFIG

Use ifconfig to display the network configuration details for the interfaces on the current system when run without any arguments (i.e. ifconfig). By supplying the command with the name of an interface (e.g. eth0 or lo) you can then alter the configuration: check the manual page for more details.

PowerPoint report with data from MYSQL

Hello!
Some times we need make a report with information that can’t be changed, and other situations better if the report informations can be changed and improved!
In this post I’m gonna show you, an library on javascript that give us, the flessible tools to do it.

So, to make it more easy, please watch the video series below, and don’t forget, please, help me to make it better give me you opinion and coments

Thank you so motch for your vist!!

Introduction: (A little introduction at how this javascript library work)
Imagem de Amostra do You Tube

Step 1: (Creating the pptx presentation without mysql connection)
Imagem de Amostra do You Tube

Step 2: (Creating the system to generate the data and reports)
Imagem de Amostra do You Tube

Step 3: (Populating database and creating the upload button)
Imagem de Amostra do You Tube

Lux monitoring – LDR Arduino and Nodejs


Hello guys! How are you? I hope everything’s ok!

So, in this post I’ll try explain, how you can do the lux monitoring system, using:

– Arduino Uno,

Photo-resistor LDR,

Two led (green and red) to visual status indicator

Nodejs and chart.js module,  to show the lux range in real time.

Step 0 > Install Nodejs and NPM

To make this task you need install before the nodejs and npm

Step 1 > Electrical connections

See the electrical connections bellow:

protoboard

Step 2 > Installation of dependencies:

Create the folder the folder Node_LDR;

Into this folder create the packagejson.js:

Into the packagejson.js file, write the code below:

{
    "name": "LDR_Aduino_Nodejs",
    "version": "0.0.1",
    "dependencies": {
      "chart.js": "^2.2.1",
      "express": "^4.14.0",
      "serialport": "^4.0.1",
      "socket.io": "^1.4.8"
    }
 }

Save and close!

After, open your prompt command and run npm install:

npminstall

When the installation is finished look into the folder   Node_LDR:

– Node_LDR

— node_modules

— package.json

If your folder it’s the same that format, everything’s ok!!

Step 3 > Installation of Arduino IDE:

Click here and install the IDE

IDE_Arduino

Step 4 > C++ code:

Open your arduino IDE and write the follow code:

int portaledred = 10;
int portaledgreen = 11;
int pinoport = 5;
int valorport = 0;
float luminosidade = 0;

void setup() {
 Serial.begin(9600);
 pinMode(portaledred, OUTPUT);
 pinMode(portaledgreen, OUTPUT);
}

void loop() {
 valorport = analogRead(pinoport);

 luminosidade = map(valorport, 0, 1023, 0, 255);
 Serial.print("Valor do LDR : ");
 Serial.println(valorport);
 Serial.print(" = Luminosidade : ");
 Serial.println(luminosidade);
 

 if (valorport > 900)
 {
 digitalWrite(portaledred, HIGH);
 digitalWrite(portaledgreen, LOW);
 }
 else
 {
 digitalWrite(portaledred, LOW);
 digitalWrite(portaledgreen, HIGH);
 }
delay(3000);
}

Make Upload the code on Arduino board:

uploadArd

After the upload is done make a test

Step 5 > Communication between Arduino, Nodejs and Web page:

Open the text editor of your preference and create the app.js with code below:

var app = require('express')();
var express = require('express');

app.use(express.static(__dirname + '/public'));

var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get("/", function(req, res){
 res.sendFile("/cygwin64/home/pablo.binotto/node/arduino/index.html");//here is necessary the all url of folder into the c:/
});

var mySocket;

var serialport = require('serialport');
var SerialPort = serialport.SerialPort;

var mySerial = new SerialPort("COM5", {
 baudrate: 9600,
 parser: serialport.parsers.readline("\n")
});

mySerial.on('open', function(){
 console.log("Porta aberta.");
});

mySerial.on("data", function(data){
 //console.log(dados);
 io.emit("dadoArduino", {
 valor: data
 });
});

io.on("connection", function(socket){
 console.log("Usuario conectado")
});

http.listen(3000, function(){
 console.log("Server running on 3000 port");
});

Save this file on Node_LDR folder and on the same folder, create the file index.html follow the code below:

<!DOCTYPE html>
<html lang="">
 <head>
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatiblr" content="IE=edge">
 <meta name= "viewport" content="width=device-width, initial-scale=1">
 <title>Node_Arduino_IO_SerialPort</title>
 <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22%2Fsocket.io%2Fsocket.io.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
 </head>
 <body>
 <canvas id="myChart" width="400" height="400"></canvas>
 <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%3D%22text%2Fjavascript%22%3E%0A%20var%20ctx%20%3D%20document.getElementById(%22myChart%22)%3B%0A%20%0A%20var%20myLineChart%20%3D%20new%20Chart(ctx%2C%20%7B%0A%20type%3A%20'line'%2C%0A%20data%3A%20data%2C%0A%20options%3A%20options%0A%20%7D)%3B%0A%20%0A%20%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
 <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%3D%22text%2Fjavascript%22%3E%0A%20var%20socket%20%3D%20io()%3B%0A%20socket.on(%22dadoArduino%22%2C%20function(dado)%7B%0A%20console.log(dado)%3B%0A%20%7D)%3B%0A%20%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
 </body>
</html>

On your prompt command write: node app.js and click enter…

Open a new web page and go to localhost:3000…

In this video below, you can see the communication happening

Step 6 > Show the result on line graph into the web page:

See you again!

Raspberry Pi and NFC ACR122u – English version

Hello everybody!

In this post I’ll show you, how to do a presence control using the ACR122u reader and the Raspberry Pi B+ 2, programing with javascript, Nodejs soquet.io and MYSQL.

sistema

Imagem de Amostra do You Tube

LXtermial

 

 

 

 

 

 

After Terminal opening, the first step is check if all thing are updated on our Raspberry

~$ sudo apt-get update

~$ sudo apt-get upgrade

Installing Node.js via package manager:

curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs
sudo apt-get install -y build-essential

For more information on how to install Node.js visit the official site nodejs.org.

to check that everything was installed correctly enter the code below:

~$ node -v

v0 . 12 . 9 

~$ npm -v

2 . 14 . 9

You’ll have something like this.

First you need install libudev-dev:

sudo apt-get install libudev-dev

Then you need to install libusb, this should do the trick:

sudo apt-get install libusb-dev

apt-get install libpcsclite1 libpcsclite-dev
npm install pcsclite
apt-get install pcscd

Now we need to install NFC Tools:

wget https://bintray.com/artifact/download/nfc-tools/sources/libnfc-1.7.1.tar.bz2

tar xjf libnfc-1.7.1.tar.bz2

cd libnfc-1.7.1

./configure –prefix=/usr –sysconfdir=/etc

or

./configure –with-drivers=all –prefix=/usr –sysconfdir=/etc

make

sudo make install

sudo apt-get install libtool

sudo apt-get install libsystemd-dev

sudo apt-get install libpcsclite1

sudo apt-get install flex

git clone git://anonscm.debian.org/pcsclite/PCSC.git
cd PCSC
./bootstrap
./configure
make

Now will install the dependencias of ACR122u reader:

— Install the ACS Driver —
make a dowload on oficial web site of ACR122u here.

unzip the file

~$ cd acsccid-x.y.z // to access the folder

~$  ./configure

~$ make

~$ make install

The installation can spend some minutes

Now you need to configure the file libccid_info.plist on cd /etc directory

~$ cd

~$ cd /etc

~$ sudo nano libccid_info.plist

Change the following line in the file:

<key>ifDriverOptions</key>
<string>0x0000</string>

To

<key>ifDriverOptions</key>
<string>0x0001</string>

Ctrl + x and press y to save!

~$ cd // to return on root folder (/home/pi..)

To verify that everything worked out so far, write:

~$ sudo nfc-list // comment: see result below

nfc-list uses libnfc 1.7.1
NFC device: ACS / ACR122U PICC Interface opened

~$ sudo nfc-scan-device -v // comment: see result below

nfc-scan-device uses libnfc 1.7.1
1 NFC device(s) found:
– ACS / ACR122U PICC Interface:
acr122_usb:001:009
chip: PN532 v1.6
initator mode modulations: ISO/IEC 14443A (106 kbps), FeliCa (424 kbps, 212 kbps), ISO/IEC 14443-4B (106 kbps), Innovision Jewel (106 kbps), D.E.P. (424 kbps, 212 kbps, 106 kbps)
target mode modulations: ISO/IEC 14443A (106 kbps), FeliCa (424 kbps, 212 kbps), D.E.P. (424 kbps, 212 kbps, 106 kbps)

I believe that everything must have worked here! In case of problems leave a comment we will solve the problem.

Acabamos a primeira fase do nosso projeto onde temos:

  • The Raspberry with the OS installed and running;
  • The ACR122u reader configured and running.

Now create a folder by typing:

~$ cd // to ensure that the root folder

~$ mkdir rfid // to create the folder

~$ cd rfid // to enter the folder

Let’s start by installing the dependencies to our project …

~$ npm install express

~$ npm install pcsclite

~$ npm install socket.io

~$ npm install mysql

  • Ready believe we installed all dependencies, but if they encounter problems tell me to review the post.

Continuing with our project created in mysql database databesname the tables using the settings below:


CREATE TABLE IF NOT EXISTS `ck` (
`ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`evento` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`qty` int(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

CREATE TABLE IF NOT EXISTS `event` (
 `nome` varchar(100) DEFAULT NULL,
 `foto` varchar(100) DEFAULT NULL,
 `rfid` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 `dept` varchar(20) NOT NULL,
 `turno` varchar(10) NOT NULL,
 `divi` varchar(1) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
 `Qty` int(1) NOT NULL DEFAULT '1',
 `fone` varchar(30) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
 `email` varchar(50) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `coutbyid` AS select `ck`.`evento` AS `evento`,count(`ck`.`qty`) AS `count(``qty``)` from `ck` group by `ck`.`evento`;
 CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `grupo` AS select `event`.`rfid` AS `rfid`,`event`.`foto` AS `foto`,`event`.`nome` AS `nome`,`event`.`turno` AS `turno`,`event`.`divi` AS `divi`,`event`.`dept` AS `dept`,`coutbyid`.`count(``qty``)` AS `count(``qty``)` from (`event` join `coutbyid` on((`event`.`rfid` = `coutbyid`.`evento`))) order by `event`.`nome`; 

Clone the files on GitHub:

sudo apt-get clone https://github.com/PabloBInotto/A-PRESENCE-CONTROL.git

cd A-PRESENCE-CONTROL/

sudo npm install

Let’s test it all worked out:

1º open the terminal in raspberry;

2º  Start new.js middleware that will be responsible for reading and writing of RFID tags in the code mysql:

~$ cd rfid

~$ node new

3º In another terminal to start the HTTP server of the node:

~$ cd rfid

~$ node sv-http

4º Open your browser and access the html we created last, the page that will display that is present or absent. In vavegador Type in: http://localhost:8000

screew

If all right gave up page will be displayed!!


 

Place raspberry in Kiosk mode and automatically start the sv-http server and has open the page to display our presence control:

First we have to install the chromium

~$ sudo apt-get install chromium x11-xserver-utils unclutter

Now let’s edit the file auto start

~$ sudo nano /etc/xdg/lxsession/LXDE-pi/autostart

The file should look like the following lines:

@xscreensaver -no-splash

@xset s off
@xset -dpms
@xset s noblank

@lxterminal –command “node /home/pi/rfid/sv-http.js”

@sed -i ‘s/”exited_cleanly”: false/”exited_cleanly”: true/’ ~/.config/chromium/Default/Preferences
@chromium –noerrdialogs –kiosk http://www.page-to.display

Ctrl + C  – y  – enter


Now let’s make the raspberry connect without using keyboard and mouse

~$ sudo nano /etc/rc.local

su -l pi -c startx // deu certo

Add line before exit 0

Ctrl + C  – y  – enter

Let’s stop here.

  • The post goes on to the next update we will make a page for more dynamic record, without having to enter the rfid each new account. The way that this is not good.

I hope you enjoyed and that everything has worked out so far. Any problems leave a comment that soon I will answer!

Should they improve what was done let me know !!

Big hug to all 🙂

Controle de presença com Raspberry – Node js – Mysql – Socket.io – ACR122u

Ola!

Nesse post vou mostrar como fazer o controle de presença usando o leitor ACR122u, um Raspberry Pi B+ 2, programando usando javascript – NODE JS, Socket.io e MYSQL.

sistema

Imagem de Amostra do You Tube

Para realizar as atividades propostas neste post você vai precisar dos itens abaixo:

acr122u Leito RFID ACR122u

Não é difícil encontrar para compra e é muito bom;

Será usado para receber informações das tags RFID

 

TagRFID

Tags RFID

O legal é comprar pelo menos umas 3 para fazer os testes

É bem baratinho!!

 

raspberry pi Uma placa Raspberry pi

Não vou explicar como fazer a configuração do sistema operacional (OS) mas é muito simples e tem vários posts sobre esse assunto na net; Eu usei o OS Wkenzy versão 2016.

sdcard4gb   Um SD card de no minimo 4GB para instalar o Sistema Operacional. A maioria dos tutoriais que eu recomendam usar um de 8GB, mas o que eu tinha aqui era um de 4GB, usei esse e deu tudo certo.
HDMI Um cabo HDMI

Será usado para ligar o Raspberry ao monitor

 

monitor  Um monitor para exibir  as respostas no nosso sistema.

O monitor deve ter entrada Digital HDMI ou você pode usar um aptador (nunca usei com aptador, mas acho que deve dar certo)

 

kit_teclado_e_mouse Vai precisar também de um mouse e um teclado para fazer a programação no Raspberry. Existe a opção de conectar remotamente via SSH usando seu desktop ou notebook, mas se você não tiver experiencia de como realizar isso, sugiro que utilize o teclado e o mouse (com conexões USB, acredito que seja difícil alguém que ainda use que use dos modelos antigos que não seja USB, mas… vai saber)

Acho que não faltou nada. Qualquer coisa coloco mais adiante….