on Embedded LInux

How to change ip address in linux

I wrote this draft quite ago . Just stumbled upon on it in the drafts section, may this would help someone

Change IP address

You can change ip address using ifconfig command itself. To set IP address 192.168.1.5, enter command:

# ifconfig eth0 192.168.1.5 netmask 255.255.255.0 up
# ifconfig eth0

To make permanent changes to IP address you need to edit configuration file according to your Linux distribution.

Here are some detailed posts:

 

MiFare Classic Detection on Android

Ever since Near Field Communication was embedded on mobile phones, loads of new ideas and business proposals made people very busy. So does the Android platform with its API’s supporting NFC. Nexus S looks like a state of the art – good starting point if one wants to get past the monotonic Nokia’s piece of the cake. I just want to share with you my experience on reading a MiFare Classic tag using the Nexus S..and the Android platform.

You need to have:

  • A MiFare Classic 1k Tag – ( hopefully you know the keys for its Blocks :=) )
  • Android SDK and IDE
  • NFC enabled Android  (Make sure if the Android version is 2.3.3 or above).

Some Basics about the card:

MiFare classic cards store data in its Sectors. In MiFare classic 1k card there are 16 of them. Each Sector contains 4 blocks. You can store 16 bytes in each block. Making about 1024 bytes of storage space..that explains the 1K part of the card. You can perform common tasks like reading, writing data on these blocks, authentification, navigating the card sectors by incrementing the blocks count. The first sector contains manufacturer’s details and a unique id for the card. This is a read only part.

Each sector on the Mifare card is secured by two 48-bit keys: A and B. The last block in the sector contains these keys, as well as a configuration that defines what each key can do with each block, i.e block 0 could be configured so that
key A could read and write, but if a reader authenticates with key B, the reader would only be able to read that block.

The rest of the memory storage can be read or written using keys A and B. Fresh, empty Mifare cards have all their sectors locked with a pair of default keys FFFFFFFFFFFF or 000000000000.

Default Keys from experiments

About the NFC part of Android

Since ever 2.3.3 Gingerbread – Android exposes an API to read a list of card technologies. To perform operations on a tag, there are three things to be noted.

  1.  The cards store data in a format,
  2.  Reading and Writing data is done using a protocol
  3.  Cards support a technology that defines what they are

hence reading and writing to these cards can be done only when the data is arranged in that format. MiFare 1K cards support the NDEF format. It also supports NFC – protocol on the communication level. Precisely – ISO 14443 – 3A specification in short NFCA and it uses the MiFare technology.

Now we need to let the Android know what kind of cards we would be using in our application. This is often defined in an XML file stored in the resource folder ( I have named the file – filter_nfc.xml and stored it in a folder named xml). This resource file contains for example,

android.nfc.tech.NfcA
 android.nfc.tech.MifareClassic

Here we have declared a tech-list. This list has to be used in the Manifest file. Imagine you would like to start an activity when a tag is touched. The Manifest file is the right place to let the launcher know what activity is to be called when a particular tag is touched.

In the Manifest file, you would have an element – activity. This would declare the name of the activity, a title for it and some metadata. Ideally you would let the system know that you want to start this activity when you touch a MiFare classic card. You can define you own filters for different activities for a variety of tag and protocol combinations.

You would then set the permissions on your Manifest file.

You can also do this in your onCreate method by using an NfcAdapter,

NfcAdapter mAdapter = NfcAdapter.getDefaultAdapter(this);

When a MiFare tag is discovered, the NFC stack would get the details of the tag and deliver it to a new Intent of this same activity. Hence to handle this, we would need an instance of the PendingIntent from the current activity.

PendingIntent mPendingIntent = PendingIntent.getActivity(this, 0,
 new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

Then we could set up our filter which defines the data format and technology type.

IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);try {
 ndef.addDataType("*/*");
 } catch (MalformedMimeTypeException e) {
 throw new RuntimeException("fail", e);
 }

 mFilters = new IntentFilter[] {
 ndef,
 };// Setup a tech list for all NfcF tags

 mTechLists = new String[][] { new String[] { MifareClassic.class.getName() } };Intent intent = getIntent();

Finally when the pending intent calls the activity again, we like to read the tag. I have put all the steps in the method resolveIntent which would do only the reading part of the tag.

resolveIntent(intent);

Reading the tag

The method looks like

… 

 

Android Image Loading Libraries

Asynchronous image loading

Consider a case where we are having 50 images and 50 titles and we try to load all the images/text into the listview, it won’t display anything until all the images get downloaded.

Here Asynchronous image loading process comes in picture. Asynchronous image loading is nothing but a loading process which happens in background so that it doesn’t block main UI thread and let user to play with other loaded data on the screen. Images will be getting displayed as and when it gets downloaded from background threads.

