on Coding, Microcontrollers

easyavr.h Header file for pin/port operations

Here I am sharing a header file called easyavr.h. This is a pretty basic header file with some helper functions related to input output pins of AVR

#ifndef __EASYAVR_H_
#define __EASYAVR_H_


//  Sets pin of port to 1
//
//  Example for PD2: PIN_ON(PORTD, 2)
#define PIN_ON(port,pin) ((port) |= (1 << (pin)))


//  Sets pin of port to 0
//
//  Example for PD2: PIN_OFF(PORTD, 2)
#define PIN_OFF(port,pin) ((port) &= ~(1 << (pin)))


//  Sets pin of port to value
//
//  Example for PD2: PIN_SET(PORTD, 2, 1)
#define PIN_SET(port,pin,val) (((val) > 0) ? PIN_ON((port),(pin)) : PIN_OFF((port),(pin)))

//  Sets all of port pins to OUTPUT mode
//
//  Example for PORTD: PORT_AS_OUTPUT(PORTD)
#define PORT_AS_OUTPUT(port) ((port) = 0xFF)

//  Sets all of port pins to INPUT mode
//
//  Example for PORTD: PORT_AS_INPUT(PORTD)
#define PORT_AS_INPUT(port) ((port) = 0x00)

//  Sets pin of port to OUTPUT mode
//
//  Example for PD1: PORT_AS_OUTPUT(DDRD, 1)
#define PIN_AS_OUTPUT(ddr,pin) ((ddr) |= (1 << (pin)))


//  Sets pin of port to INPUT mode
//
//  Example for PD1: PORT_AS_INPUT(DDRD, 1)
#define PIN_AS_INPUT(ddr,pin) ((ddr) &= ~(1 << (pin)))

//  Checks pin's value of port
//  Returns 1 or 0
//
//  Example for PD2: CHECK_PIN(PIND, 2)
#define CHECK_PIN(pinreg,pin) (((pinreg) & (1 << (pin))) != 0)


#endif
 

validating a base64 encoded string using regular expression

We can validate a base64 encoded string using a nice regex (regular expression). The following regex can be used with any programming language. I would use php for the example. The regex is as follows.

^[a-zA-Z0-9/+]*={0,2}$

Which will also detect the usage of = or == at the end of the string (and only end).

A function geared specifically toward this:

<?phpfunction is_base64_encoded()
 {
     if (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $data)) {
           return TRUE;
      } 
     else {
             return FALSE;
       }
 };
 is_base64_encoded("iash21iawhdj98UH3"); // true
 is_base64_encoded("#iu3498r"); // false
 is_base64_encoded("asiudfh9w=8uihf"); // false
 is_base64_encoded("a398UIhnj43f/1!+sadfh3w84hduihhjw=="); // false
?>
 

Android snippet: validate a hex number input

This is how you can validate a hex input in android code. The regex it makes use of can be used in other languages as well.

Validation steps are :

  • check if the input is not null or zero length
  • check if the input has even numbers as hex numbers are always even
  • match the input with the validating regex.
public boolean validHexInput(String str) {

   if (str == null || str.length() == 0) {
      return false;
   }

   // length should be even number 
   // otherwise its not a valid hex 
   if (str.length() % 2 == 0) {
      String var1 = "(?i)[0-9a-f]+";
      return str.matches(var1);
 }

 return false;
}

 

Getting power and battery info from AXP209

Here is a script that gives some info about battery (when one is plugged)

