Monday, September 30, 2013

Booting BeagleBone Black from SD

http://embeddedcomputer.nl/lanotattachments/download/file/id/3/store/1/


Booting Ubuntu on BeagleBoard Black
http://circuitco.com/support/index.php?title=Booting_Ubuntu_on_BeagleBoard_Black


Linux on ARM / Home:
http://eewiki.net/display/linuxonarm/BeagleBone+Black

uEnv.txt based bootscript:

Beaglebone Black CircuitCo support page:
http://circuitco.com/support/index.php?title=BeagleBoneBlack

BeagleBone Boot Sequence.
http://elinux.org/EBC_Exercise_21a_Boot_Sequence#Booting_Up


Unbrick
http://hipstercircuits.com/unbrick-beaglebone-black-without-erasing-emmc/

Angstrom Cloud9 distribution download
http://downloads.angstrom-distribution.org/demo/beaglebone/

Burning an IMG File
http://doc.freenas.org/index.php/Burning_an_IMG_File

6+ hour:
Building Angstrom for Beaglebone from Source:
http://derekmolloy.ie/building-angstrom-for-beaglebone-from-source/


http://nomel.tumblr.com/post/30357133735/beaglebone-tutorial-how-to-compile-kernel-modules-and

Saturday, September 28, 2013

DIY Gas Turbine

http://www.gtba.co.uk/faq.htm

Create Partion and Filesystems

Divide and conquer your disk space
http://www.ibm.com/developerworks/library/l-lpic1-v3-104-1/


Friday, September 27, 2013

Beaglebone USB Ethernet Connection

http://robotic-controls.com/learn/beaglebone/beaglebone-internet-over-usb-only

http://shallowsky.com/blog/hardware/talking-to-beaglebone.html



On the beaglebone:

/sbin/route add default gw 192.168.7.1
echo "nameserver 8.8.8.8" >> /etc/resolv.conf
You'll probably want to add these lines to the end of /usr/bin/g-ether-load.sh on the BBB, so they'll be run automatically every time you boot. Then, back on your Linux host, do this:
sudo iptables -A POSTROUTING -t nat -j MASQUERADE
echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward > /dev/null
Now you should be able to ping, ssh or otherwise use the BBB to get anywhere on the net.
Once your network is running, you might want to run /usr/bin/ntpdate -b -s -u pool.ntp.org to set the time, since the BBB doesn't have a real-time clock (RTC).


Scripts for configuration after automatic connection

http://www.circuidipity.com/getting-started-with-beaglebone-black.html

Wednesday, September 25, 2013

RT-N16

http://www.dd-wrt.com/wiki/index.php/Asus_RT-N16

http://www.anandtech.com/show/6180/open-source-router-platforms

OpenWRT
http://wiki.openwrt.org/toh/asus/rt-n16#from.linux

Tuesday, September 24, 2013

interrupt, Callback, Software Debounce, RPi

raspi.tv/2013/how-to-use-interrupts-with-python-on-the-raspberry-pi-and-rpi-gpio-part-2

Friday, September 20, 2013

Why should you use strncpy instead of strcpy?

www.blogger.com/blogger.g?blogID=3857439785589817539#editor/target=post;postID=1092521179290748231

strncpy combats buffer overflow by requiring you to put a length in it. strcpy depends on a trailing \0, which may not always occur.
Secondly, why you chose to only copy 5 characters on 7 character string is beyond me, but it's producing expected behavior. It's only copying over the first n characters, where n is the third argument.
The n functions are all used as defensive coding against buffer overflows. Please use them in lieu of older functions, such as strcpy.
 
 
strncpy was initially introduced into the C library to deal with fixed-length name fields in structures such as directory entries
 
http://www.lysator.liu.se/c/rat/d11.html
 
memcpy
memmove
 
....
 
functions

chris & Sinan: It's getting upvotes because the question was, "Why would you use strncpy instead of strcpy?" Not, "What is strncpy for?" There's a distinct difference. This answer addresses the former, not the latter.
 
 
http://stackoverflow.com/questions/2593814/why-do-i-get-a-segmentation-fault-when-using-strncpy
 