Asynchronous image loading libraries

  1. Nostra’s Universal Image loader – https://github.com/nostra13/Android-Universal-Image-Loader
  2. Picasso – http://square.github.io/picasso/
  3. UrlImageViewHelper by Koush
  4. Volley – By Android team members @ Google
  5. Novoda’s Image loader – https://github.com/novoda/ImageLoader

Let’s have a look at examples using Picasso and Universal Image loader libraries.

Example 1: Nostra’s Universal Image loader

Image loading using UniversalImageLoader

Step 1: Initialize ImageLoader configuration

public class MyApplication extends Application{
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
// Create global configuration and initialize ImageLoader with this configuration
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()).build();
ImageLoader.getInstance().init(config);
}
}

Step 2: Declare application class inside Application tag in AndroidManifest.xml file

<application android:name="MyApplication">

Step 3: Load image and display into ImageView

ImageLoader.getInstance().displayImage(objVideo.getThumb(), holder.imgVideo);

Now, Universal Image loader also provides a functionality to implement success/failure callback to check whether image loading is failed or successful.

ImageLoader.getInstance().displayImage(photoUrl, imgView,
new ImageLoadingListener() {
@Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
findViewById(R.id.EL3002).setVisibility(View.VISIBLE);
}
@Override
public void onLoadingFailed(String arg0, View arg1,
FailReason arg2) {
// TODO Auto-generated method stub
findViewById(R.id.EL3002).setVisibility(View.GONE);
}
@Override
public void onLoadingComplete(String arg0, View arg1,
Bitmap arg2) {
// TODO Auto-generated method stub
findViewById(R.id.EL3002).setVisibility(View.GONE);
}
@Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
findViewById(R.id.EL3002).setVisibility(View.GONE);
}
});

Example 2: Picasso

Image loading straight way:

Picasso.with(context).load("http://postimg.org/image/wjidfl5pd/").into(imageView);

Image re-sizing:

Picasso.with(context)
.load(imageUrl)
.resize(100, 100)
.centerCrop()
.into(imageView)

Example 3: UrlImageViewHelper library

UrlImageViewHelper by Koush

It’s an android library that sets an ImageView’s contents from a url, manages image downloading, caching, and makes your coffee too.

UrlImageViewHelper will automatically download and manage all the web images and ImageViews. Duplicate urls will not be loaded into memory twice. Bitmap memory is managed by using a weak reference hash table, so as soon as the image is no longer used by you, it will be garbage collected automatically.

Image loading straight way:

UrlImageViewHelper.setUrlDrawable(imgView, "http://yourwebsite.com/image.png");

Placeholder image when image is being downloaded:

UrlImageViewHelper.setUrlDrawable(imgView, "http://yourwebsite.com/image.png", R.drawable.loadingPlaceHolder);

Cache images for a minute only:

UrlImageViewHelper.setUrlDrawable(imgView, "http://yourwebsite.com/image.png", null, 60000);

Example 4: Volley library

Yes Volley is a library developed and being managed by some android team members at Google, it was announced by Ficus Kirkpatrick during the last I/O. I wrote an article about Volley library 10 months back :) , read it and give it a try if you haven’t used it yet.

Let’s look at an example of image loading using Volley.

Step 1: Take a NetworkImageView inside your xml layout.

<com.android.volley.toolbox.NetworkImageView
android:id="@+id/imgDemo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"/>

Step 2: Define a ImageCache class

Yes you are reading title perfectly, we have to define an ImageCache class for initializing ImageLoader object.

