PIC16F684 Blink LED with PICkit 3

This post is for beginners who would like to run a simple LED blinking example using PIC16F684 with PICkit 3. Most of the beginners may start learning by using Demo board that is usually shipped with the PICkit 3 but this post aims to connect PICkit 3 directly to the PIC16F684. This post assumes that MPLAB IDE and XC8 compiler have been successfully installed.

PICkit 3 is a programmer and debugger for PIC microcontollers. PICkit 3 has 6 pins but pin 6 is not used in our case. Here is the connection between PICkit 3 and PIC16F684

PICkit 3 pins on the left and PIC16F684 pins on the right
pin 1 <-----> pin 4 
pin 2 <-----> pin 1 (Vdd)
pin 3 <-----> pin 14 (Vss)
pin 4 <-----> pin 13
pin 5 <-----> pin 12

In this example, an LED is connected to PIC16F684 on pin number 9 (RC1) and the other side is to ground. Note that pin 14 (Vss) acts as ground. Also, internal clock of the PIC16F684 is used so configuration bit of FOSC must be set to INTOSCIO. Here is the code for blinking an LED on port RC1.

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

// CONFIG
#pragma config FOSC = INTOSCIO
#pragma config WDTE = OFF 
#pragma config PWRTE = OFF 
#pragma config MCLRE = OFF 
#pragma config CP = OFF 
#pragma config CPD = OFF 
#pragma config BOREN = OFF 
#pragma config IESO = OFF 
#pragma config FCMEN = OFF 

#define _XTAL_FREQ 8000000
/*
 * 
 */
int main(int argc, char** argv) {

 TRISCbits.TRISC1 = 0;
 ANSEL = 0;

 while(1)
 {
 /* TODO <INSERT USER APPLICATION CODE HERE> */

 RC1 = 0;
 __delay_ms(500);
 RC1 = 1;
 __delay_ms(500);
 }
 
 return (EXIT_SUCCESS);
}

 

iOS Objective C: Obtaining MAC address of an IP from ARP Table

There are many reasons where one might want to obtain a MAC address of a host (or network device) in a local area network given a valid IP address to be used in iOS application development. In computer networking, Address Resolution Protocol (ARP) is used for resolution of a network layer address into a link layer address. Typically ARP involves exchanging ARP messages to obtain MAC address of a host given that IP address of the host is known. This link provides a nice explanation of ARP.

ARP table is a cache which stores IP addresses and associated MAC addresses of the network devices. Smartphones such as Android and iOS platforms also contain an ARP table. One can view ARP table on Mac OS X by using terminal and type command:

arp -a
(10.0.0.1) at e8:fc:af:ff:99:d5 on en0 ifscope [ethernet]
(10.0.0.5) at 80:ea:96:e6:55:4f on en0 ifscope [ethernet]
(10.0.0.12) at a4:5e:60:bd:5b:2d on en0 ifscope permanent [ethernet]
(10.0.0.16) at f4:f9:51:d3:e:35 on en0 ifscope [ethernet]
(10.0.0.22) at f4:f9:51:d3:e:36 on en0 ifscope [ethernet]
(10.0.0.255) at ff:ff:ff:ff:ff:ff on en0 ifscope [ethernet]

If we could programmatically access ARP table we could also obtain a MAC address of the associated IP address. Thanks to Evgeniy Kapralov who posted arpmac project on GitHub in accessing ARP table of the iOS device programmatically.

Why do we need this? Well, iOS 8 does not provide APIs in accessing ARP table and there may be cases where one might want to programmatically determine MAC address of a network device on iOS platform.

PL2303 Prolific USB to TTL Driver for Windows 8.1

After plugging in the USB to TTL (3.3V) to the PC with Windows 8.1 in order to connect to the Raspberry Pi according to the lesson in Adafruit Window 8.1 does not seem to have appropriate driver for the device but I manage to get it working using the following steps:

1. Download the driver Profilic_Win8_x64_x86 and extract it
2. Open Device Manager3. Expand Ports (COM & LPT) 
4. Right click device name Prolifc USB-to-Serial Comm Port and select Property
5. Select Driver tab
6. Click Update Driver
7. Choose Browse my computer for driver software
8. Choose Let me pick from a list of device drivers on my computer
9. Click Have Disk
10. Choose the folder that you extracted from the downloaded zip file.
11. Choose file "ser2pl.inf" and click Open
12. Click OK
13. After successfully installed restart your PC.

 

 

 

Enable Telnet on Mac OS X Mavericks

Telnet is a network protocol and a network application that provides bidirectional interactive text-oriented communication between two endpoints. One endpoint acts as a server and another acts as a client. You can use Telnet client on Mac OS X by running telnet command in the Terminal followed by ip address or domain name of the server:

anand$ telnet localhost

However, if you need to make your Mac OS X (Mavericks) to run as a Telnet server you can enable it from the Terminal via launchctl command. You can follow the following steps:

anand$ sudo launchctl
Password:
launchd% load -F /System/Library/LaunchDaemons/telnet.plist 
launchd% exit

Now you can try using Telnet client to your Mac. For example, you can use telnet command on the Terminal to access the Telnet server on your Mac:

anand$ telnet localhost
Trying ::1...
Connected to localhost.
Escape character is '^]'.
login:

Now you can provide log in information to gain access to your Mac via Telnet!!.

Note that Telnet is a plain text-based application without any encryption and it is not secure. You may want to use SSH instead if you want to do remote management of your Mac.

This technique should also work with Mac OS X Lion as stated in this post

Clone or Backup Raspberry Pi SD Card with Mac OS X

If you need to backup or make a copy of Raspberry Pi SD Card then there are some tools available. However, this post explain how to use command line on Mac OS X in creating an image file (backup file) of an SD Card and later this image file can be used to put into another SD Card.

First of all run the terminal on your Mac and type command df -h

AnandMac-2:~ anand$ df -h
Filesystem                          Size   Used  Avail Capacity  iused   ifree %iused  Mounted on
/dev/disk0s2                       247Gi  231Gi   16Gi    94% 60530779 4093113   94%   /
devfs                              187Ki  187Ki    0Bi   100%      648       0  100%   /dev
map -hosts                           0Bi    0Bi    0Bi   100%        0       0  100%   /net
map auto_home                        0Bi    0Bi    0Bi   100%        0       0  100%   /home
localhost:/_orgYFQCOsa4qp3lbDpDV7  247Gi  247Gi    0Bi   100%        0       0  100%   /Volumes/MobileBackups
/dev/disk0s4                        51Gi   46Gi  5.0Gi    91%   254868 5354408    5%   /Volumes/BOOTCAMP

Then connect SD Card that contains data to backup to the SD Card reader. Run the command df -h again.

AnandMac-2:~ anand$ df -h
Filesystem                          Size   Used  Avail Capacity  iused   ifree %iused  Mounted on
/dev/disk0s2                       247Gi  231Gi   16Gi    94% 60530901 4092991   94%   /
devfs                              190Ki  190Ki    0Bi   100%      656       0  100%   /dev
map -hosts                           0Bi    0Bi    0Bi   100%        0       0  100%   /net
map auto_home                        0Bi    0Bi    0Bi   100%        0       0  100%   /home
localhost:/_orgYFQCOsa4qp3lbDpDV7  247Gi  247Gi    0Bi   100%        0       0  100%   /Volumes/MobileBackups
/dev/disk0s4                        51Gi   46Gi  5.0Gi    91%   254868 5354408    5%   /Volumes/BOOTCAMP
/dev/disk1s1                       7.4Gi  1.9Mi  7.4Gi     1%        0       0  100%   /Volumes/Kingston

Now compare the results of running command df -h before and after inserting the SD card and look for the new device. In my case it is /dev/disk1s1. This is the device name of the partition.

After finding the device name of the partition now we are going to determine the raw device name of the entire disk by omitting the final “s1” and replacing “disk” with “rdisk” (this is very important: you will lose all data on the hard drive on your computer if you get the wrong device name). Make sure the device name is the name of the whole SD card as described above, not just a partition of it, for example, rdisk1, not rdisk1s1. In my case it is /dev/rdisk1

Run the following command to create an image file from the SD Card

sudo dd if=/dev/rdisk1 of=/path/to/filename.img bs=1m

The above command is simply taking the whole disk (SD card) and create an image file to the location “/path/to/filename.img”. You may use any filename. Note that dd command will not feedback anything to the terminal unless there is an error or it is finished. While waiting for the dd command to finish you may see the progress by pressing Control+t

In order to create an SD card from the image file (any image file or the one you just created), determine the device name of the partition of the SD card using df -h as described above. In my case it is /dev/disk1s1. Then unmount the partition so that you will be allowed to overwrite the disk:

sudo diskutil unmount /dev/disk1s1

Then run the following command

sudo dd bs=1m if=/path/to/filename.img of=/dev/rdisk1

After the dd command finishes, eject the card:

sudo diskutil eject /dev/rdisk1

 

Raspberry Pi with 3G Air Card using Sakis3G

I am involving in a project where I have to connect to the Internet using 3G USB Air Card. install the following packages

sudo apt-get install usb-modeswitch ppp libusb-dev

