Monday, 25 August 2014 11:51

USB RS485 8 Relay boards by Raspberry Pi

Written by
 
Now I'll show you a very easy way how to control 32 relays with the help of Raspberry PI with web Interface
 
 
 
Needed 
1 RaspberryPI
KMTronic RS485 8 Relay Boards
KMTronic USB<>RS485 adapter
1 USB cable 
12 volt power
recommend install Raspbian
 

 

 

 

 

 

 

Commands for control shell script of the relays:

 
 
echo -e "\xFF\x01\x01" > /dev/ttyUSB0  -> For ON Relay 1
echo -e "\xFF\x01\x00" > /dev/ttyUSB0  -> For OFF Relay 1
echo -e "\xFF\x02\x01" > /dev/ttyUSB0  -> For ON Relay 2
echo -e "\xFF\x02\x00" > /dev/ttyUSB0  -> For OFF Relay 2
echo -e "\xFF\x03\x01" > /dev/ttyUSB0  -> For ON Relay 3
echo -e "\xFF\x03\x00" > /dev/ttyUSB0  -> For OFF Relay 3    
 
and etc..

 

 

 

 

Web interface

 

 

For full shell scrip download this  Download

 

Download web interface -Download

 

 

 

Thursday, 21 August 2014 13:30

How to connect RaspberryPI camera

Written by
Needed 
1 RaspberryPI
1 Raspberry PI Camera
recommend install Raspbian
 
 
 
ENABLING THE CAMERA
 
Open the raspi-config tool from the Terminal:
 
Interminal :
sudo raspi-config
 
Select Enable camera and hit Enter, then go to Finish and you'll be prompted to reboot.
 
 
 
 
BASIC USAGE OF RASPISTILL
 
With the camera module connected and enabled, enter the following command in the Terminal to take a picture:
 
 
raspistill -o cam.jpg
 
 
 
In this example the camera has been positioned upside-down. If the camera is placed in this position, the image must be flipped to appear the right way up.
 
VERTICAL FLIP & HORIZONTAL FLIP
 
With the camera placed upside-down, the image must be rotated 180° to be displayed correctly. The way to correct for this is to apply both a vertical and a horizontal flip by passing in the -vf and -hf flags:
 
 
raspistill -vf -hf -o cam2.jpg
 
Vertical and horizontal flipped photo
 
Now the photo has been captured correctly.
 
RESOLUTION
 
The camera module takes pictures at a resolution of 2592 x 1944 which is 5,038,848 pixels or 5 megapixels.
 
FILE SIZE
 
A photo taken with the camera module will be around 2.4MB. This is about 425 photos per GB.
 
Taking 1 photo per minute would take up 1GB in about 7 hours. This is a rate of about 144MB per hour or 3.3GB per day.
 
BASH SCRIPT
 
You can create a Bash script which takes a picture with the camera. To create a script, open up your editor of choice and write the following example code:
 
#!/bin/bash
 
DATE=$(date +"%Y-%m-%d_%H%M")
 
raspistill -vf -hf -o /home/pi/camera/$DATE.jpg
 
This script will take a picture and name the file with a timestamp.
 
You'll also need to make sure the path exists by creating the camera folder:
 
mkdir camera
Say we saved it as camera.sh, we would first make the file executable:
 
chmod +x camera.sh
Then run with:
 
./camera.sh
 
MORE OPTIONS
 
For a full list of possible options, run raspistill with no arguments. To scroll, redirect stderr to stdout and pipe the output to less:
 
raspistill 2>&1 | less
 
Use the arrow keys to scroll and type q to exit.

 

Thursday, 21 August 2014 08:59

Raspberry PI USB DS18B20

Written by
 
 
Needed 
1 RaspberryPI
1 USB<>DS18B20
recommend install Raspbian
 
 
 
 
 
 
In terminal 
 
 
 
 
 
 
In web browser
 
 
 
 
 
 
 
 
C code
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
 
int main(int argc, char* argv[]) {
 
    struct termios serial;
    char inBuff[100];
    char logBuff[100];
    char *buffer;
    char *logPtr;
    int wcount = 0;
    int j;
    int fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NDELAY);
    FILE *log;
    //log = fopen("log.txt","w");
 
    if (fd == -1) {
        perror(argv[2]);
        return -1;
    }
 
    if (tcgetattr(fd, &serial) < 0) {
        perror("Getting configuration");
        return -1;
    }
 
    //////////////////// Set up Serial Configuration ////////////
    serial.c_iflag = 0;
    serial.c_oflag = 0;
    serial.c_lflag = 0;
    serial.c_cflag = 0;
 
    serial.c_cc[VMIN] = 0;
    serial.c_cc[VTIME] = 10;
 
    serial.c_cflag = B9600 | CS8 | CREAD;
    fcntl(fd,F_SETFL,0);
    tcsetattr(fd, TCSANOW, &serial); // Apply configuration
    //////////////////////////////////////////////////////////////
 
    
   int rcount;  
   buffer = &inBuff[0];
   logPtr = &logBuff[0];
 
   while(1)
  {
   buffer = &inBuff[0];
   memset(buffer,0,sizeof(inBuff));
   logPtr = &logBuff[0];
   memset(logPtr,0,sizeof(logBuff));
 
while( (rcount = read(fd,buffer,1)) > 0)
{
       
    if (rcount < 0) {
        perror("Read");
        return -1;
    }
 
      buffer++;
}
 
             for(j=0;j<sizeof(inBuff);j++)
{
if(inBuff[j] == '+') {
//printf("\r\n");
while(inBuff[j++] != '\r'){
//printf("%c",inBuff[j-1]);
*logPtr = inBuff[j-1];logPtr++;
}
*logPtr = '\r';logPtr++;
                        *logPtr = '\n';logPtr++;
}
}
 
printf("%s",logBuff);
             printf("\r\n"); 
log = fopen("log.txt","w");
fwrite(logBuff,1,sizeof(logBuff),log);
fclose(log);
}
   close(fd);
}
 
 
 
 
 
 
create log.txt file and set chmod -R 777 /path/to/file.log to folder
 
 
 
 
PHP Script
 