public class BitmapLruCache
extends LruCache<String, Bitmap>
implements ImageLoader.ImageCache {
public BitmapLruCache() {
this(getDefaultLruCacheSize());
}
public BitmapLruCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
@Override
public Bitmap getBitmap(String url) {
return get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
public static int getDefaultLruCacheSize() {
final int maxMemory =
(int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
}

Step 3: Create an ImageLoader object and load image
Create an ImageLoader object and initialize it with ImageCache object and RequestQueue object.

ImageLoader.ImageCache imageCache = new BitmapLruCache();
ImageLoader imageLoader = new ImageLoader(Volley.newRequestQueue(context), imageCache);

Step 4: Load an image into ImageView

NetworkImageView imgAvatar = (NetworkImageView) findViewById(R.id.imgDemo);
imageView.setImageUrl(url, imageLoader);

Which library to use?

Can you decide which library you would use? Let us know which and what are the reasons? :)

Selection of the library is always depends on the requirement. Let’s look at the few fact points about each library so that you would able to compare exactly and can take decision.

Picasso:

  • It’s just a one liner code to load image using Picasso.
  • No need to initialize ImageLoader and to prepare a singleton instance of image loader.
  • Picasso allows you to specify exact target image size. It’s useful when you have memory pressure or performance issues, you can trade off some image quality for speed.
  • Picasso doesn’t provide a way to prepare and store thumbnails of local images.
  • Sometimes you need to check image loading process is in which state, loading, finished execution, failed or cancelled image loading. Surprisingly It doesn’t provide a callback functionality to check any state. “fetch()” dose not pass back anything. “get()” is for synchronously read, and “load()” is for asynchronously draw a view.

Universal Image loader (UIL):

which was again probably a very first complete solution and also a most voted answer (for the image loading solution) on Stackoverflow.

  • UIL library is better in documentation and even there’s a demo example which highlights almost all the features.
  • UIL provides an easy way to download image.
  • UIL uses builders for customization. Almost everything can be configured.
  • UIL doesn’t not provide a way to specify image size directly you want to load into a view. It uses some rules based on the size of the view. Indirectly you can do it by mentioning ImageSize argument in the source code and bypass the view size checking. It’s not as flexible as Picasso.

Volley:

  • It’s officially by Android dev team, Google but still it’s not documented.
  • It’s just not an image loading library only but an asynchronous networking library
  • Developer has to define ImageCache class their self and has to initialize ImageLoader object with RequestQueue and ImageCache objects.

So now I am sure now you can be able to compare libraries. Choosing library is a bit difficult talk because it always depends on the requirement and type of projects. If the project is large then you should go for Picasso or Universal Image loader. If the project is small then you can consider to use Volley librar, because Volley isn’t an image loading library only but it tries to solve a more generic solution.).

I suggest you to start with Picasso. If you want more control and customization, go for UIL.

Read more:

  1. http://blog.bignerdranch.com/3177-solving-the-android-image-loading-problem-volley-vs-picasso/
  2. http://stackoverflow.com/questions/19995007/local-image-caching-solution-for-android-square-picasso-vs-universal-image-load
  3. https://plus.google.com/103583939320326217147/posts/bfAFC5YZ3mq

 

VIA http://www.technotalkative.com

 

convert a decimal value to its binary representation ( string )

Wanted to share this snippet of code which I used to display a decimal numbers binary representation. It is quite self explanatory and easy to understand.

/**
  * Turns a decimal value to its binary representation
  */
char* dec2binWzerofill(unsigned long Dec, unsigned int bitLength){
    return dec2binWcharfill(Dec, bitLength, '0');
}

char* dec2binWcharfill(unsigned long Dec, unsigned int bitLength, char fill){
  static char bin[64];
  unsigned int i=0;
unsigned int j;
  while (Dec > 0) {
    bin[32+i++] = ((Dec & 1) > 0) ? '1' : fill;
    Dec = Dec >> 1;
  }

  for ( j = 0; j< bitLength; j++) {
    if (j >= bitLength - i) {
      bin[j] = bin[ 31 + i - (j - (bitLength - i)) ];
    }else {
      bin[j] = fill;
    }
  }
  bin[bitLength] = '';

  return bin;
}
 

LPC810 Breakout Board

This basic Arm Cortex-M0+ NXP LPC810 breakout board features a FTDI programming header, USB (mini-B) connector for power only, a LM117-3.3v voltage regulator, power LED, ISP and Reset buttons and a standard 2×5-pin 0.05″ SWD debug connector. All pins are brought out to the edge of the board. Three PCBs from OSHPark.com cost me $6.55 […]

https://ucexperiment.wordpress.com/2015/02/22/lpc810-breakout-board/

 

Seven Ready-Made Raspberry Pi Projects You Can Install in a Few Clicks (Repost)

Anyone who has a Raspberry Pi knows how exciting it is to have this little computer in the palm of your hand. Now with the introduction of the latest model, and with it being more powerful and staying at the same old price, there is so much more you can do now. Looking for something […]

http://lifehacker.com/seven-ready-made-raspberry-pi-projects-you-can-install-1691368805

 

How to install Groovy on a Banana Pi or Raspberry Pi

The Raspberry or Banana Pi have already pre-installed Python. If you like to stay with Groovy on these nice little devices, here are the instructions to install Groovy. GVM makes the whole process very easy and convenient. Open a terminal window and use these commands: curl -s get.gvmtool.net > installGroovy.sh chmod u+x installGroovy.sh installGroovy.sh source […]

https://jolorenz.wordpress.com/2015/03/22/how-to-install-groovy-on-a-banana-pi-or-raspberry-pi/

 

Automated Plant Watering System Uses Car Parts

[Shane] recently built an automated plant watering system for his home. We’ve seen several similar projects before, but none of them worked quite like this one. Shane’s system is not hooked into the house plumbing and it doesn’t use any off-the-shelf electronic valves. Instead, [Shane’s] build revolves around a device that looks like it was intended […]

http://hackaday.com/2015/02/20/automated-plant-watering-system-uses-car-parts/

 

Analog pH Meter with PIC16F684 and arduino

Need to measure water quality and other parameters?  DF Robot’s Analog pH Meter Kit is  specially designed for simple interface and has convenient and practical connector and a bunch of features. Get pH measurements at ± 0.1pH (25 ℃). For most hobbyist this great accuracy range and it’s low cost makes this a great tool for biorobotics and other projects! It has an LED which works as the Power Indicator, a BNC connector and PH2.0 sensor interface. To use it, just connect the pH sensor with BND connector, and plug the PH2.0 interface into the analog input port of any micro-controller.

The Wiki page  has a sample code for using this kit with arduino,  along with schematic, specifications, features ,precautions and setup Instructions. The arduino Interfacing is simple and the schematic and code is available on the wiki page.

PH_meter_connection1_(1)

Interfacing with a pic is also straight forward, Shawon Shahryiar shared his project where he used a PIC16F684. Below is the demonstration video and code.

/*
Coder: Shawon Shahryiar
https://www.facebook.com/groups/ArduinoBangla/
https://www.facebook.com/groups/microarena/
https://www.facebook.com/MicroArena
 */


#include <16F684.h>

#device *= 16
#device ADC = 10

#fuses NOWDT, INTRC_IO, PROTECT, PUT, CPD
#fuses NOBROWNOUT, NOMCLR, NOIESO, FCMEN

#use delay (internal = 4MHz)


#include "lcd.c"


#define const_A 0.00171016
#define LED	pin_C3


const unsigned char symbol[16] ={
    0x00, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x00, 0x00,
    0x00, 0x00, 0x0E, 0x0E, 0x0E, 0x00, 0x00, 0x00
};


void setup();
void lcd_symbol();
unsigned long adc_avg();
void show_bar(unsigned char value);

void main() {
    unsigned char samples_A = 0x00;
    unsigned char samples_B = 0x00;
    unsigned long temp = 0x0000;
    unsigned long avg = 0x0000;
    unsigned long buffer[10];
    float pH_value = 0.0;

    memset(buffer, 0x00, sizeof (buffer));

    setup();

    while (TRUE) {
        for (samples_A = 0; samples_A < 10; samples_A++) {
            buffer[samples_A] = adc_avg();
            delay_ms(9);
        }

        for (samples_A = 0; samples_A < 9; samples_A++) {
            for (samples_B = (1 + samples_A); samples_B < 10; samples_B++) {
                if (buffer[samples_A] > buffer[samples_B]) {
                    temp = buffer[samples_A];
                    buffer[samples_A] = buffer[samples_B];
                    buffer[samples_B] = temp;
                }
            }
        }

        avg = 0;

        for (samples_A = 3; samples_A < = 6; samples_A++) {
            avg += buffer[samples_A];
        }

        avg >>= 2;

        pH_value = (avg * const_A);

        lcd_gotoxy(1, 1);
        printf(lcd_putc, "pH Value: %2.2g ", pH_value);
        show_bar(((unsigned char) pH_value));
    };
}

void setup() {
    disable_interrupts(GLOBAL);
    setup_WDT(WDT_off);
    setup_oscillator(OSC_4MHz);
    setup_comparator(NC_NC_NC_NC);
    setup_ADC(ADC_clock_div_8);
    setup_ADC_ports(sAN0);
    set_ADC_channel(0);
    setup_CCP1(CCP_off);
    setup_timer_0(T0_internal);
    setup_timer_1(T1_disabled);
    setup_timer_2(T2_disabled, 255, 1);
    set_timer0(0x00);
    set_timer1(0x0000);
    set_timer2(0x00);
    lcd_init();
    lcd_symbol();
    delay_ms(4000);
}

void lcd_symbol() {
    unsigned char s = 0;

    lcd_send_byte(0, 0x40);

    for (s = 0x00; s < = 0x0F; s++) {
        lcd_send_byte(1, symbol[s]);
    }

    lcd_send_byte(0, 0x80);
}

unsigned long adc_avg() {
    unsigned char samples = 4;
    unsigned long avg = 0;

    while (samples > 0) {
        read_adc(adc_start_only);
        while (!adc_done());
        avg += read_adc(adc_read_only);
        samples--;
    }
    avg /= 4.0;

    return avg;
}

void show_bar(unsigned char value) {
    unsigned char x_pos = 0;

    for (x_pos = 1; x_pos < = 16; x_pos++) {
        lcd_gotoxy(x_pos, 2);
        lcd_putc(0);
    }

    lcd_gotoxy((value + 1), 2);
    lcd_putc(1);

    output_toggle(LED);
    delay_ms(100);
}