Sakis3G is a tweaked shell script that helps end user connecting through through 3G/UMTS/GPRS. Get sakis3g source from git

git clone git://github.com/Trixarian/sakis3g-source
cd sakis-source
mkdir build
./compile
sudo cp build/sakis3gz /usr/bin/sakis3g

When I first compiled it failed to compile and I had to install libusb-dev. After successfully compile you need to run as root. In fact after compilation it recommend:

sudo bash || su
to connect use
sakis3g connect
or
sakis3g --interactive connect

My operator requires to put APN but no username and password required. Sakis3g will guide you how to enter APN but if you do not put username it will quit and cannot connect. What I do is I enter a blank space for my username and password then it connects.

Raspberry Pi Ultrasonic Sensor (HC-SR04)

One may want to connect an ultrasonic sensor with a Raspberry Pi. In fact, there many posts talks about this already but I have it here for my own record and in fact most of the content of this post inspired by this site.

I have got HC-SR04 ultrasonic sensor which is a fairly cheap sensor in hand. An ultrasonic sensor can be used to measure the distance between the object itself and an object in front of it by sending out an ultrasonic pulse and listening for its echo (a reply or response). In practice one could connect this sensor with other devices other than Raspberry Pi such as Arduino.

Here is the connectivity (you can also see here):

Vcc --> 5V pin
Trig --> GPIO pin (GPIO 17)
Echo --> Series with 1K Ohm and goes to GPIO pin (GPIO 27)
GND --> Ground pin

Note for Raspberry Pi model B: GPIO 17 is pin 11, GPIO 27 is pin 13, 5V is pin 2 and Ground is pin 6.

One may use any other GPIO pins. In this case GPIO 17 will be an output from Raspberry Pi to the sensor’s Trig pin. This pin is used to trigger the sensor to send out an ultrasonic signal. According to the datasheet a signal of 10 microseconds is a required to trigger the sensor.One may use voltage divider to lower down 5V to 3.3V instead.

In addition, a 1K Ohm resister is required to drop down the output of the Echo pin to 3.3V since Raspberry Pi GPIO pins support 3.3V. Hence, the GPIO 27 used in this case acts as an input pin from the sensor to the Pi.

Here is the code (slightly modified from here)

#!/usr/bin/python

# remember to change the GPIO values below to match your sensors
# GPIO output = the pin that's connected to "Trig" on the sensor
# GPIO input = the pin that's connected to "Echo" on the sensor

def reading(sensor):
    import time
    import RPi.GPIO as GPIO
    
    # Disable any warning message such as GPIO pins in use
    GPIO.setwarnings(False)
    
    # use the values of the GPIO pins, and not the actual pin number
    # so if you connect to GPIO 25 which is on pin number 22, the 
    # reference in this code is 25, which is the number of the GPIO 
    # port and not the number of the physical pin
    GPIO.setmode(GPIO.BCM)
    
    if sensor == 0:
        
        # point the software to the GPIO pins the sensor is using
        # change these values to the pins you are using
        # GPIO output = the pin that's connected to "Trig" on the sensor
        # GPIO input = the pin that's connected to "Echo" on the sensor
        GPIO.setup(17,GPIO.OUT)
        GPIO.setup(27,GPIO.IN)
        GPIO.output(17, GPIO.LOW)
        
        # found that the sensor can crash if there isn't a delay here
        # no idea why. If you have odd crashing issues, increase delay
        time.sleep(0.3)
        
        # sensor manual says a pulse ength of 10Us will trigger the 
        # sensor to transmit 8 cycles of ultrasonic burst at 40kHz and 
        # wait for the reflected ultrasonic burst to be received
        
        # to get a pulse length of 10Us we need to start the pulse, then
        # wait for 10 microseconds, then stop the pulse. This will 
        # result in the pulse length being 10Us.
        
        # start the pulse on the GPIO pin 
        # change this value to the pin you are using
        # GPIO output = the pin that's connected to "Trig" on the sensor
        GPIO.output(17, True)
        
        # wait 10 micro seconds (this is 0.00001 seconds) so the pulse
        # length is 10Us as the sensor expects
        time.sleep(0.00001)
        
        # stop the pulse after the time above has passed
        # change this value to the pin you are using
        # GPIO output = the pin that's connected to "Trig" on the sensor
        GPIO.output(17, False)

        # listen to the input pin. 0 means nothing is happening. Once a
        # signal is received the value will be 1 so the while loop
        # stops and has the last recorded time the signal was 0
        # change this value to the pin you are using
        # GPIO input = the pin that's connected to "Echo" on the sensor
        while GPIO.input(27) == 0:
          signaloff = time.time()
        
        # listen to the input pin. Once a signal is received, record the
        # time the signal came through
        # change this value to the pin you are using
        # GPIO input = the pin that's connected to "Echo" on the sensor
        while GPIO.input(27) == 1:
          signalon = time.time()
        
        # work out the difference in the two recorded times above to 
        # calculate the distance of an object in front of the sensor
        timepassed = signalon - signaloff
        
        # we now have our distance but it's not in a useful unit of
        # measurement. So now we convert this distance into centimetres
        distance = timepassed * 17000
        
        # return the distance of an object in front of the sensor in cm
        return distance
        
        # we're no longer using the GPIO, so tell software we're done
        GPIO.cleanup()

    else:
        print "Incorrect usonic() function varible."

        