The problem is that tp->mnem is pointing to a string literal, which is generally allocated in a read-only segment of memory. Therefore it's illegal to overwrite it. 

C dynamic memory allocation

statically, automatically dynamically

Static-duration variables are allocated in main memory, usually along with the executable code of the program, and persist for the lifetime of the program; automatic-duration variables are allocated on the stack and come and go as functions are called and return.

These limitations are avoided by using  dynamic memory allocation in which memory is more explicitly (but more flexibly) managed. Typically, by allocating it from heap

Type safety:

int *ptr;
ptr = malloc(10 * sizeof (*ptr));               /* without a cast */
ptr = (int *)malloc(10 * sizeof (*ptr));        /* with a cast */
ptr = reinterpret_cast<int *>(malloc(10 * sizeof (*ptr))); /* with a cast, for C++ */

Wednesday, September 18, 2013

Tuesday, September 17, 2013

Difference between .o and .ko file

http://stackoverflow.com/questions/10476990/difference-between-o-and-ko-file

The short answer is that the .ko file is your object file linked with some kernel automatically generated data structures that are needed by the kernel.
The .o file is the object file of your modules - the result of compiling your c files. The kernel build system then automatically creates another C file with some data structures describing the kernel module (named your_module_kmod.c), compile this C file into another object file and links your object file and the object file it built together to create the .ko file.
The dynamic linker in the kernel that is in charge of loading kernel modules, expects to find the data structure the kernel put in the kmod object in the .ko file and will not be able to load your kernel module without them

Sunday, September 15, 2013

Disabling the beaglebone black HDMI Cape

mount /dev/mmcblk0p1  /mnt/card

Edit the uEnv.txt on the mounted partition:
nano /mnt/card/uEnv.txt

To disable the HDMI Cape, change the contents of uEnv.txt to:
optargs=quiet capemgr.disable_partno=BB-BONELT-HDMI,BB-BONELT-HDMIN

Save the file:
Ctrl-X, Y

Unmount the partition:
umount /mnt/card

Reboot the board:
shutdown -r now

Wait about 10 seconds and reconnect to the BeagleBone Black through SSH. To see what capes are enabled:
cat /sys/devices/bone_capemgr.*/slots
 
 
 
 
 
 
 
 
Every line shows something like “P-O-L” or “P-O–”. The letter “L” means 
the Cape is enabled; no letter “L” means that it is disabled. You can 
see here that the HDMI Cape has been disabled, so pin 27 to 46 on header
 P8 are now available to use
 
http://www.logicsupply.com/blog/2013/07/18/disabling-the-beaglebone-black-hdmi-cape/ 

Sunday, September 8, 2013

Scope, lifetime and Visability in C

 http://www.linuxforu.com/2011/10/joy-of-programming-scope-lifetime-and-visibility-in-c/


There are five scopes in C: program, file, function, block, and prototype.


void foo() {}
// "foo" has program scope
static void bar() {
    // "bar" has file scope
    printf("hello world");
    int i;
    // "i" has block scope
}
void baz(int j);
// "j" has prototype scope
print:
// "print" has function scope

All non-static functions have program scope, and they can be called from anywhere in the program.

Of course, to make such a call, the function needs to be first declared using extern, before being called, but the point is that it is available throughout the program.

 There are three lifetimes in C: static, automatic and dynamic.

Summery of differences

As you can see, scope, lifetime and visibility are related to each other, but are distinct. Scope is about the ‘availability’ of the declared variable: within the same scope, it is not possible to declare/define two variables of the same type with the same name. Lifetime is about the duration in which the variable is ‘alive’: it determines how long the named or unnamed variable has memory allocated to it.
Visibility is about the ‘accessibility’ of the declared variables: it arises because of the possibility of variables in outer scope having the same name as the ones in inner scopes, resulting in ‘hiding’.

Function Pointers and Callback in C

http://www.linuxforu.com/2012/02/function-pointers-and-callbacks-in-c-an-odyssey/

