Monday, October 21, 2013

Which PC/gadget has the highest pixel resolution?

Here I have collected and calculated PPI (Pixels per Inch) for some laptops and tablets.



Screen Diameter (inch)Screen Ratio (Width/Height)Angle (rad)Screen widthScreen HeightNumber Of Pixels (Horizontal)Number Of Pixels (Vertical)PPI
15.61.780.5113.607.65128072094.14HP Pavilion 2000T
15.61.780.5113.607.651366768100.44
17.31.780.5115.088.481600900106.11HP Pavilion 17z Laptop
141.780.5112.206.861366768111.92HP Pavilion 14 Chromebook
15.61.780.5113.607.651600900117.68
18.41.780.5116.049.0219201080119.72Alienware 18
15.61.600.5613.238.2716801050127.00
17.31.780.5115.088.4819201080127.34HP ENVY 17t 1080p
15.61.780.5113.607.6519201080141.21HP ENVY 15t Quad 1080p
15.61.780.5113.607.6519201080141.21Dell XPS 15
8.91.600.567.554.721280800169.60Amazon Kindle HD
17.31.780.5115.088.4825601440169.78
15.41.600.5613.068.1628801800220.53Apple Macbook 15.4 with Retina Display
13.31.780.5111.596.5225601440220.84Toshiba KIRAbook™ 13 Ultrabook
13.31.600.5611.287.0525601600226.98Apple Macbook 15.4 with Retina Display
141.780.5112.206.8632001800262.25HP TouchSmart 14 Ultrabook
8.91.330.647.125.3420481536287.64iPad 8.9" with Retina Display
71.600.565.943.7119201200323.45Amazon Kindle HDX 7"
8.91.780.517.764.3625601440330.02Amazon Kindle HDX 8.9"


So far, nothing can beat Amazon Kindle HDX, not HP not even Apple iPad with Retina display.  Because the price of a laptop is significantly higher with higher PPI, the affordable price of Kindle plus its highest PPI makes it the best gadget for eyes and pocket!

Saturday, October 12, 2013

Distance Measurement

Last week my order of ultrasonic ranging device arrived.  With excitement I connected it to my Pic18 protoboard.  With my existing code framework I added driver to access this thing and display it to LCD (as well as logging it via rs232 to laptop pc).

I took a short video of  the board with my new iPhone5s and edited it using iMovie which is now available for free on iTunes store.

Here is the link:




Sunday, September 1, 2013

XML-RPC Client/Server in Python

This demo shows how to have RPC connection in python.  The server collects CPU information (Linux).

Server-side:

 #!/usr/bin/python
import re
import os
import sys
import xmlrpclib

from SimpleXMLRPCServer import SimpleXMLRPCServer

def is_even(n):
    return n%2 == 0

def get_mhz():
    try:
        #return 0
        f = open("/proc/cpuinfo", 'r')
    except IOError:
        print "Unable to access /proc/cpuinfo"
        exit
    except:
        print "Other unhandled error (why?)"
      
    else:
        f.seek(0)
        line = f.readline()
        while line:
            line = line.strip()
            print "line = %s" % line
            m = re.match("cpu MHz[\t ]+: (.*)", line)
            if m:
                print m.group(1)
                f.close()
                return m.group(1)
            line = f.readline()
      
#    finally:
#        print "Sorry, still fails"


def xmlsrv_exit():
    print "trying to exit now..."
    try:
        print "try sys.exit(0)"
        #sys.exit(0)
    except:
        print "Unable to exit"
  
server = SimpleXMLRPCServer(("localhost", 8000))
print "Listening on port 8000..."
server.register_function(is_even, "xmlsrv_is_even")
server.register_function(get_mhz, "xmlsrv_get_mhz")
server.register_function(xmlsrv_exit, "xmlsrv_exit")
server.serve_forever()





Client side:

#!/usr/bin/python

import xmlrpclib

try:
    proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
    #print proxy.system.listMethods()
    print "3 is even: %s" % str(proxy.xmlsrv_is_even(3))
    print "100 is even: %s" % str(proxy.xmlsrv_is_even(100))

    print "CPU Clock: %s" % str(proxy.xmlsrv_get_mhz())

except xmlrpclib.Fault, err:
    print "A fault occurred"
    print "Fault code: %d" % err.faultCode
    print "Fault string: %s" % err.faultString
   
#proxy.xmlsrv_exit()


 

Multithreaded IGMP Query

Example how to access raw socket in Python:


#!/usr/bin/python

from socket import *
from struct import *
from time import *
import sys
import IN
import threading
import signal


src = '192.168.2.2'
dst = '224.0.0.1'
dev = "eth1.100" + "\0"

if len(sys.argv) > 1:
    dev = sys.argv[1]
    print "device = %s" % dev