print reading(0)

The above code is saved with file name ‘usonic.py’. Ensure that this code is executable.

chmod +x usonic.py

The code must be run with sudo (super user) since it requires accessing hardware.

sudo ./usonic.py

 

Ubuntu – start Firefox in fullscreen mode from command line (Terminal)

Somehow I want to start firefox on my Ubuntu 12.04 LTS from command line in fullscreen mode. Firefox can be invoked from command line using command:

firefox

However, the command does not seem to have fullscreen option. This site uses xdotool to simulate that button F11 on the keyboard is pressed so the firefox goes on fullscreen. Hence, I a simple bash script helps achieving this task. Here is the script:

firefox http://localhost/abc.html & # one can use any url
xdotool key F11 # hit full screen

I save the above script as “firefoxfullscreen.sh” and I run it whenever I need it. Note that the script is relatively simple and it should be modified based on your purposes. One possibility is to add delay in between the two line as shown below:

firefox http://localhost/abc.html & # one can use any url
sleep 5
xdotool key F11 # hit full screen

Send Commands or Data to Other Terminals

Somehow I need to send commands from one terminal to another. Luckily I found this post which saves my time. Here is a set of steps that one need to follow:

Copy the code below to a C file (e.g. ttyecho.c)

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <string.h>
#include <unistd.h>

void print_help(char *prog_name) {
        printf("Usage: %s [-n] DEVNAME COMMAND\n", prog_name);
        printf("Usage: '-n' is an optional argument if you want to push a new line at the end of the text\n");
        printf("Usage: Will require 'sudo' to run if the executable is not setuid root\n");
        exit(1);
}

int main (int argc, char *argv[]) {
    char *cmd, *nl = "\n";
    int i, fd;
    int devno, commandno, newline;
    int mem_len;
    devno = 1; commandno = 2; newline = 0;
    if (argc < 3) {
        print_help(argv[0]);
    }
    if (argc > 3 && argv[1][0] == '-' && argv[1][1] == 'n') {
        devno = 2; commandno = 3; newline=1;
    } else if (argc > 3 && argv[1][0] == '-' && argv[1][1] != 'n') {
        printf("Invalid Option\n");
        print_help(argv[0]);
    }
    fd = open(argv[devno],O_RDWR);
    if(fd == -1) {
        perror("open DEVICE");
        exit(1);
    }
    mem_len = 0;
    for ( i = commandno; i < argc; i++ ) {
        mem_len += strlen(argv[i]) + 2;
        if ( i > commandno ) {
            cmd = (char *)realloc((void *)cmd, mem_len);
        } else { //i == commandno
            cmd = (char *)malloc(mem_len);
        }

        strcat(cmd, argv[i]);
        strcat(cmd, " ");
    }
  if (newline == 0)
        usleep(225000);
    for (i = 0; cmd[i]; i++)
        ioctl (fd, TIOCSTI, cmd+i);
    if (newline == 1)
        ioctl (fd, TIOCSTI, nl);
    close(fd);
    free((void *)cmd);
    exit (0);
}

Run the following command in the directory where the C file (ttyecho.c) has been created

make ttyecho

The above command will create an executable file named ttyecho Copy this file to the bin directory under your Home Directory. In my case it is /home/pi/bin . Create the bin directory if it doesn’t exist. It is a good practice to keep all custom binaries/executables in this bin directory.

Now change the owner/group to root using the following commands

sudo chown root:root ttyecho
sudo chmod u+s ttyecho

The above two commands change the owner/group to root and set the setuid bit for the executable which will allow you to run the utility with root permissions.

Start another terminal or switch to another existing terminal that you wish to control and execute the command tty in order to determine the terminal. You can see a sample output below.

@~$ tty
/dev/pts/5

Now to execute a command on /dev/pts/5, run the following command in the controlling/original terminal.

ttyecho -n /dev/pts/5 ls

You will see that the ls command is executed in /dev/pts/5. The -n option makes ttyecho send a newline after the command, so that the command gets executed and not just inserted.