http://www.learncpp.com/cpp-tutorial/78-function-pointers/

typedef....

Using name space and scope

http://stackoverflow.com/questions/223021/whats-the-scope-of-the-using-declaration-in-c

The scope of the using statement depends on where it is located in the code:
  • Placed at the top of a file, it has scope throughout that file.
  • If this is a header file, it will have scope in all files that include that header. In general, this is "not a good idea" as it can have unexpected side effects
  • Otherwise the using statement has scope within the block that contains it from the point it occurs to the end of the block. If it is placed within a method, it will have scope within that method. If it is placed within a class definition it will have scope within that class.

http://stackoverflow.com/questions/1677778/why-enclose-blocks-of-c-code-in-curly-braces

http://stackoverflow.com/questions/2759371/in-c-do-braces-act-as-a-stack-frame

void foo(int[]);
void bar(void);
void foobar(int); 

void foobar(int flag) {
    if (flag) {
        int big[100000000];
        foo(big);
    }
    bar();
}
gives:
_foobar:
    pushl   %ebp
    movl    %esp, %ebp
    movl    $400000008, %eax
    call    __alloca
    cmpl    $0, 8(%ebp)
    je      L2
    leal    -400000000(%ebp), %eax
    movl    %eax, (%esp)
    call    _foo
L2:
    call    _bar
    leave
    ret

Friday, August 23, 2013

sync folders over remote placeT

http://www.finiteloops.com/weblog/?p=111

rsync -avze ssh /localpath(source)/ user@remoteaddress:/remotepath/(destination)

Tuesday, August 20, 2013

Static Library .a and Dynamic Library .so

http://www.ilkda.com/compile/Static_Versus_Dynamic.htm


Creating .so and .a in Unix
http://stackoverflow.com/questions/1648215/creating-so-and-a-in-unix

Sunday, August 18, 2013

gcc warning: function used but not defined

static

internal linkage

http://stackoverflow.com/questions/5526461/gcc-warning-function-used-but-not-defined

warning: format not a string literal and no format arguments

This warning is gcc's way of telling you that it cannot verify the format string argument to the printf style function (printf, fprintf... etc). This warning is generated when the compiler can't manually peek into the string and ensure that everything will go as you intend during runtime. Lets look at a couple of examples.
Case 1. This string can be verified at compile time and the compiler will allow it without warning:
printf("This string has no format");
Case 2: For this case, the compiler can detect that you have a format specifier and will raise a different warning. On my machine it said "warning: too few arguments for format".
// This will most probably crash your machine
printf("Not a safe string to %s"); 
Case 3. Now this is somewhat your case. You are taking a string generated at runtime and trying to print it. The warning you are getting is the compiler warning you that there could be a format specifier in the string. Say for eg "bad%sdata". In this case, the runtime will try to access a non-existent argument to match the %s. Even worse, this could be a user trying to exploit your program (causing it to read data that is not safe to read).
char str[200];
scanf("%s", str)
printf(str)
 http://stackoverflow.com/questions/4419293/warning-format-not-a-string-literal-and-no-format-arguments

Friday, August 9, 2013

Anatomy of real-time Linux architecture

http://www.ibm.com/developerworks/library/l-real-time-linux/

An operating system that can support the desired deadlines of the real-time tasks (even under worst-case processing loads) is called a hard real-time system. But hard real-time support isn't necessary in all cases. If an operating system can support the deadlines on average, it's called a soft real-time system. Hard real-time systems are those in which missing a deadline can have a catastrophic result (such as deploying an airbag too late or allowing brake pressure to slip for too long). Soft real-time systems can miss deadlines without the overall system failing (such as losing a frame of video).
Although the thin kernel approach has its advantages (hard real-time support coexisting with a standard Linux kernel), the approach does have drawbacks. The real-time and non-real-time tasks are independent, which can make debugging more difficult. Also, non-real-time tasks do not have full Linux platform support (the thin kernel execution is called thin for a reason).
Examples of this approach include RTLinux (now proprietary and owned by Wind River Systems), Real-Time Application Interface (RTAI), and Xenomai.