src = gethostbyname(gethostname())
                  
def ichecksum(data, sum=0):
    """ Compute the Internet Checksum of the supplied data.  The checksum is
    initialized to zero.  Place the return value in the checksum field of a
    packet.  When the packet is received, check the checksum, by passing
    in the checksum field of the packet and the data.  If the result is zero,
    then the checksum has not detected an error.
    """
    # make 16 bit words out of every two adjacent 8 bit words in the packet
    # and add them up
    for i in range(0,len(data),2):
        if i + 1 >= len(data):
            sum += ord(data[i]) & 0xFF
        else:
            w = ((ord(data[i]) <> 16) > 0)
        sum = (sum & 0xFFFF) + (sum >> 16)

    # one's complement the result
    sum = ~sum

    return sum & 0xFFFF


def dump( data ):
    i = 0
    for x in data:
        if i == 4:
            print ''
            i = 0
        i += 1
        sys.stdout.write( ' %0.2x' % ord(x) )
    print ''


# ip header generation

def create_ip_hdr(id, type):
    ip_ihl = 5
    ip_ver = 4
    ip_tos = 0
    ip_tot_len = 0  # kernel will fill the correct total length
    ip_frag_off = 0
    ip_ttl = 255
    ip_proto = type #IPPROTO_IGMP
    ip_check = 0    # kernel will fill the correct checksum
    isrc = inet_aton( src )
    idst = inet_aton( dst )
    ip_ihl_ver = (ip_ver << 4) + ip_ihl
    router_alert = int( '1001010000000100', 2 ) << 16

    # the ! in the pack format string means network order
    ip_hdr = pack('!BBHHHBBH4s4sI',
        ip_ihl_ver, ip_tos, ip_tot_len, id, ip_frag_off, ip_ttl, ip_proto,
        ip_check,
        isrc, idst,
        router_alert)

    crc = pack( '!H', ichecksum( ip_hdr ) )
    ip_hdr = ip_hdr[:10] + crc + ip_hdr[12:]
    return ip_hdr


# IGMP header:
# type (octet), max resp time (octet), checksum (octet), group (4-octets)
IGMP_QUERY = 0x11
IGMP_REPORT = 0x16
IGMP_LEAVE = 0x17
igmp_type = IGMP_QUERY
IGMP_RESP_TIME = 120


def create_igmp_packet(id, type, group_addr='224.0.0.1'):
    igmp = pack( '!BBH4s', type, IGMP_RESP_TIME, 0, inet_aton(group_addr))
    crc = pack( '!H', ichecksum( igmp ) )
    igmp = igmp[0:2] + crc + igmp[4:]
    packet = create_ip_hdr(id, IPPROTO_IGMP) + igmp
    print 'packet:'
    dump( packet )
    return packet

def create_non_igmp_packet(id, type, group_addr='224.0.0.1'):
    igmp = pack( '!BBH4s', type, IGMP_RESP_TIME, 0, inet_aton(group_addr))
    crc = pack( '!H', ichecksum( igmp ) )
    igmp = igmp[0:2] + crc + igmp[4:]
    packet = create_ip_hdr(id, IPPROTO_UDP) + igmp
    print 'packet:'
    dump( packet )
    return packet


group = '224.0.0.1'
id = 1

s = socket( AF_INET, SOCK_RAW, IPPROTO_RAW )
s.setsockopt( IPPROTO_IP, IP_HDRINCL, 1 )
s.setsockopt( IPPROTO_IP, IP_MULTICAST_TTL, 2)
s.setsockopt( SOL_SOCKET, IN.SO_BINDTODEVICE, dev)

socksema = threading.Semaphore()
stop = False

def signal_handler(signal, frame):
    global stop
    print 'You pressed Ctrl+C!'
    stop = True
    #th1.join()
    #th2.join()
    #sys.exit(0)

class IgmpQueryThread(threading.Thread):
    def run(self):
        global stop,id
        while (not stop):
            socksema.acquire()
            print "Sending IGMP query"
            igmp_q = create_igmp_packet(id, IGMP_QUERY, group)
            print s.sendto( igmp_q, (dst, 0) )
            socksema.release()
            dump( igmp_q)
            id += 1
            sleep(1)


class IgmpReportThread(threading.Thread):       
    def run(self):
        global stop,id
        while (not stop):
            socksema.acquire()
            print "Sending IGMP report"
            igmp_r = create_igmp_packet(id, IGMP_REPORT, group)
            print s.sendto( igmp_r, (dst, 0) )
            id += 1
            socksema.release()
            sleep(1)


i = 0
th1 = IgmpQueryThread()
th2 = IgmpReportThread()

th1.start()
th2.start()