<?php
$handle = @fopen("log.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        echo $buffer;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
?>
 
 
 
 
...............
Wednesday, 20 August 2014 13:13

How to Compiling C and C++ Programs

Written by
 

 

Compiling C and C++ Programs

gcc is the "GNU" C Compiler, and g++ is the "GNU C++ compiler, while cc and CC are the Sun C and C++ compilers also available on Sun workstations. Below are several examples that show how to use g++ to compile C++ programs, although much of the information applies to C programs as well as compiling with the other compilers.

Example 1: Compiling a simple program

Consider the following example: Let "hello.C" be a file that contains the following C++ code.
  #include "iostream.h"
  int main() 
  {
    cout << "Hello\n";
  } 
The standard way to compile this program is with the command
  g++ hello.C -o hello 

This command compiles hello.C into an executable program named "hello" that you run by typing 'hello' at the command line. It does nothing more than print the word "hello" on the screen.

Alternatively, the above program could be compiled using the following two commands.
  g++ -c hello.C
  g++ hello.o -o hello 

The end result is the same, but this two-step method first compiles hello.C into a machine code file named "hello.o" and then links hello.o with some system libraries to produce the final program "hello". In fact the first method also does this two-stage process of compiling and linking, but the stages are done transparently, and the intermediate file "hello.o" is deleted in the process.


Frequently used compilation options

C and C++ compilers allow for many options for how to compile a program, and the examples below demonstrate how to use many of the more commonly used options. In each example, "myprog.C" contains C++ source code for the executable "myprog". In most cases options can be combined, although it is generally not useful to use "debugging" and "optimization" options together.

Compile myprog.C so that myprog contains symbolic information that enables it to be debugged with the gdb debugger.
g++ -g myprog.C -o myprog
Have the compiler generate many warnings about syntactically correct but questionable looking code. It is good practice to always use this option with gcc and g++.
g++ -Wall myprog.C -o myprog
Generate symbolic information for gdb and many warning messages.
g++ -g -Wall myprog.C -o myprog
Generate optimized code on a Solaris machine with warnings. The -O is a capital o and not the number 0!
g++ -Wall -O -mv8 myprog.C -o myprog
Generate optimized code on a Solaris machine using Sun's own CC compiler. This code will generally be faster than g++ optimized code.
CC -fast myprog.C -o myprog
Generate optimized code on a Linux machine.
g++ -O myprog.C -o myprog
Compile myprog.C when it contains Xlib graphics routines.
g++ myprog.C -o myprog -lX11
If "myprog.c" is a C program, then the above commands will all work by replacing g++ with gcc and "myprog.C" with "myprog.c". Below are a few examples that apply only to C programs.
Compile a C program that uses math functions such as "sqrt".
gcc myprog.C -o myprog -lm
Compile a C program with the "electric fence" library. This library, available on all the Linux machines, causes many incorrectly written programs to crash as soon as an error occurs. It is useful for debugging as the error location can be quickly determined using gdb. However, it should only be used for debugging as the executable myprog will be much slower and use much more memory than usual.
gcc -g myprog.C -o myprog -lefence

Example 2: Compiling a program with multiple source files

If the source code is in several files, say "file1.C" and "file2.C", then they can be compiled into an executable program named "myprog" using the following command:
  g++ file1.C file2.C -o myprog 
The same result can be achieved using the following three commands:
  g++ -c file1.C
  g++ -c file2.C
  g++ file1.o file2.o -o myprog 
The advantage of the second method is that it compiles each of the source files separately. If, for instance, the above commands were used to create "myprog", and "file1.C" was subsequently modified, then the following commands would correctly update "myprog".
  g++ -c file1.C
  g++ file1.o file2.o -o myprog 
Note that file2.C does not need to be recompiled, so the time required to rebuild myprog is shorter than if the first method for compiling myprog were used. When there are numerous source file, and a change is only made to one of them, the time savings can be significant. This process, though somewhat complicated, is generally handled automatically by a makefile.
Monday, 18 August 2014 07:06

Control DMX512 devices via Raspberry PI

Written by

 

1 RaspberryPI
1 Moving Head Baby LED
1 DMX512
1 USB cable
1 JoyStick Dilong
recommend install Raspbian

 

 

 

 

 

 

 

FTDI lib installation guide

 

D2XX for Linux
--------------
 
As Linux distributions vary these instructions are a guide to installation 
and use.  FTDI has tested the driver and samples with Ubuntu 12.04 (kernel 
version 3.2) for i386 and x86_64, and Debian 6 'squeeze' (kernel version 
2.6.32) for arm926.
 
FTDI developed libftd2xx primarily to aid porting Windows applications 
written with D2XX to Linux.  We intend the APIs to behave the same on
Windows and Linux so if you notice any differences, please contact us 
(see http://www.ftdichip.com/FTSupport.htm).
 
FTDI do not release the source code for libftd2xx.  If you prefer to work
with source code and are starting a project from scratch, consider using
the open-source libFTDI.
 
libftd2xx uses an unmodified version of libusb 
(http://sourceforge.net/projects/libusb/).  Source code for libusb is 
included in the driver distribution.
 
 
 
Installing the D2XX shared library and static library.
------------------------------------------------------
 
1.  tar xfvz libftd2xx1.1.12.tar.gz
 
This unpacks the archive, creating the following directory structure:
 
    build
        arm926
        i386
        x86_64
    examples
    libusb
    ftd2xx.h
    WinTypes.h
 
2.  cd build/arm926
 
3.  sudo -s 
  or, if sudo is not available on your system: 
    su
 
Promotes you to super-user, with installation privileges.  If you're
already root, then step 3 (and step 7) is not necessary.
 
4.  cp lib* /usr/local/lib
 
Copies the libraries to a central location.
 
5.  chmod 0755 /usr/local/lib/libftd2xx.so.1.1.12
 
Allows non-root access to the shared object.
 
6.  ln -sf /usr/local/lib/libftd2xx.so.1.1.12 /usr/local/lib/libftd2xx.so
 
Creates a symbolic link to the 1.1.12 version of the shared object.
 
7.  exit
 
Ends your super-user session.
 
 
 
Building the shared-object examples.
------------------------------------
 
1.  cd examples
 
2.  make -B
 
This builds all the shared-object examples in subdirectories.
 
With an FTDI device connected to a USB port, try one of the 
examples, e.g. reading EEPROM.
 
3.  cd EEPROM/read
 
4.  sudo ./read
 
If the message "FT_Open failed" appears:
    Perhaps the kernel automatically loaded another driver for the 
    FTDI USB device.
 
    sudo lsmod
 
    If "ftdi_sio" is listed:
        Unload it (and its helper module, usbserial), as follows.
 
        sudo rmmod ftdi_sio
        sudo rmmod usbserial
 
    Otherwise, it's possible that libftd2xx does not recognise your 
    device's Vendor and Product Identifiers.  Call FT_SetVIDPID before
    calling FT_Open/FT_OpenEx/FT_ListDevices.
 
 
 
Building the static-library example.
------------------------------------
 
1.  cd examples/static
 
2.  rm lib*
 
Cleans out any existing libraries built for another target.
 
3.  cp /usr/local/lib/libftd2xx.a .
 
4.  make -B
 
5.  sudo ./static_link
 
This example demonstrates writing to, and reading from, a device with a loop-back connector attached.
 
 
 
The examples show how to call a small subset of the D2XX API.  The full API is available here:
http://www.ftdichip.com/Support/Documents/ProgramGuides/D2XX_Programmer%27s_Guide(FT_000071).pdf

 

 
 
 

Code

 

clear.sh

 

#!/bin/bash
#//sudo lsmod
sudo rmmod ftdi_sio
sudo rmmod usbserial
 
compile.sh
 
#!/bin/bash
 
gcc -o dmx512 dmx512.c -L. -lftd2xx -Wl,-rpath /usr/local/lib
 
 
 
 

 

dmx512.c

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../ftd2xx.h"
#include "time.h"
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/joystick.h>
 
#define JOY_DEV "/dev/input/js0"
 
BYTE Start[] = {0x00};
BYTE MAB[256] = {0};
BYTE DMX_Data[512];
DWORD   BytesWritten;
 
void delay_ms(unsigned int howLong);
void delay_us(unsigned int howLong);
 
int main(void)
{
DWORD dwBytesInQueue = 0;
EVENT_HANDLE eh;
FT_STATUS ftStatus;
FT_HANDLE ftHandle;
int iport = 0;
float fAxis;
 
//////////////////////////////////// JOYSTICK Definitions /////////////////////////////
int f;
int joy_fd, *axis=NULL, num_of_axis=0, num_of_buttons=0, x;
char *button=NULL, name_of_joystick[80];
struct js_event js;
 
if( ( joy_fd = open( JOY_DEV , O_RDONLY)) == -1 )
{
printf( "Couldn't open joystick\n" );
return -1;
}
 
ioctl( joy_fd, JSIOCGAXES, &num_of_axis );
ioctl( joy_fd, JSIOCGBUTTONS, &num_of_buttons );
ioctl( joy_fd, JSIOCGNAME(80), &name_of_joystick );
 
axis = (int *) calloc( num_of_axis, sizeof( int ) );
button = (char *) calloc( num_of_buttons, sizeof( char ) );
 
printf("Joystick detected: %s\n\t%d axis\n\t%d buttons\n\n"
, name_of_joystick
, num_of_axis
, num_of_buttons );
 
fcntl( joy_fd, F_SETFL, O_NONBLOCK ); /* use non-blocking mode */
///////////////////////////////////////////////////////////////////////////////////////
 
 
////////////////////////////////////////// DMX ////////////////////////////////////////
ftStatus = FT_Open(iport, &ftHandle);
if(ftStatus != FT_OK) {
/* 
This can fail if the ftdi_sio driver is loaded
use lsmod to check this and rmmod ftdi_sio to remove
also rmmod usbserial
*/
printf("FT_Open(%d) failed\n", iport);
return 1;
}
 
ftStatus = FT_SetDataCharacteristics(ftHandle, FT_BITS_8, FT_STOP_BITS_2,FT_PARITY_NONE);
if(ftStatus != FT_OK)
{
FT_Close(ftHandle);
                printf("Can't set characteristics\n");
                return 1;
}
 
ftStatus = FT_SetBaudRate(ftHandle,250000);
        if(ftStatus != FT_OK) {
                FT_Close(ftHandle);
                printf("Can't set baudrate\n");
                return 1;
        }
//////////////////////////////////////////////////////////////////////////////////////////
 
memset(&DMX_Data[0],0,sizeof(DMX_Data));
 
while(1)
{       
 
//////////////////////////////// Read Joystick data /////////////////////////////
read(joy_fd, &js, sizeof(struct js_event));
/* see what to do with the event */
switch (js.type & ~JS_EVENT_INIT)
{
case JS_EVENT_AXIS:
axis   [ js.number ] = js.value;
break;
case JS_EVENT_BUTTON:
button [ js.number ] = js.value;
break;
}
 
/* print the results */
//printf( "X: %6d  Y: %6d  ", axis[0], axis[1] );
 
//if( num_of_axis > 2 )
// printf("Z: %6d  ", axis[2] );
 
//if( num_of_axis > 3 )
// printf("R: %6d  ", axis[3] );
 
//for( x=0 ; x<num_of_buttons ; ++x )
// printf("B%d: %d  ", x, button[x] );
 
                
 
 
if(axis[0] < 0)
{
if(DMX_Data[0] != 0)
DMX_Data[0] -= 5;
}
 
else if(axis[0] > 0)
{
if(DMX_Data[0] < 0xFF)
DMX_Data[0] += 5;
}
 
else{}
 
 
if(axis[1] < 0)
                {
                        if(DMX_Data[2] != 0)
                        DMX_Data[2] -= 5;
                }
 
                else if(axis[1] > 0)
                {
                        if(DMX_Data[2] < 0xFF)
                        DMX_Data[2] += 5;
                }
 
                else{}
 
 
if(button[0] == 1)
{
DMX_Data[5] = 0xFF;
  DMX_Data[7] = 0xFF;
}
 
if(button[1] == 1)
                {
                        DMX_Data[5] = 0xFF;
                        DMX_Data[6] = 0xFF;
                }
 
if(button[2] == 1)
                {
                        DMX_Data[5] = 0xFF;
                        DMX_Data[8] = 0xFF;
                }
 
       if(button[3] == 1)
                {
                        DMX_Data[5] = 0x00;
                        DMX_Data[6] = 0x00;
DMX_Data[7] = 0x00;
                        DMX_Data[8] = 0x00;
 
                }
 
 
//////////////////////////////////////////////////////////////////////////////////
 
/////////////////////////// Send DMX512 Packet ///////////////////////////////////
ftStatus = FT_SetBreakOn(ftHandle);
delay_ms(10); //10ms delay
ftStatus = FT_SetBreakOff(ftHandle);
delay_us(8);
ftStatus = FT_Write(ftHandle,Start,sizeof(Start),&BytesWritten);
ftStatus = FT_Write(ftHandle,DMX_Data,sizeof(DMX_Data),&BytesWritten);
delay_ms(15);
//////////////////////////////////////////////////////////////////////////////////
 
}
 
return 0;
}
 
void delay_ms (unsigned int howLong)
{
  struct timespec sleeper, dummy ;
 
  sleeper.tv_sec  = (time_t)(howLong / 1000) ;
  sleeper.tv_nsec = (long)(howLong % 1000) * 1000000 ;
 
  nanosleep (&sleeper, &dummy) ;
}
 
 
void delay_us (unsigned int howLong)
{
  struct timespec sleeper, dummy ;
 
  sleeper.tv_sec  = (time_t)(howLong / 1000000) ;
  sleeper.tv_nsec = (long)(howLong % 1000) * 1000 ;
 
  nanosleep (&sleeper, &dummy) ;
}

 

 
 
 
How to compiling C and C++ programs
 
 
 
Archives contains all files you need

 

http://www.info.kmtronic.com/software/Raspberry_PI/DMX512.zip

 

 

 

 

 

 

 

 

 

.....

Friday, 15 August 2014 07:39

Raspberry PI DS18B20 connect to GPIO

Written by

 

How to connect DS18B20 to RaspberryPI GPIO

 

 

 

 

 

How to view what is the ID of the Device?

 

 
In terminal

 

pi@raspberrypi /sys/bus/w1/devices $ cd /sys/bus/w1/devices/
pi@raspberrypi /sys/bus/w1/devices $ ls
28-000004d13e6d  w1_bus_master1
 
 
28-000004d13e6d This is a my ID 

 

 

How to test DS18B20

 

cat /sys/bus/w1/devices/28-000004d13e6d/w1_slave

 

 

t=26500 = 26.5 C

 

PHP Script 

 

<?php
//File to read
$file = '/sys/bus/w1/devices/28-000004d13e6d/w1_slave';
 
//Read the file line by line
$lines = file($file);
 
//Get the temp from second line 
$temp = explode('=', $lines[1]);
 
//Setup some nice formatting (i.e. 21,3)
$temp = number_format($temp[1] / 1000, 1, ',', '');
 
//And echo that temp
echo $temp . "C";
?>
 
 
 
 

 

Download PHP Script - DOWNLOAD

 

Thursday, 14 August 2014 11:47

Raspberry Pi PC Remote Control

Written by

 

 

 

I'll show you how to Remote control USB Web Relays

 

 

Needed 

1 RaspberryPI
1 PC Remote
1 USB relay
1 USB cable
recommend install Raspbian

 

 

 

 

 

C code : kbd.c

 

#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <linux/input.h>
#include <string.h>
#include <stdio.h>
 
static const char *const evval[3] = {
    "RELEASED",
    "PRESSED ",
    "REPEATED"
};
 
char inData[4] = {0,0,0,0}; //Input Buffer
char *ptr;
 
int main(void)
{
    const char *dev = "/dev/input/event0";
    struct input_event ev;
    ssize_t n;
    int fd;
    ptr = &inData[0];
 
    fd = open(dev, O_RDONLY);
    if (fd == -1) {
        fprintf(stderr, "Cannot open %s: %s.\n", dev, strerror(errno));
        return EXIT_FAILURE;
    }
 
while (1) {
        n = read(fd, &ev, sizeof ev);
        if (n == (ssize_t)-1) {
            if (errno == EINTR)
                continue;
            else
                break;
        } else
        if (n != sizeof ev) {
            errno = EIO;
            break;
        }
  if (ev.type == EV_KEY && ev.value >= 0 && ev.value <= 2)
           // printf("%s 0x%04x (%d)\n", evval[ev.value], (int)ev.code, (int)ev.code);
            if(ev.value == 1){//Pressed
if(ev.code == 163){// >| key
popen("exec /home/pi/pcremote/./on.sh","r");
        }
else if(ev.code == 165){// |< key
popen("exec /home/pi/pcremote/./off.sh","r");
}
else{}
   }
    }
    fflush(stdout);
    fprintf(stderr, "%s.\n", strerror(errno));
    return EXIT_FAILURE;
}
 

 

 
 
 
 
File : on.sh
 
#!/bin/bash
# sends on signal to the USB relay
echo -e "\xFF\x01\x01" > /dev/ttyUSB0
 
 
File: off.sh
 
#!/bin/bash
# sends on signal to the USB relay
echo -e "\xFF\x01\x00" > /dev/ttyUSB0
 
 
 
Wednesday, 13 August 2014 12:42

Raspberry Pi ModBus Energy Meter 2

Written by

 

Needed 
1 RaspberryPI
1 SDM120C EnergyMeter
1 USB<>RS485 Converter
1 twisted pair cable
recommend install Raspbian

 

 

 

Set speed USB port - 2400 bps, 8E1

 

stty -F /dev/ttyUSB0 2400 cs8 parenb -parodd

 

 

 

 

C code

 

 

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
 
union
{
char c[4];
float f;
}u;
 
int main(int argc, char* argv[]) {
 
    struct termios serial;
    char inBuff[16];
    char *buffer;
    char choice[5];
    int wcount = 0;
    char cVoltage[] = {0x01,0x04,0x00,0x00,0x00,0x02,0x71,0xCB};
    char cCurrent[] = {0x01,0x04,0x00,0x06,0x00,0x02,0x91,0xCA};
    char cPower[] = {0x01,0x04,0x00,0x0C,0x00,0x02,0xB1,0xC8};
    char cAAPower[] = {0x01,0x04,0x00,0x12,0x00,0x02,0xD1,0xCE};
    char cRAPower[] = {0x01,0x04,0x00,0x18,0x00,0x02,0xF1,0xCC};
    char cPFactor[] = {0x01,0x04,0x00,0x1E,0x00,0x02,0x11,0xCD};
    char cFrequency[] = {0x01,0x04,0x00,0x46,0x00,0x02,0x90,0x1E};
    char cIAEnergy[] = {0x01,0x04,0x00,0x48,0x00,0x02,0xF1,0xDD};
    char cEAEnergy[] = {0x01,0x04,0x00,0x4A,0x00,0x02,0x50,0x1D};
    char cTAEnergy[] = {0x01,0x04,0x01,0x56,0x00,0x02,0x90,0x27};
 
    int fd = open("/dev/ttyUSB2", O_RDWR | O_NOCTTY | O_NDELAY);
 
    if (fd == -1) {
        perror(argv[2]);
        return -1;
    }
 
    if (tcgetattr(fd, &serial) < 0) {
        perror("Getting configuration");
        return -1;
    }
 
    //////////////////// Set up Serial Configuration ////////////
    serial.c_iflag = 0;
    serial.c_oflag = 0;
    serial.c_lflag = 0;
    serial.c_cflag = 0;
 
    serial.c_cc[VMIN] = 0;
    serial.c_cc[VTIME] = 10;
 
    serial.c_cflag = B2400 | CS8 | PARENB | CREAD & ~PARODD;
    fcntl(fd,F_SETFL,0);
    tcsetattr(fd, TCSANOW, &serial); // Apply configuration
    //////////////////////////////////////////////////////////////
 
    
   int rcount;  
   buffer = &inBuff[0];
   int i = 0;
   int j = 0;
 
   //////////////////////////         Voltage                /////////////////////////////
   i = 0; j = 0;
   memset(&inBuff[0],0,sizeof(inBuff));
   write(fd,cVoltage,sizeof(cVoltage));
   buffer = &inBuff[0];
   printf("Sent: ");
   for(j = 0;j < sizeof(cVoltage);j++)
   {
printf("%02x ",cVoltage[j]);
   }
   printf("\r\n");
   printf("Received: " );
while( (rcount = read(fd,buffer,1)) > 0)
{
      if (rcount < 0) {
           perror("Read");
          return -1;
        }
 
      buffer++;
printf("%02x ",inBuff[i]); i++;
  }
    u.c[3] = inBuff[3];
    u.c[2] = inBuff[4];
    u.c[1] = inBuff[5];
    u.c[0] = inBuff[6];
printf("\r\n");
printf("Voltage: %4.2f V \r\n\r\n",u.f);
///////////////////////////////////////////////////////////////////////////////////////////
 
 
 //////////////////////////         Current                /////////////////////////////
   i = 0; j = 0;
   memset(&inBuff[0],0,sizeof(inBuff));
   write(fd,cCurrent,sizeof(cCurrent));
   buffer = &inBuff[0];
   printf("Sent: ");
   for(j = 0;j < sizeof(cCurrent);j++)
   {
        printf("%02x ",cCurrent[j]);
   }
   printf("\r\n");
   printf("Received: " );
        while( (rcount = read(fd,buffer,1)) > 0)
        {
           if (rcount < 0) {
           perror("Read");
           return -1;
        }
 
        buffer++;
        printf("%02x ",inBuff[i]); i++;
  }
    u.c[3] = inBuff[3];
    u.c[2] = inBuff[4];
    u.c[1] = inBuff[5];
    u.c[0] = inBuff[6];
printf("\r\n");
printf("Current: %4.2f A \r\n\r\n",u.f);
///////////////////////////////////////////////////////////////////////////////////////////
 
 
///////////////////////////////         Power               ///////////////////////////////
   i = 0; j = 0;
   memset(&inBuff[0],0,sizeof(inBuff));
   write(fd,cPower,sizeof(cPower));
   buffer = &inBuff[0];
   printf("Sent: ");
   for(j = 0;j < sizeof(cPower);j++)
   {
        printf("%02x ",cPower[j]);
   }
   printf("\r\n");
   printf("Received: " );
        while( (rcount = read(fd,buffer,1)) > 0)
        {
           if (rcount < 0) {
           perror("Read");
           return -1;
        }
 
        buffer++;
        printf("%02x ",inBuff[i]); i++;
  }
    u.c[3] = inBuff[3];
    u.c[2] = inBuff[4];
    u.c[1] = inBuff[5];
    u.c[0] = inBuff[6];
printf("\r\n");
printf("Power: %4.2f W \r\n\r\n",u.f);
///////////////////////////////////////////////////////////////////////////////////////////
 
 
///////////////////////////////   Active Apparent Power     ///////////////////////////////
   i = 0; j = 0;
   memset(&inBuff[0],0,sizeof(inBuff));
   write(fd,cAAPower,sizeof(cAAPower));
   buffer = &inBuff[0];
   printf("Sent: ");
   for(j = 0;j < sizeof(cAAPower);j++)
   {
        printf("%02x ",cAAPower[j]);
   }
   printf("\r\n");
   printf("Received: " );
        while( (rcount = read(fd,buffer,1)) > 0)
        {
           if (rcount < 0) {
           perror("Read");
           return -1;
        }
 
        buffer++;
        printf("%02x ",inBuff[i]); i++;
  }
    u.c[3] = inBuff[3];
    u.c[2] = inBuff[4];
    u.c[1] = inBuff[5];
    u.c[0] = inBuff[6];
printf("\r\n");
printf("Active Apparent Power: %4.2f VA \r\n\r\n",u.f);
///////////////////////////////////////////////////////////////////////////////////////////
 
///////////////////////////////   Reactive Apparent Power     ///////////////////////////////
   i = 0; j = 0;
   memset(&inBuff[0],0,sizeof(inBuff));
   write(fd,cRAPower,sizeof(cRAPower));
   buffer = &inBuff[0];
   printf("Sent: ");
   for(j = 0;j < sizeof(cRAPower);j++)
   {
        printf("%02x ",cRAPower[j]);
   }
   printf("\r\n");
   printf("Received: " );
        while( (rcount = read(fd,buffer,1)) > 0)
        {
           if (rcount < 0) {
           perror("Read");
           return -1;
        }
 
        buffer++;
        printf("%02x ",inBuff[i]); i++;
  }
    u.c[3] = inBuff[3];
    u.c[2] = inBuff[4];
    u.c[1] = inBuff[5];
    u.c[0] = inBuff[6];
printf("\r\n");
printf("Reactive Apparent Power: %4.2f VAr \r\n\r\n",u.f);
///////////////////////////////////////////////////////////////////////////////////////////
 
////////////////////////////////////   Power Factor     ///////////////////////////////////
   i = 0; j = 0;
   memset(&inBuff[0],0,sizeof(inBuff));
   write(fd,cPFactor,sizeof(cPFactor));
   buffer = &inBuff[0];
   printf("Sent: ");
   for(j = 0;j < sizeof(cPFactor);j++)
   {
        printf("%02x ",cPFactor[j]);
   }
   printf("\r\n");
   printf("Received: " );
        while( (rcount = read(fd,buffer,1)) > 0)
        {
           if (rcount < 0) {
           perror("Read");
           return -1;
        }
 
        buffer++;
        printf("%02x ",inBuff[i]); i++;
  }
    u.c[3] = inBuff[3];
    u.c[2] = inBuff[4];
    u.c[1] = inBuff[5];
    u.c[0] = inBuff[6];
printf("\r\n");
printf("Power Factor: %4.2f \r\n\r\n",u.f);
///////////////////////////////////////////////////////////////////////////////////////////
 
/////////////////////////////////////   Frequency     /////////////////////////////////////
   i = 0; j = 0;
   memset(&inBuff[0],0,sizeof(inBuff));
   write(fd,cFrequency,sizeof(cFrequency));
   buffer = &inBuff[0];
   printf("Sent: ");
   for(j = 0;j < sizeof(cFrequency);j++)
   {
        printf("%02x ",cFrequency[j]);
   }
   printf("\r\n");
   printf("Received: " );
        while( (rcount = read(fd,buffer,1)) > 0)
        {
           if (rcount < 0) {
           perror("Read");
           return -1;
        }
 
        buffer++;
        printf("%02x ",inBuff[i]); i++;
  }
    u.c[3] = inBuff[3];
    u.c[2] = inBuff[4];
    u.c[1] = inBuff[5];
    u.c[0] = inBuff[6];
printf("\r\n");
printf("Frequency: %4.2f Hz \r\n\r\n",u.f);
///////////////////////////////////////////////////////////////////////////////////////////
 
/////////////////////////////  Import Active Energy   /////////////////////////////////////
   i = 0; j = 0;
   memset(&inBuff[0],0,sizeof(inBuff));
   write(fd,cIAEnergy,sizeof(cIAEnergy));
   buffer = &inBuff[0];
   printf("Sent: ");
   for(j = 0;j < sizeof(cIAEnergy);j++)
   {
        printf("%02x ",cIAEnergy[j]);
   }
   printf("\r\n");
   printf("Received: " );
        while( (rcount = read(fd,buffer,1)) > 0)
        {
           if (rcount < 0) {
           perror("Read");
           return -1;
        }
 
        buffer++;
        printf("%02x ",inBuff[i]); i++;
  }
    u.c[3] = inBuff[3];
    u.c[2] = inBuff[4];
    u.c[1] = inBuff[5];
    u.c[0] = inBuff[6];
printf("\r\n");
printf("Import Active Energy: %4.2f KWh \r\n\r\n",u.f);
///////////////////////////////////////////////////////////////////////////////////////////
 
/////////////////////////////  Export Active Energy   /////////////////////////////////////
   i = 0; j = 0;
   memset(&inBuff[0],0,sizeof(inBuff));
   write(fd,cEAEnergy,sizeof(cEAEnergy));
   buffer = &inBuff[0];
   printf("Sent: ");
   for(j = 0;j < sizeof(cEAEnergy);j++)
   {
        printf("%02x ",cEAEnergy[j]);
   }
   printf("\r\n");
   printf("Received: " );
        while( (rcount = read(fd,buffer,1)) > 0)
        {
           if (rcount < 0) {
           perror("Read");
           return -1;
        }
 
        buffer++;
        printf("%02x ",inBuff[i]); i++;
  }
    u.c[3] = inBuff[3];
    u.c[2] = inBuff[4];
    u.c[1] = inBuff[5];
    u.c[0] = inBuff[6];
printf("\r\n");
printf("Export Active Energy: %4.2f KWh \r\n\r\n",u.f);
///////////////////////////////////////////////////////////////////////////////////////////
 
/////////////////////////////  Total  Active Energy   /////////////////////////////////////
   i = 0; j = 0;
   memset(&inBuff[0],0,sizeof(inBuff));
   write(fd,cTAEnergy,sizeof(cTAEnergy));
   buffer = &inBuff[0];
   printf("Sent: ");
   for(j = 0;j < sizeof(cTAEnergy);j++)
   {
        printf("%02x ",cTAEnergy[j]);
   }
   printf("\r\n");
   printf("Received: " );
        while( (rcount = read(fd,buffer,1)) > 0)
        {
           if (rcount < 0) {
           perror("Read");
           return -1;
        }
 
        buffer++;
        printf("%02x ",inBuff[i]); i++;
  }
    u.c[3] = inBuff[3];
    u.c[2] = inBuff[4];
    u.c[1] = inBuff[5];
    u.c[0] = inBuff[6];
printf("\r\n");
printf("Total Active Energy: %4.2f KWh \r\n\r\n",u.f);
///////////////////////////////////////////////////////////////////////////////////////////
 
 
 
close(fd);
}
 

 

 

 

 

 

Download All files - DOWNLOAD

 

Wednesday, 13 August 2014 07:17

Raspberry Pi ModBus Energy Meter 1

Written by

 

Needed 
1 RaspberryPI
1 EJS 212 D2AMX Energy meter with ModBus
1 USB<>RS485 Converter
1 twisted pair cable
recommend install Raspbian

 

 

 

Set speed USB port - 9'600 bps, 8E1

 

stty -F /dev/ttyUSB0 9600 cs8 parenb -parodd

 

 

C code

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
 
int main(int argc, char* argv[]) {
 
    struct termios serial;
    char inBuff[16];
    char *buffer;
    char choice[5];
    int wcount = 0;
    char rdINPUT[8]= {0x22,0x04,0x00,0x00,0x00,0x06,0x77,0x5B};
    int fd = open("/dev/ttyUSB2", O_RDWR | O_NOCTTY | O_NDELAY);
    double tariff1,tariff2,tariff3;
 
    if (fd == -1) {
        perror(argv[2]);
        return -1;
    }
 
    if (tcgetattr(fd, &serial) < 0) {
        perror("Getting configuration");
        return -1;
    }
 
    //////////////////// Set up Serial Configuration ////////////
    serial.c_iflag = 0;
    serial.c_oflag = 0;
    serial.c_lflag = 0;
    serial.c_cflag = 0;
 
    serial.c_cc[VMIN] = 0;
    serial.c_cc[VTIME] = 10;
 
    serial.c_cflag = B9600 | CS8 | PARENB | CREAD & ~PARODD;
    fcntl(fd,F_SETFL,0);
    tcsetattr(fd, TCSANOW, &serial); // Apply configuration
    //////////////////////////////////////////////////////////////
 
    
   int rcount;  
   buffer = &inBuff[0];
   int i = 0;
   int j = 0;
   write(fd,rdINPUT,8);
   buffer = &inBuff[0];
 
   printf("Send: ");
   for(j = 0;j < sizeof(rdINPUT);j++)
   {
printf("%02x ",rdINPUT[j]);
   }
   printf("\r\n");
   printf("Received: " );
while( (rcount = read(fd,buffer,1)) > 0)
{
      if (rcount < 0) {
           perror("Read");
          return -1;
        }
 
      buffer++;
printf("%02x ",inBuff[i]); i++;
  }
       tariff2 =(double)(256*256*256*inBuff[3]) + (double)(256*256*inBuff[4]) + (double)(256*inBuff[5]) + (double)inBuff[6];
       tariff2 =(double)(256*256*256*inBuff[7]) + (double)(256*256*inBuff[8]) + (double)(256*inBuff[9]) + (double)inBuff[10];
       tariff1 =(double)(256*256*256*inBuff[11]) + (double)(256*256*inBuff[12]) + (double)(256*inBuff[13]) + (double)inBuff[14];
       printf("\r\n");
       printf("Peak Tariff 3: %4.3f KWh",tariff3/100);
       printf("\r\n");
       printf("Daily Tariff 2: %4.3f KWh",tariff2/100);
       printf("\r\n");
       printf("Night Tariff 1: %4.3f KWh",tariff1/100);
       printf("\r\n");
 
close(fd);
}
 

 

 

 

 

Input Registers

Address

Value

0x00

Energy tariff 3 - peak (most significant part)

0x01

Energy tariff 3 - peak (low significant part)

0x02

Energy tariff 2 - peak (most significant part)

0x03

Energy tariff 2 - peak (low significant part)

0x04

Energy tariff 1 - peak (most significant part)

0x05

Energy tariff 1 - peak (low significant part)

 

Note: All values ​​of the energy registers are in hundredths of KWh, 1 from the register corresponds to 0.01 KWh

 

 

 

 

 
 
 
 
Tuesday, 12 August 2014 12:11

Raspberry Pi Door Lock 03

Written by

 

 

This project will show how to control door lock system using basic free code via keyboard.

 

 

All you need is:
1x Raspberry Pi
1x USB Keyboard
1x Electromechanical Strike
1x USB One Channel Relay controller

 

 

 

Electromechanical Strike
http://www.amig.es/en/strike-body-mod-18-19/g/372

 

 

 

 

 

By entering simple PIN code (example 1234 & ENTER) on the keyboard you can open the door.

 

 File : on.sh

#!/bin/bash
# sends on signal to the USB relay
echo -e "\xFF\x01\x01" > /dev/ttyUSB0 ;sleep 1
echo -e "\xFF\x01\x00" > /dev/ttyUSB0 

 

 

 

File : keyboard.c

 

#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <linux/input.h>
#include <string.h>
#include <stdio.h>
 
static const char *const evval[3] = {
    "RELEASED",
    "PRESSED ",
    "REPEATED"
};
 
char PIN[4] = {79,80,81,75}; //1,2,3,4
char inData[4] = {0,0,0,0}; //Input Buffer
char *ptr;
int cntr = 0; //Counter
 
int main(void)
{
    const char *dev = "/dev/input/event0";
    struct input_event ev;
    ssize_t n;
    int fd;
    ptr = &inData[0];
 
    fd = open(dev, O_RDONLY);
    if (fd == -1) {
        fprintf(stderr, "Cannot open %s: %s.\n", dev, strerror(errno));
        return EXIT_FAILURE;
    }
 
while (1) {
        n = read(fd, &ev, sizeof ev);
        if (n == (ssize_t)-1) {
            if (errno == EINTR)
                continue;
            else
                break;
        } else
        if (n != sizeof ev) {
            errno = EIO;
            break;
        }
  if (ev.type == EV_KEY && ev.value >= 0 && ev.value <= 2)
           // printf("%s 0x%04x (%d)\n", evval[ev.value], (int)ev.code, (int)ev.code);
            if(ev.value == 1){//Pressed
if(ev.code == 96){//Enter
if(memcmp(PIN,inData,4) == 0)
{
printf("Code accepted!\r\n");
popen("exec /home/pi/keyboard/./on.sh","r");
}
ptr = &inData[0];
memset(ptr,0,4);
cntr = 0;
}
else{
if(cntr == 4){//$ digits limit
cntr = 0;
ptr = &inData[0];
}
*ptr = ev.code;
ptr++;
                cntr++;
}
 
}
 
    }
    fflush(stdout);
    fprintf(stderr, "%s.\n", strerror(errno));
    return EXIT_FAILURE;
}

 

 

View how to compile C Files 

http://info.kmtronic.com/how-to-compiling-c-and-c-programs.html

 

 

All Files DOWNLOAD

 

 

 

 

 

 

 

Page 8 of 33