The new configuration option CONFIG_PREEMPT changes this behavior of the kernel by allowing processes to be preempted if high-priority work is available to do (even if the process is in the middle of a system call).

Trade-off
Although the option enables soft real-time performance and even under load makes the operating system execute more smoothly,


it does so at a cost. That cost is slightly lower throughput and a small reduction in kernel performance because of the added overhead of the CONFIG_PREEMPT option. This option is useful for desktop and embedded systems, but it may not be right in all scenarios (for example, servers).

Kernel 2.6 for high resolution timers

1us resolution (if supported by underlying hardware)

Timer management (implemented with Red-black tree) for efficiency.

O(1) scheduler 

Preempt_RT Patch 

The PREEMPT_RT patch provides several modifications to yield hard real-time support. 

Reimplementing some of the kernel locking primitives to be fully preemptable,

Priority Inheritance

in kernel mutexes, and converting interrupt handlers into kernel threads so that they are fully preemptable

This article gave a brief overview of some of the techniques used to bring real-time computing to the Linux kernel. Numerous early attempts used a thin-kernel approach to segregate the real-time tasks from the standard kernel. Later, nano-kernel approaches came on the scene that appear very much like the hypervisors used in virtualization solutions today. Finally, the Linux kernel provides its own means for real time, both soft and hard.




Which operating system book do you recommend?

http://programmers.stackexchange.com/questions/7340/which-operating-system-book-do-you-recommend

Characteristics of a Good API

How to Design a Good API and Why it Matters
Joshua Bloch
Principal Software Engineer


Easy to learn
Easy to use, even without documentation
Hard to misuse
Easy to read and maintain code that uses it
Sufficiently powerful to satisfy requirements
Easy to extend
Appropriate to audience

 Your job is to extract true requirements  Should take the form of use-cases

USE-cases
Can be easier and more rewarding to build something more general


Start with Short Spec 1 page is Ideal

At this stage, agility trumps over completeness

Bounce spec off as many people as possible
_ Listen to their input and take it seriously

If you keep the spec short, it’s easy to modify

Flesh it out as you gain confidence
_ This necessarily involves coding

Write to Your API Early and Often

Start before you've implemented the API
_ Saves you doing implementation you'll throw away

Continue writing to API as you flesh it out
_ Prevents nasty surprises
_ Code lives on as examples, unit tests

Writing to SPI is Even More Important

Service Provider Interface (SPI)

 Plug-in interface enabling multiple implementations 

Write multiple plug-ins before release
_ If you write one, it probably won't support another
_ If you write two, it will support more with difficulty
_ If you write three, it will work fine

Maintain Realistic Expectations

Most API designs are over-constrained
_ You won't be able to please everyone
_ Aim to displease everyone equally

Expect to make mistakes
_ A few years of real-world use will flush them out
_ Expect to evolve API


API Should Do One Thing and Do it Well
• Functionality should be easy to explain
_ If it's hard to name, that's generally a bad sign
_ Good names drive development
_ Be amenable to splitting and merging modules


API Should Be As Small As Possible But
No Smaller

When in doubt leave it out
_ Functionality, classes, methods, parameters, etc.
_ You can always add, but you can never remove

Look for a good power-to-weight ratio

This maximizes information hiding
• Allows modules to be used, understood, built,
tested, and debugged independently

Documentation Matters

Document every class, interface, method,
constructor, parameter, and exception

Class: what an instance represents
_ Method: contract between method and its client
_ Preconditions, postconditions, side-effects
_ Parameter: indicate units, form, ownership


 Document state space very carefully

• Take advantage of API-friendly features
_ Generics, varargs, enums, default arguments
• Know and avoid API traps and pitfalls
_ Finalizers, public static final arrays


Subclass Only Where It Makes Sense

• Subclassing implies substitutability (Liskov)
_ Subclass only when is-a relationship exists
_ Otherwise, use composition

Provide Programmatic Access to All
Data Available in String Form

Use most specific possible input parameter type
_ Moves error from runtime to compile time