signal.signal(signal.SIGINT, signal_handler)
print 'Press Ctrl+C to quit'
#signal.pause()


while(not stop):
    if (i % 5 == 0):
        print "Sending NON-IGMP (%d)" % i
        false_igmp = create_non_igmp_packet(id, IGMP_QUERY, group)
        print s.sendto( false_igmp, (dst, 0) )
        #stop = True
        id += 1
    sleep( 1 )
    i += 1
   
th1.join()
th2.join()

s.close()




Sunday, July 7, 2013

Create Delay using Number of Cycles in PIC MCU

Most of the delay code available on the Internet for PIC is based on real time delay.  The problem with this approach is that it's hardcoded for certain clock frequency only.  When we use the code for different frequency clock, we have to change the code, sometimes drastically.

Another approach is just to make a routine to waste number of instruction cycles, regardless of the clock frequency.  The caller then later calculate how many cycles it needs to waste in order to get the wanted delay.  It's more maintainable this way than the former.  All PIC MCUs have each instruction executed in 4 clock frequency, or F_cy = F_clock/4, hence T_cy = 1/F_cy = 4/F_clock.

Here is the example of the code for PIC16F877A to waste 10 T_cy cycles.  If F_clock is 16 MHz, F_Cy = 4MHz and T_Cy = 0.25 uSec.  So 10*T_cy = 2.5 uSec delay.
I don't see any reason it won't be compiled and working on other pic16-based MCUs.  I compiled the code with gpasm and header file from sdcc.
 


    title "Delay 10 Tcy"

    include <p16f_common.inc>

    list n=0

    radix    dec
    global    _delay10tcy
    extern   _d1
 
; -----------------------------------------------------------------------
; Variables declaration
;DLY_VAR UDATA_SHR  0x190
;WREG         res 1
WREG        equ     _d1



code_delay10tcy code

_delay10tcy:
    ; polynomial for 10tcy delay is f(x) = 10 + 10 * (x-1)

    ; caller takes 2 TCy, return takes 2 Tcy, so we need 6 more Tcy here
      banksel   WREG            ; 2 Tcy
      decf      WREG,f          ; (x-1), 1 TCy.  TCy so far = 4 + 2 + 1 = 7

      movfw     WREG            ; 1, TCy so far = 8
      bz        @delay10_end    ; 2 Tcy if x=0, otherwise 1, TCy so far = 9 (if x>0)
      nop                       ; 1 TCy, TCy so far = 10

@delay10_loop:                  ; (x-1) * 10
      goto       $+1            ; 2 TCy, TCy so far = 2
      goto       $+1            ; 2 TCy, TCy so far = 4
      goto       $+1            ; 2 TCy, TCy so far = 6

      nop                       ; TCy so far 7
      decfsz    WREG, f         ; TCy so far 8 (if x>0), else 9
      goto       @delay10_loop  ; TCy so far 10
      nop                     

@delay10_end:

      return                    ; 2

      end



Save the code to a file name delay10tcy.S.

To compile it on Linux:

gpasm -c -M -m --mpasm-compatible -e ON -DSDCC -Dpic16f877a -p16f877a -I/usr/local/share/sdcc/include/pic14  delay10tcy.S

The variable "_d1" above has been defined elsewhere as 8-bit user data (so it's shareable among other delayxtcl routines), but if we want to make it local just declare is such as:

DELAY_VAR  udata_shr 0x190
d1  res 1

and remove underscore in all references to d1.

Wednesday, June 19, 2013

Parent-Child Relationship in OOP C++

The C++ source code below:


#include <cstdio>
#include <iostream>

using namespace std;

class CParent {
public:
 CParent() {
  ref++;
  cout <<  "class CParent: constructor ref=" << ref << endl;
  Function();
 };
 virtual ~CParent() {
  ref--;
  cout << "class CParent: destructor ref=" << ref << endl;
 }
 virtual int Function() {
  cout << "\tA::Function()" << endl;
  return ref;
 }
 static unsigned int ref;
};


class CChild : public CParent {
public:
 CChild() {
  ref++;
  cout << "\tclass CChild: constructor ref=" << ref << endl;
  m_a = new CParent();
 };
 virtual ~CChild() {
  ref--;
  cout << "\tclass CChild: destructor ref=" << ref << endl;
  delete m_a;
 }

 static unsigned int ref;
private:
 CParent *m_a;
};


unsigned int CParent::ref = 0;
unsigned int CChild::ref = 0;

int main()
{
 int i;
 int n = 2;

 CChild *c = new CChild[n];
 for(i=0; i(&c[i]);
  printf("p[%d].Function()=%d\n", i, p->Function());
 }
 cout << "CChild::Ref=" << CChild::ref << endl;
 delete [] c;
}