• Measuring Voltage with an Arduino

    It turns out the Arduino 168 and 328 can measure their own voltage rail.


    Copy, paste into Arduino and see what it returns. This works on an Arduino 168 or 328.

    long readVcc(){
      long result;
      // Read 1.1V reference against AVcc
      ADMUX = _BV(REFS0)| _BV(MUX3)| _BV(MUX2)| _BV(MUX1);
      delay(2);// Wait for Vref to settle
      ADCSRA |= _BV(ADSC);// Convert
      result = ADCL;
      result |= ADCH<<8;
      result =1126400L/ result;// Back-calculate AVcc in mV
      return result;
    void setup(){
    void loop(){
      Serial.println( readVcc(), DEC );

    The voltage is returned in millivolts. So 5000 is 5V, 3300 is 3.3V.

    Note the following:

    • This works on Arduinos with a 328 or 168 only. It looks like the same trick might be possible on the Arduino Mega – experiments are ongoing, and will be reported here.

    How it works

    The Arduino 328 and 168 have a built in precision voltage reference of 1.1V. This is used sometimes for precision measurement, although for Arduino it usually makes more sense to measure against Vcc, the positive power rail.

    The chip has an internal switch that selects which pin the analogue to digital converter reads. That switch has a few leftover connections, so the chip designers wired them up to useful signals. One of those signals is that 1.1V reference.

    So if you measure how large the known 1.1V reference is in comparison to Vcc, you can back-calculate what Vcc is with a little algebra. That is how this works.

  • Setting Up Cacti on Redhat/CentOS/Fedora

    Cacti is a network graphing tool similar to MRTG. How do I install and configure common options to collect SNMP data and various other data (such as system load, network link status, hard disk space, logged in users etc) into an RRD?

    From the official project site:

    Tutorial details
    Difficulty Easy (rss)
    Root privileges Yes
    Requirements None
    Estimated completion time 20m

    Cacti is a complete frontend to RRDTool, it stores all of the necessary information to create graphs and populate them with data in a MySQL database. The frontend is completely PHP driven. Along with being able to maintain Graphs, Data Sources, and Round Robin Archives in a database, cacti handles the data gathering. There is also SNMP support for those used to creating traffic graphs with MRTG.

    Required software(s)

    You need to install the following software on RHEL / Fedora / CentOS Linux:

    1. MySQL Server : Store cacti data.
    2. NET-SNMP server – SNMP (Simple Network Management Protocol) is a protocol used for network management.
    3. PHP with net-snmp module – Access SNMP data using PHP.
    4. Apache / lighttpd / ngnix webserver : Web server to display graphs created with PHP and RRDTOOL.

    Install the Cacti software on CentOS / RHEL

    First, login as root user and type the following command to install mysql, apache and php:
    # yum install mysql-server mysql php-mysql php-pear php-common php-gd php-devel php php-mbstring php-cli php-snmp php-pear-Net-SMTP php-mysql httpd

    Configure MySQL server

    First, set root password:
    # mysqladmin -u root password NEWPASSWORD

    Create cacti MySQL database

    Create a database called cacti, enter:
    # mysql -u root -p -e 'create database cacti'
    Create a user called cacti with a password called zYn95ph43zYtq, enter:
    # mysql -u root -p

    mysql> GRANT ALL ON cacti.* TO [email protected] IDENTIFIED BY 'zYn95ph43zYtq'; 	
    mysql> FLUSH privileges;
    mysql> \q

    Install snmpd

    Type the following command to install net-snmpd
    # yum install net-snmp-utils php-snmp net-snmp-libs
    Configure snmpd, open /etc/snmp/snmpd.conf
    # vi /etc/snmp/snmpd.conf
    Append / modify it as follows (see snmpd.conf man page for details):

    com2sec local     localhost           public
    group MyRWGroup v1         local
    group MyRWGroup v2c        local
    group MyRWGroup usm        local
    view all    included  .1                               80
    access MyRWGroup ""      any       noauth    exact  all    all    none
    syslocation Unknown (edit /etc/snmp/snmpd.conf)
    syscontact Root  (configure /etc/snmp/snmp.local.conf)
    pass . /usr/bin/ucd5820stat

    Save and close the file. Turn on snmpd service:
    # /etc/init.d/snmpd start
    # chkconfig snmpd on

    Make sure you are getting information from snmpd:
    # snmpwalk -v 1 -c public localhost IP-MIB::ipAdEntIfIndex
    Sample ouptut:

    IP-MIB::ipAdEntIfIndex. = INTEGER: 2
    IP-MIB::ipAdEntIfIndex.67.yy.zz.eee = INTEGER: 3
    IP-MIB::ipAdEntIfIndex. = INTEGER: 1

    Install cacti

    First, make sure EPEL repo is enabled. Type the following command to install cacti:
    # yum install cacti

    Install cacti tables

    Type the following command to find out cacti.sql path:
    # rpm -ql cacti | grep cacti.sql
    Sample output:


    Type the following command to install cacti tables (you need to type the cacti user password):
    # mysql -u cacti -p cacti < /usr/share/doc/cacti-0.8.7d/cacti.sql

    Configure cacti

    Open /etc/cacti/db.php file, enter:
    # vi /etc/cacti/db.php
    Make changes as follows:

    /* make sure these values refect your actual database/host/user/password */
    $database_type = "mysql";
    $database_default = "cacti";
    $database_hostname = "localhost";
    $database_username = "cacti";
    $database_password = "zYn95ph43zYtq";
    $database_port = "3306";

    Save and close the file.

    Configure httpd

    Open /etc/httpd/conf.d/cacti.conf file, enter:
    # vi /etc/httpd/conf.d/cacti.conf
    You need to update allow from line. Either set to ALL or your LAN subnet to allow access to cacti:

    # Cacti: An rrd based graphing tool
    Alias /cacti    /usr/share/cacti
    <Directory /usr/share/cacti/>
            Order Deny,Allow
            Deny from all
            Allow from

    Another option is create /usr/share/cacti/.htaccess file and password protect the directory. Finally, restart httpd:
    # service httpd restart

    Setup cacti cronjob

    Open /etc/cron.d/cacti file, enter:
    # vi /etc/cron.d/cacti
    Uncomment the line:

    */5 * * * *     cacti   /usr/bin/php /usr/share/cacti/poller.php > /dev/null 2>&1

    Save and close the file.

    Run cacti installer

    Now cacti is ready to install. Fire a webbrowser and type the url:
    Just follow on screen instructions. The default username and password for cacti is admin / admin. Upon first login, you will be force to change the default password.

    How do I configure SNMP data collection?

    SNMP can be used to monitor server traffic. Once installed login to cacti.
    => Click on Devices

    => Select Localhost

    => Make sure SNMP options are selected as follows:

    Fig.01: SNMP configuration

    Fig.01: SNMP configuration

    Finally, click on Save button.

    How do I create SNMP graphs?

    Click on “Create Graphs for this Host” link on top right side.

    Select SNMP – Interface Statistics

    Select a graph type (such as In/Out bytes with total bandwidth)

    Finally, click on Create button.

    How do I view graphs?

    To view graphs click on Graphs tab. Here is sample graph from one my own box:

    Fig.02: Cacti in Action - Memory, CPU and Network Usage

    Fig.02: Cacti in Action – Memory, CPU and Network Usage

    (Fig.02: Cacti in action)

    Fig.03: Cacti in Action Disk, Load average and User stats

    Fig.03: Cacti in Action Disk, Load average and User stats

  • XBee Basics

    What’s cooler than a robot? A robot with a wireless network adapter! The XBEE wireless radio modules from Maxstream are a quick, inexpensive, and easy way to implement a wireless serial interface between two devices. They are practically a drop in replacement for a TTL-level serial cable. They have a low (~ 50mA) current consumption, and long range (rated at 300ft line of sight, but I have at least full speed coverage throughout a two-story house).

    An important note: Series 1 XBEE devices cannot talk to Series 2 (or series 2.5 devices)

    Wiring Options
    Connecting to the XBEE devices is quite easy, however, just remember that they are 3.3V devices. The regular ol’ XBEE will draw about 50mA (the PRO modules may draw upwards of 300mA). We can easily power our regular XBEE from an LP2950 3.3V 100mA regulator.

    There are a variety of easy to use modules for setting up your XBEE:

    • An XBEE USB Explorer can be used to connect an XBEE directly to your PC. It is a compact circuit board that already hhas a 3.3V regulator, plus a USB connection to commiunicate with your computer. It draws power directly from the serial port. Simply plug it into a USB port and you’re ready to go. I always keep an Explorer handy to do setup on my XBEE devices. (The XBEE Explorer is the red circuit board shown in the picture below).


    • You can also connect an XBEE directly to an FTDI breakout board.XBEEs unfortunately use 2mm headers, rather 0.1″ that we are all so accustomed to, however a breakout board that converts the 2mm layout to a breadboard-accessable 0.1″ one is available for only a few dollars. The breadboard below shows an FTDI breakout board, connected to and powering an XBEE breakout board.
    • An XBEE can be directly coupled to the TX/RX lines of a 3.3V or 5V microcontroller. In either case, it will still require a 3.3V power source. It is recommended that you use several resistors for a voltage divider if using the XBEE with a 5V microcontroller, however, I don’t. The following schematic shows both a circuit with voltage divider resistors and without, regardless, the XBEE always requires a 3.3V power supply:


    Most users will find they already have the FTDI drivers, but you may find that you need to install drivers for the XBEE Explorer or FTDI breakout. They can be found at http://ftdichip.com/Drivers/VCP.htm

    Pairing and Other Parameters
    If you want to have your XBEEs communicate at high speed, with the automatic resending of lost packets, you’ll want to pair them. And trust me — you want the automatic resending capability! This is very easy, we just need to set a few registers in the device. XBEE devices have several settings that we will use, and many more that we won’t be using right now. XBEE modules use standard AT commands. This is a protocol left over from the days of serial modems, but it still works for us now. These commands allow you to edit the registers found inside the XBEE. Each register has a name, prefixed by AT, such as ATBD, which is the Baud Rate register.

    First off, XBEE radios only operate at a given baud rate, this is the number of bits per second that the XBEE can send. A brand new xbee will default to 9600bps, which is pretty slow. We can change the baud rate, by changing the ATBD register. Both of our XBEEs have to be the same baud rate to talk to one another. The available baud rates (and corresponding ATBD value) are:

    • 1 = 2400bps
    • 2 = 4800bps
    • 3 = 9600bps
    • 4 = 19200bps
    • 5 = 38400bps
    • 6 = 57600 bps
    • 7 = 115200 bps

    The next parameter of interest is the Personal Area Network ID. This is a number shared amongst each XBEE in a network. For now, we are only using 2 XBEEs, but we could have many, many more in a single network. XBEEs on different networks do not “see” each other. The default PAN is 3332, so you should avoid that number. The PAN ID is stored in ATID

    Once both of our XBEEs are on the same network, we can give each one an address number, denoted by ATMY. We can also set the destination address, which is what address number to talk to, denoted ATDL (for destination low, we really don’t need to use the high bytes if we keep our address numbers < 16 bits in length). A sample setup of two XBEEs that will talk directly to one another, at 38.4kbps:

    ATID = 1111
    ATMY = 10
    ATDL = 11
    ATBD = 5

    ATID = 1111
    ATMY = 11
    ATDL = 10
    ATBD = 5

    Additionally, XBEE devices are 2.4Ghz radios. The 2.4Ghz band is currently used by many, many devices. None of them operate at exactly 2.4Ghz, there are several different channels which are in the 2.4Ghz band. We can change which channel the XBEE devices are on, ATCH, but again, devices on different channels cannot talk to one another.

    Using the MaxStream Software

    MaxStream distributes a piece of software called X-CTU which allows you to set all of the parameters we describe above, using a Graphical User Interface. Unfortunately, the software is a Windows application, but luckily for those of you using Linux (like myself), X-CTU can be run under Wine, here’s how.

    When we start X-CTU, we need to select the baud rate and port that our XBEE is connected to:

    It’s a good idea to click Test/Query to check that your baud/port are correct. If so, you’ll see a box that says:

    Once we know we have a good connection, we’ll switch over to the Modem Configuration tab, and click Read. The items of interest are obviously the Channel (CH), PAN ID, Destination Low (DL), and Source Address (MY). We have to scroll down a ways to see the Baud Rate (BD) setting:

    Once we make any changes, click Write to send them out to the XBEE. The write phase could take a little time.

    Using the XBEE-API Terminal to Send AT Commands Directly
    The XBEE-API Terminal is a simple to use python program that allows you to interact with an XBEE directly, sending AT commands. Why can’t we just use any old terminal? First, we want to send carriage returns rather than newlines, but also, we don’t want to send a carriage return on some transmissions.

    To setup the XBEE-API Terminal, you will need Python 2.5, and the PySerial package installed. You’ll then want to pull down xbee-serial-terminal.py and xbee.py and put them on your path (I’d also recommend renaming xbee-serial-terminal.py to something easier like xbeeterm.py):

    This same API can be used to programmatically interact with XBEEs quite easily. Setting this up to run, is just like any other python script.

    Before we can send AT commands, we need to get the XBEE into AT command mode, by sending “+++” and nothing else, for at least 3 seconds. We should have a short pause and then see “OK”. The XBEE will automatically exit AT command mode after 10 seconds of inactivity. We can then send data to our XBEE, or read back. With our example XBEE still in the XBEE Explorer, we would see:

    > +++
    > ATBD
    > ATID
    > ATDL
    > ATMY
    > ATND

    That last command is quite interesting. ATND tells the XBEE to do a Node Detection, which lets us find what devices are on around us. In this case our Arduino XBEE was on, we can now see what the key registers are set to, and how strong our connection is.

    We can also easily set parameters. An important thing to note though, is that changes we make are stored in temporary memory, if we power the XBEE device off, they are lost. We need to send ATWR to write the changes to non-volatile memory. If we decide to change our settings:

    > +++
    > ATID2222
    > ATMY12
    > ATID
    > ATWR

    Our PAN is now 2222, and our ID is 12 rather than 10. Our XBEEs will no longer talk to each other, or even see one another. You should change it back before continuing!

    Testing our setup with an Arduino
    To test our setup, we can use an Arduino to loopback our data. In this example, the Arduino will recieve data from the XBEE, and then send it back out, after incrementing by one. Thus if we send “Hello”, we should see “Ifmmp”. Hook up one of our XBEEs as shown above with our Breadboarded Arduino Connection, and plug our other into the XBEE Explorer. NOTE: You will have to remove the XBEE from the breadboard when downloading code onto the Arduino.

    // this is where we will put our data
    int myData = 0;
    void setup(){
        // Start up our serial port, we configured our XBEE devices for 38400 bps. 
    void loop(){
        // handle serial data, if any
        if(Serial.available() > 0){
            myData = Serial.read();
            if(myData == '\n')
                Serial.print(myData + 1, BYTE);

    Notes About Protocols
    Being a wireless network, there will eventually be lost information — even though the XBEE has automatic resend of lost packets. For mission critical stuff, I recommend adding your own data integrity or checksum/resend protocols on top of the hardware resend built into the XBEE.