• Don't use string if a better type exists
_ Strings are cumbersome, error-prone, and slow
• Don't use floating point for monetary values
_ Binary floating point causes inexact results!
• Use double (64 bits) rather than float (32 bits)
_ Precision loss is real, performance loss negligible

Avoid Long Parameter Lists

Three or fewer parameters is ideal
_ More and users will have to refer to docs

Long lists of identically typed params harmful
_ Programmers transpose parameters by mistake
_ Programs still compile, run, but misbehave!

Two techniques for shortening parameter lists
_ Break up method
_ Create helper class to hold parameters

Avoid Return Values that Demand
Exceptional Processing

return zero-length array or empty collection, not null



Saturday, August 3, 2013

RTC real time clock and raspberry pi

http://en.wikipedia.org/wiki/Real-time_clock

Supercapacitor

Setup with raspberry pi
http://learn.adafruit.com/adding-a-real-time-clock-to-raspberry-pi/set-rtc-time

Scheduling Computing and Pipe/pipeline (Unix)

https://en.wikipedia.org/wiki/Scheduling_(computing)
Some scheduling disciplines

First in first out

Shortest Remaining time

Fixed priority pre-emptive scheduling

Round robin

Multilevel queue

Manual Scheduling

In real time environments, such as embedded systems for


the scheduler also must ensure that processes can meet deadlines; this is crucial for keeping the system stable

https://en.wikipedia.org/wiki/Pipeline_(Unix)

In most Unix-like systems, all processes of a pipeline are started at the same time, with their streams appropriately connected, and managed by the scheduler together with all other processes running on the machine. An important aspect of this, setting Unix pipes apart from other pipe implementations, is the concept of buffering: for example a sending program may produce 5000 bytes per second, and a receiving program may only be able to accept 100 bytes per second, but no data is lost. Instead, the output of the sending program is held in a queue. When the receiving program is ready to read data, the operating system sends its data from the queue, then removes that data from the queue. If the queue buffer fills up, the sending program is suspended (blocked) until the receiving program has had a chance to read some data and make room in the buffer. In Linux, the size of the buffer is 65536 bytes.

Friday, August 2, 2013

LearnCpp 8.7 — The hidden “this” pointer

http://www.learncpp.com/cpp-tutorial/87-the-hidden-this-pointer/

Most of the time, you never need to explicitly reference the “this” pointer. However, there are a few occasions where it can be useful:

1) If you have a constructor (or member function) that has a parameter of the same name as a member variable, you can disambiguate them by using “this”:
1
2
3
4
5
6
7
8
9
10
11
class Something
{
private:
    int nData;
 
public:
    Something(int nData)
    {
        this->nData = nData;
    }
};
Note that our constructor is taking a parameter of the same name as a member variable. In this case, “nData” refers to the parameter, and “this->nData” refers to the member variable. Although this is acceptable coding practice, we find using the “m_” prefix on all member variable names provides a better solution by preventing duplicate names altogether!

2) Occasionally it can be useful to have a function return the object it was working with. Returning *this will return a reference to the object that was implicitly passed to the function by C++.


One use for this feature is that it allows a series of functions to be “chained” together, so that the output of one function becomes the input of another function! The following is somewhat more advanced and can be considered optional material at this point.


class Calc
{
private:
    int m_nValue;
 
public:
    Calc() { m_nValue = 0; }
 
    Calc& Add(int nValue) { m_nValue += nValue; return *this; }
    Calc& Sub(int nValue) { m_nValue -= nValue; return *this; }
    Calc& Mult(int nValue) { m_nValue *= nValue; return *this; }
 
    int GetValue() { return m_nValue; }
};


Note that Add(), Sub() and Mult() are now returning *this, which is a reference to the class itself. Consequently, this allows us to do the following:
1
2
Calc cCalc;
cCalc.Add(5).Sub(3).Mult(4);
The important point to take away from this lesson is that the “this” pointer is a hidden parameter of any member function. Most of the time, you will not need to access it directly. It’s worth noting that “this” is a const pointer — you can change the value of the object it points to, but you can not make it point to something else!