reading a complete dip switch

Dependencies:   Hotboards_switches mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 
00002 /* Library:     Hotboards_switches.h
00003  * Project:     dip_switch
00004  * File:        main.cpp
00005  * Author:      Diego Perez
00006  * Modified by: Roman Valencia 
00007  * Contact:     http://www.hotboards.org/
00008  *
00009  * Read an entire dip switch composed by 8 interrupts
00010  */
00011 
00012 #include "mbed.h"
00013 #include "Hotboards_switches.h"
00014 
00015 // Creates a single sw object composed by 8 interrupts. theses interrupts will give us a
00016 // LOW(0) value when close because our dip switch works with pull-ups.
00017 Hotboards_switches dip_sw( PA_6 , PA_7 , PB_6 , PC_7 , PA_9 , PA_8 , PB_10 , PB_4 );
00018 // If your dip switch will gave you a HIGH(1) value when close, then we need to create the sw
00019 // object with an extra parameter: 
00020 // Hotboards_switches dip_sw( PA_6 , PA_7 , PB_6 , PC_7 , PA_9 , PA_8 , PB_10 , PB_4 , 1 );
00021 // In any case the functions will return a HIGH(1) value any time the sw is closed
00022 
00023 // For this example we will use the USB serial port, here we initialize it
00024 Serial pc(USBTX,USBRX);
00025 
00026 int i, j;
00027 uint8_t value;
00028 
00029 int main()
00030 {
00031     while(1)
00032     {
00033         // Reads the dip switch and puts it in value
00034         value = dip_sw.read();
00035         // Inverts the read value to make it coincide with the state of each
00036         // switch in binary
00037         value = ~value;
00038         // Sends throught USB serial the value in decimal
00039         pc.printf( "dec = " );
00040         pc.printf( "%d\r" , value );
00041         // Sends through USB serial the value in binary
00042         pc.printf( "bin = " );
00043         for(i=0;i<8;i++)            //Extracts and shows the binary value of each sw
00044         { 
00045             j = value&0x80;         //Applies a mask(10000000) to extract the value of the bit in turn
00046             j>>=7;                  //Moves this bit 7 positions to the right
00047             pc.printf("%d",j);      //Sends through USB serial the value of the extracted bit
00048             value <<=1;             //Moves the position 1 bit to the left to extract the next bit
00049         }
00050         pc.printf( "\n\r" );
00051         wait( 1 );
00052     }
00053 }