I think that this page has mistakes (http://linux-sunxi.org/AXP209#Spec_Sheets) because discharging and charging current are inverted.

#!/bin/sh
# This program gets the battery info from PMU
# Voltage and current charging/discharging
#
# Nota : temperature can be more than real because of self heating
#######################################################################
# Copyright (c) 2014 by RzBo, Bellesserre, France
#
# Permission is granted to use the source code within this
# file in whole or in part for any use, personal or commercial,
# without restriction or limitation.
#
# No warranties, either explicit or implied, are made as to the
# suitability of this code for any purpose. Use at your own risk.
#######################################################################

# force ADC enable for battery voltage and current
i2cset -y -f 0 0x34 0x82 0xC3

################################
#read Power status register @00h
POWER_STATUS=$(i2cget -y -f 0 0x34 0x00)
#echo $POWER_STATUS

BAT_STATUS=$(($(($POWER_STATUS&0x02))/2))  # divide by 2 is like shifting rigth 1 times
#echo $(($POWER_STATUS&0x02))
echo "BAT_STATUS="$BAT_STATUS
# echo $BAT_STATUS

################################
#read Power OPERATING MODE register @01h
POWER_OP_MODE=$(i2cget -y -f 0 0x34 0x01)
#echo $POWER_OP_MODE

CHARG_IND=$(($(($POWER_OP_MODE&0x40))/64))  # divide by 64 is like shifting rigth 6 times
#echo $(($POWER_OP_MODE&0x40))
echo "CHARG_IND="$CHARG_IND
# echo $CHARG_IND

BAT_EXIST=$(($(($POWER_OP_MODE&0x20))/32))  # divide by 32 is like shifting rigth 5 times
#echo $(($POWER_OP_MODE&0x20))
echo "BAT_EXIST="$BAT_EXIST
# echo $BAT_EXIST

################################
#read Charge control register @33h
CHARGE_CTL=$(i2cget -y -f 0 0x34 0x33)
echo "CHARGE_CTL="$CHARGE_CTL
# echo $CHARGE_CTL


################################
#read Charge control register @34h
CHARGE_CTL2=$(i2cget -y -f 0 0x34 0x34)
echo "CHARGE_CTL2="$CHARGE_CTL2
# echo $CHARGE_CTL2


################################
#read battery voltage	79h, 78h	0 mV -> 000h,	1.1 mV/bit	FFFh -> 4.5045 V
BAT_VOLT_LSB=$(i2cget -y -f 0 0x34 0x79)
BAT_VOLT_MSB=$(i2cget -y -f 0 0x34 0x78)

#echo $BAT_VOLT_MSB $BAT_VOLT_LSB

BAT_BIN=$(( $(($BAT_VOLT_MSB << 4)) | $(($(($BAT_VOLT_LSB & 0xF0)) >> 4)) ))

BAT_VOLT=$(echo "($BAT_BIN*1.1)"|bc)
echo "Battery voltage = "$BAT_VOLT"mV"

###################
#read Battery Discharge Current	7Ah, 7Bh	0 mV -> 000h,	0.5 mA/bit	FFFh -> 4.095 V
BAT_IDISCHG_LSB=$(i2cget -y -f 0 0x34 0x7B)
BAT_IDISCHG_MSB=$(i2cget -y -f 0 0x34 0x7A)

#echo $BAT_IDISCHG_MSB $BAT_IDISCHG_LSB

BAT_IDISCHG_BIN=$(( $(($BAT_IDISCHG_MSB << 4)) | $(($(($BAT_IDISCHG_LSB & 0xF0)) >> 4)) ))

BAT_IDISCHG=$(echo "($BAT_IDISCHG_BIN*0.5)"|bc)
echo "Battery discharge current = "$BAT_IDISCHG"mA"

###################
#read Battery Charge Current	7Ch, 7Dh	0 mV -> 000h,	0.5 mA/bit	FFFh -> 4.095 V
BAT_ICHG_LSB=$(i2cget -y -f 0 0x34 0x7D)
BAT_ICHG_MSB=$(i2cget -y -f 0 0x34 0x7C)

#echo $BAT_ICHG_MSB $BAT_ICHG_LSB

BAT_ICHG_BIN=$(( $(($BAT_ICHG_MSB << 4)) | $(($(($BAT_ICHG_LSB & 0xF0)) >> 4)) ))

BAT_ICHG=$(echo "($BAT_ICHG_BIN*0.5)"|bc)
echo "Battery charge current = "$BAT_ICHG"mA"

this script gives the AC power status :

#!/bin/sh
# This program gets the power status (AC IN or BAT) for pcDuino3
# I2C interface with AXP209
#
#######################################################################
# Copyright (c) 2014 by RzBo, Bellesserre, France
#
# Permission is granted to use the source code within this
# file in whole or in part for any use, personal or commercial,
# without restriction or limitation.
#
# No warranties, either explicit or implied, are made as to the
# suitability of this code for any purpose. Use at your own risk.
#######################################################################

#read Power status register @00h
POWER_STATUS=$(i2cget -y -f 0 0x34 0x00)
#echo $POWER_STATUS

# bit 7 : Indicates ACIN presence 0: ACIN does not exist; 1: ACIN present
#echo "bit 7 : Indicates ACIN presence 0: ACIN does not exist; 1: ACIN present"
#echo "bit 2 : Indicates that the battery current direction 0: battery discharge; 1: The battery is charged"

AC_STATUS=$(($(($POWER_STATUS&0x80))/128))  # divide by 128 is like shifting rigth 8 times
#echo $(($POWER_STATUS&0x80))
echo "AC_STATUS="$AC_STATUS
# echo $AC_STATUS

Example :

battery charging

rzbo@ubuntu:~$ ./battery_info.sh
BAT_STATUS=0
CHARG_IND=1
BAT_EXIST=1
CHARGE_CTL=0xd0
CHARGE_CTL2=0x47
Battery voltage = 3895.1mV
Battery discharge current = 304.0mA
Battery charge current = 0mA

rzbo@ubuntu:~$ ./power_status.sh
AC_STATUS=1

Battery discharging (USB power unplugged)

rzbo@ubuntu:~$ ./battery_info.sh
BAT_STATUS=0
CHARG_IND=0
BAT_EXIST=1
CHARGE_CTL=0xd0
CHARGE_CTL2=0x47
Battery voltage = 3678.4mV
Battery discharge current = 0mA
Battery charge current = 176.0mA

rzbo@ubuntu:~$ ./power_status.sh
AC_STATUS=0

IMG_20140916_183651 IMG_20140916_183625

 

Android: Call to getLayoutInflater() outside activity

Some times we need the inflater outside activities in android . To get access to the inflator we may use the following code snippet. You can use this outside activities – all you need is to provide a Context:

LayoutInflater inflater = LayoutInflater.from(context);

the from function also checks with assert that you actually get an inflater back and throws an error otherwise – which will be much easier to deal with then a null pointer exception somewhere in the code.

An Alternate way is shown below but I recommend to use the above one:

LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

Then to retrieve your different widgets, you inflate a layout:

View view = inflater.inflate( R.layout.myNewInflatedLayout, null );
Button myButton = (Button) view.findViewById( R.id.myButton );
 

Android: Updating the text of Toast message instantly

In my app,I wanted to show the number of taps to be made to accomplish a task, for this purpose i used Toast class , I used Toast.makeText to show the text. problem is that I couldn’t change the text or make it hide quickly if new text was to be shown. Android would queue all the makeText requests.

I wanted to have a solution to be able to change the text or be able to cancel the previous toast without waiting for it to finish. While Looking for solution I found this class called Boast by a StackOverFlow user Richard Le Mesurier. The Boast class accomplishes exactly what I needed.

The trick is to keep track of the last Toast that was shown, and to cancel that one.

What Richard Le Mesurier have done is to create a Toast wrapper, that contains a static reference to the last Toast displayed.

When I need to show a new one, I first cancel the static reference, before showing the new one (and saving it in the static).

Here’s full code of the Boast wrapper Richard Le Mesurier made – it mimics enough of the Toast methods for me to use it.

By default the Boast will cancel the previous one, so you don’t build up a queue of Toasts waiting to be displayed.

This should be a direct drop-in replacement for Toast in most use cases. for example

 mBoast.makeText(this,"your text",Duration).show();
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.widget.Toast;

/**
 * {@link Toast} decorator allowing for easy cancellation of notifications. Use
 * this class if you want subsequent Toast notifications to overwrite current
 * ones. </p>
 *
 * By default, a current {@link Boast} notification will be cancelled by a
 * subsequent notification. This default behaviour can be changed by calling
 * certain methods like {@link #show(boolean)}.
 */
public class Boast
{
    /**
     * Keeps track of certain {@link Boast} notifications that may need to be cancelled.
     * This functionality is only offered by some of the methods in this class.
     */
    private volatile static Boast globalBoast = null;

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Internal reference to the {@link Toast} object that will be displayed.
     */
    private Toast internalToast;

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Private constructor creates a new {@link Boast} from a given
     * {@link Toast}.
     *
     * @throws NullPointerException
     *         if the parameter is <code>null</code>.
     */
    private Boast(Toast toast)
    {
        // null check
        if (toast == null)
        {
            throw new NullPointerException(
                    "Boast.Boast(Toast) requires a non-null parameter.");
        }

        internalToast = toast;
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Make a standard {@link Boast} that just contains a text view.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param text
     *        The text to show. Can be formatted text.
     * @param duration
     *        How long to display the message. Either {@link #LENGTH_SHORT} or
     *        {@link #LENGTH_LONG}
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, CharSequence text,
                                 int duration)
    {
        return new Boast(Toast.makeText(context, text, duration));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view with the
     * text from a resource.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param resId
     *        The resource id of the string resource to use. Can be formatted
     *        text.
     * @param duration
     *        How long to display the message. Either {@link #LENGTH_SHORT} or
     *        {@link #LENGTH_LONG}
     *
     * @throws Resources.NotFoundException
     *         if the resource can't be found.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, int resId, int duration)
            throws Resources.NotFoundException
    {
        return new Boast(Toast.makeText(context, resId, duration));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view. Duration
     * defaults to {@link #LENGTH_SHORT}.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param text
     *        The text to show. Can be formatted text.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, CharSequence text)
    {
        return new Boast(Toast.makeText(context, text, Toast.LENGTH_SHORT));
    }

    /**
     * Make a standard {@link Boast} that just contains a text view with the
     * text from a resource. Duration defaults to {@link #LENGTH_SHORT}.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param resId
     *        The resource id of the string resource to use. Can be formatted
     *        text.
     *
     * @throws Resources.NotFoundException
     *         if the resource can't be found.
     */
    @SuppressLint("ShowToast")
    public static Boast makeText(Context context, int resId)
            throws Resources.NotFoundException
    {
        return new Boast(Toast.makeText(context, resId, Toast.LENGTH_SHORT));
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Show a standard {@link Boast} that just contains a text view.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param text
     *        The text to show. Can be formatted text.
     * @param duration
     *        How long to display the message. Either {@link #LENGTH_SHORT} or
     *        {@link #LENGTH_LONG}
     */
    public static void showText(Context context, CharSequence text, int duration)
    {
        Boast.makeText(context, text, duration).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view with the
     * text from a resource.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param resId
     *        The resource id of the string resource to use. Can be formatted
     *        text.
     * @param duration
     *        How long to display the message. Either {@link #LENGTH_SHORT} or
     *        {@link #LENGTH_LONG}
     *
     * @throws Resources.NotFoundException
     *         if the resource can't be found.
     */
    public static void showText(Context context, int resId, int duration)
            throws Resources.NotFoundException
    {
        Boast.makeText(context, resId, duration).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view. Duration
     * defaults to {@link #LENGTH_SHORT}.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param text
     *        The text to show. Can be formatted text.
     */
    public static void showText(Context context, CharSequence text)
    {
        Boast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * Show a standard {@link Boast} that just contains a text view with the
     * text from a resource. Duration defaults to {@link #LENGTH_SHORT}.
     *
     * @param context
     *        The context to use. Usually your {@link android.app.Application}
     *        or {@link android.app.Activity} object.
     * @param resId
     *        The resource id of the string resource to use. Can be formatted
     *        text.
     *
     * @throws Resources.NotFoundException
     *         if the resource can't be found.
     */
    public static void showText(Context context, int resId)
            throws Resources.NotFoundException
    {
        Boast.makeText(context, resId, Toast.LENGTH_SHORT).show();
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Close the view if it's showing, or don't show it if it isn't showing yet.
     * You do not normally have to call this. Normally view will disappear on
     * its own after the appropriate duration.
     */
    public void cancel()
    {
        internalToast.cancel();
    }

    /**
     * Show the view for the specified duration. By default, this method cancels
     * any current notification to immediately display the new one. For
     * conventional {@link Toast#show()} queueing behaviour, use method
     * {@link #show(boolean)}.
     *
     * @see #show(boolean)
     */
    public void show()
    {
        show(true);
    }

    /**
     * Show the view for the specified duration. This method can be used to
     * cancel the current notification, or to queue up notifications.
     *
     * @param cancelCurrent
     *        <code>true</code> to cancel any current notification and replace
     *        it with this new one
     *
     * @see #show()
     */
    public void show(boolean cancelCurrent)
    {
        // cancel current
        if (cancelCurrent && (globalBoast != null))
        {
            globalBoast.cancel();
        }

        // save an instance of this current notification
        globalBoast = this;

        internalToast.show();
    }

}
 

How to Turn a Raspberry Pi into NVR or DVR With Motion

Raspberry Pi is a low-cost micro-computer that is able to run Linux and has endless extension possibilities then can be also used for network video recorder (NVR) is a software program that records video in a digital format to a disk driveUSB flash drive, SD memory card or other mass storage device.

This post will guide you through the process of setting up your Raspberry Pi as a Network video recorder (NVR)

Requirements

You are going to need the following:

  • A Raspberry Pi
  • An Internet connection
  • An SD Card flashed with Raspbian OS (> 8 Gb)
  • IP or Analog camera with mjpeg streaming support or USB Camera (If you want record from Raspberry’s camera module, Please visit “Raspberry Pi as low-cost HD surveillance camera“)

Continue Reading …

 

NEED TIMING DIAGRAMS? TRY WAVEDROM

When working with anything digital, you’re going to end up reading or writing a timing diagram before long. For us, that’s meant keeping (text) notes, drawing something on a napkin, or using a tool like Inkscape. None of these are ideal.

An afternoon’s search for a better tool ended up with Wavedrom.

Just so you know where we’re coming from, here’s our list of desiderata for a timing diagram drawing solution:

  • Diagrams have a text-based representation, so their generation can be easily scripted and the results versioned and tracked throughout project development
  • Command-line rendering of images, because we like to automate everything
  • Looks good
  • Simple to use for common cases, but flexible enough to do some strange stuff when needed
  • Output modifiable when absolutely necessary: SVG would be nice

Basically, what we want is graphviz for timing diagrams.

Wavedrom nails four out of these five at the moment, and has promise to cover all of the bases. Give the online editor demo a try. We found it intuitive enough that we could make simple diagrams without even reading the fine manual. The tutorial has got you covered for more esoteric use cases.

foo

Clearly, some good thought has been put into the waveform description language, WaveJSON; it’s mostly readable and makes the essentials quick and easy. Because you can also enter straight SVG, it leaves the door open for full-fledged lunacy.

Wavedrom is written in JavaScript, and built for embedding in webpages; that’s the way they intend us to use it. On the other hand, if you want to run your own local version of the online editor, you can download it and install it locally if you’d like.

Our only quibble is that the standalone, command-line application wouldn’t generate images without the GUI on our Arch system. (Looks like there are some Google Chrome dependencies?) Otherwise, we think we’ve found our solution.

There are other applications out there. Drawtiming looks good, but we can’t quite get our head around the file format and the graphic output isn’t as flexible as we’d like: it only outputs GIF and we’re more into SVG because it can be edited easily after the fact.

There are font-based solutions that let you “type” the timing diagrams. We found Xwave and “Timing Diagram Font“. These work but aren’t particularly flexible; if you want something to happen at odd times, you’re out of luck. Plus, it just feels like a dirty hack, as if that were a bad thing.

Latex users can use tikz-timing, which makes sketching out your timing diagrams as much fun as laying out a very complex table in Latex (that is: not fun at all). On the other hand, it looks good, is ultimately flexible, outputs PDF, and would be scriptable if someone put the time in to write a nice frontend.

So for the next little while, we’re trying out Wavedrom.

What do you use for making timing diagrams?

VIA: HACKADAY

 

Chocometer :an open source near infrared sensor aiming glucose measurements without pain.

marcelclaro’s project for The Hackaday Prize aims to do just that. Instead of measuring blood directly, his project will measure blood glucose by shining light through a finger or an earlobe. Using light to detect blood glucose is something that has been studied in the lab, but so far, there aren’t any products on the market that use this technique.

There are two major problems marcel needs to overcome to turn this project into reality. The first is simply raw data for calibration. For [marcel], this is easy; he has Type 1 diabetes, and takes four glucose measurements a day. Patient heal thyself, or something.

The second problem is getting a photosensor that’s sensitive enough. By using an InGaAs PIN diode, a current-controlled oscillator, and a digital counter, [marcel] should have a sensor that’s good enough, with electronics that are cheap enough, to create some tech that is truly game changing for a few hundred million people around the world.

 

Simulating Arduino in Proteus VSM

 This is an old post which I am reposting… also check Simulating Arduino Mega2560 in Proteus.

Arduino platform is a great tool for everyone who wants to play with microcontrollers in a simple and inexpensive way. It offers perhaps the quickest and easiest ways to do cool stuffs with its rich built-in library and easy to grasp interface. It’s also open-source and for this reason there are many open-source projects with it in the Internet. I have personally enjoyed it a lot. Although Arduino is pretty popular amongst many users, there is no good simulator software for it. Proteus VSM, on the other hand, is a very good circuit simulator software. However it lacks a model or simulator primitive for Arduino. Thus simulating Arduino in Proteus is in a way impossible. If these powerful tools can be synced together then a lot of new possibilities will arise. This is what I wondered from day one of Arduinoing. In this doc we will discuss how to integrate these software and simulate Arduino in Proteus.In Proteus we need to add a .hex or .coff file in a micro in order to simulate its behaviour. However Arduino works with .ino or .pde files and the folders that hold Arduino sketches don’t contain .hex or .coff files. Thus there’s no straight way. Now if there’s no straight path then we have to go around.Firstly we have to make a suitable Proteus schematic like the one shown. You can also download a template provided at the end of post.

405495_1826120830872_733664937_nOnce the schematic is completed, we have to set the fuses and clock frequency as shown

429053_1826118790821_849601661_n

…