Showing posts with label libraries. Show all posts
Showing posts with label libraries. Show all posts

Tuesday, October 18, 2011

Task 37 - Integrate the new eeprom library from the link

Integrating the new eeprom library from the link here. 

"To use the library, make a folder in your SKETCHBOOKPATH\libaries 
  with the name I2C_EEPROM and put the .h and .cpp there. 
  Optionally make a examples subdirectory to place the sample app."

Reference: http://arduino.cc/playground/Main/LibraryForI2CEEPROM


Having tried Task 38 in room D208, I'm now wondering if my current change of room (D209) is causing a problem.  The website refers to a 'boundary problem', & I have a feeling that I don't really know what I'm doing (yet)..








Hmmm.. When in a quandary, have a laugh - "thanks" to Mike Keefe of the 'Denver Post'




















And this guy, Andrew Toos, at CartoonStock

 I like the 'robot' on the right..  these are just too good (hehe)  :-D

Friday, October 7, 2011

tasks 18 & 19: revised software showing library use

First of all i re-wrote the software for tasks 18 & 19, as you will see in the next post

i then rewrote the functions in a test LIB sketch, & when it compiled & ran ok, i deleted the setup() & loop() parts & saved it in a separate folder which i have  called Arduino Libraries.

These should NOT BE CONFUSED with the C-libraries, for which you must write the line, at the head of your code:
 #include Clib1.h
(which normally has those pointy brackets enclosing the .h file - but which means something entirely different in this blog's HTML so i can't put them in).



In the Arduino task sketch, click on 'Sketch' as shown on the right.

Click on 'Add File...'

 You get the dialog box as shown on the left.

You have to know where your required file is, & open it..

Click on the 'Open' tab.

You now have TWO sketches open, & they can be combined to operate as one.

And when you save the original sketch, the LIBrary sketch is saved with it, so that every time you subsequently open the main sketch you get the LIB sketch opening with it.

i should add a line to the LIB sketch, describing the required parameters.

in theory (hehe - famous last words!) i should be able:
  to write anything that has the right parameters for the right job;
  to plug in a different motor provided the parameters fit;
  change the motor type used with only minor code alterations.

this has been a bit of a holdup, & i think is worth the extra effort i've made for it.

ps: the same probably applies to Processing sketches i'd imagine..

Here's some example code - Keypress input via the Serial Monitor:


 /*
 * Project:     LIB04_KeypressInput
 * Author:      Jane-Maree Howard
 * Date:         Saturday 08/10/2011
 * Platform:   Arduino 22
 * Purpose:    To make a library function for inputting a key-press via Serial comm link
 * Operation:  Description: inputs a key-press & returns an Integer
 -                     Procedure(): int KeypressInput();  no parameters             
 */
int KeypressInput()
{
  /*  inputs a keypress via the Serial comms link
      & returns a non-zero Integer only if there is an input
      CALLED IN MAIN SKETCH  */

  int iKey = 0;
  // send data only when you receive data
  if (Serial.available() > 0)
      iKey = Serial.read();
  return iKey;
}//KeypressInput()
.
 //END

Used in the following posts (click to return to them if necessary):
  Project 02 - Motor Project;
 Task 13;
 Task 14;


Sunday, September 25, 2011

Project 3 -- Minor Project: software

/*
 * Project:    Minor_Project_621
 * Author:     Jane-Maree Howard
 * Date:       Wednesday 21/09/2011
 * Platform:   Arduino 22
 * Purpose:    To demonstate a fridge-control robot
 * Operation:  Several thermistors are mounted inside the fridge.
 *              Their values are read in sequence at 1-minute intervals,
 *              their average is calculated, & the values & their average stored in EEPROM
 *              A LDR is also mounted inside the fridge, to detect when the door is opened.
 *              Change in the LDR resistance trigers an interrupt, & this is also recorded.
               Declare: 
               Setup():             
               Loop():                   
 */
#include                   // EEPROM library

int  iAnalogPin[]    = {0,1,2,3};    // analog pin numbers
int  iLEDpin         = 13;           // door-open LED
int  iDarkLevel      = 100;          // pre-set photocell reading triggering interrupt

int  iGetData        = 0;            // get signal to retrieve data

int  iHeading        = 0;            // signal to print heading
int  iSecond         = 1000;         // 1 second delay &..
int  iMinute         = 60000;        // ..1 minute delay

int  iTemperature[3];                // temperature readings from A0 - A2
int  iAvgTemp;                       // Average of the 3 temperatures

volatile byte iAddressCount   = 0;   // EEPROM address counter
volatile byte bLEDstate       = 0;   // LED pin ON or OFF
 
/* all operations are performed in the setup() section of the program */
void setup()  
{
  delay(iSecond*5);                 // up to 10 minute delay
  pinMode(iLEDpin, OUTPUT);         // LED-pin is an output..
  digitalWrite(iLEDpin,LOW);        // ..initially turned off
  Serial.begin(9600);               // SM @ 9600baud
  // attach interrupt 0, to digital pin 2
  attachInterrupt(0, DoorOpen, CHANGE); // ..on CHANGE
                     
  iGetData  = KeypressInput();      // check for receiving data
  while (iGetData == 0)             // if no signal,start reading..
  {
    // stop interrupts while reading
    noInterrupts();                 // stop interrupts while reading
    iAvgTemp   = 0;                 // zero average Temperature vble               
    /* First read the 3 values into iTemperature[] .. */
    for (byte j=0; j<3; j++)
    { 
      // read value on 3 thermistor pins i.e. iAnalogPin[j]
      iTemperature[j]  = analogRead(iAnalogPin[j]); 
      // now we have to map 0-1023 to 0-255..
      // ..since we want to store the values as bytes..
      iTemperature[j]  = map(iTemperature[j], 0, 1023, 0, 255);
      // ..& write them to EEPROM
      EEPROM.write(iAddressCount, iTemperature[j]);
      // increment the address count..
      iAddressCount++ ;
      iAvgTemp        += iTemperature[j];  // add to average total         
      // delay 10 milliseconds
      delay(10);  
    }//for(j)
    iAvgTemp  = (int)(iAvgTemp/3);
    // write Average to EEPROM also..
    EEPROM.write(iAddressCount, iAvgTemp);
    // ..& increment the address count.
    iAddressCount++ ;
    interrupts();                   // re-enable interrupts
   
    // debugging
    Serial.print("\nrecorded data\t");
    for (int j=0;j<3;j++)
      Serial.print(iTemperature[j]);
    Serial.print(iAvgTemp);
   
    delay(iMinute);                 // delay 1 minute..
    iGetData  = KeypressInput();    // ..then check for receiving data
  }// while(==0) */


 
  while (iGetData != 0)             // ..otherwise, retrieve stored data & send to SM
  {
    if (iHeading%20 == 0)
      Heading();
    iHeading++;
   
    //diagnostic stuff & logic testing
    if (iHeading > 100)
    {
      iGetData  = 0;    // check for receiving data
      iHeading = 0;
    }//if()
   
  }// while(!=0)
}// end setup()

void loop()
{/*nothing done in here*/}//end loop()

/* prints heading to Serial Monitor at pre-set intervals */
void Heading()
{
  Serial.println("\nTemperatures\tT0\tT1\tT2\tT3\tAverage\tDoor\n");
}//Heading()

//END


LIBRARY FUNCTIONS:

/*
 * Project:    LIB04_KeypressInput
 * Author:     Jane-Maree Howard
 * Date:       Saturday 08/10/2011
 * Platform:   Arduino 22
 * Purpose:    To make a library function for inputting a key-press via Serial comm link
 * Operation:  Description: inputs a key-press & returns an Integer
 -             Declare:     NONE - MUST BE DECLARED IN CONJOINING SKETCH(ES)
 -             Setup():     NONE - MUST BE USED ONLY IN CONJOINING SKETCH(ES)
 -                          (used  only in testing)
 -             Procedure(): int KeypressInput();  no parameters   
 -             Loop():      NONE - MUST BE USED ONLY IN CONJOINING SKETCH(ES)
 -                          (used  only in testing)            
 */
int KeypressInput()
{
  /*  inputs a keypress via the Serial comms link
      & returns a non-zero Integer only if there is an input
      CALLED IN MAIN SKETCH  */
  int iKey = 0;
  // send data only when you receive data
  if (Serial.available() > 0)
    iKey = Serial.read();
  return iKey;
}//KeypressInput()
//END



/*
 * Project:    LIB09_photocell_interrupt
 * Author:     Jane-Maree Howard
 * Date:       Thursday 24/11/2011
 * Platform:   Arduino 22
 * Purpose:    To make a Photocell Switch for an interrupt pin (digital 2 or 3).
 * Operation:  The circuit arrangement is the same as the ladyada
 *             LED dimmer, but here the software has a trigger threshold 
 *             for turning the interrupt pin on.
 *             The output of the Analog pin is measured as before,
 *              but instead of analogWrite() to the interrupt pin,
 *              digitalWrite is used to switch the pin on or off.
 *             We don't need to map the Analog pin output,
 *              since it's merely a trigger.
 *             Original description:
 *               "Connect one end of the photocell to 5V, the other end to Analog 0.
 *                Then connect one end of a 4.7K resistor from Analog 0 to ground
 *                Connect LED from pin 9 through a resistor to ground"
 *             Declare, Setup(), Loop(): 
 *              NONE - MUST BE USED ONLY IN CONJOINING SKETCH(ES)
 -             Procedure(): void PhotocellTrigger(int,int,int); 
 -                          void DoorOpen();
 */

/* the photocell pin value is tracked by the interrupt */
void PhotocellTrigger(int iInterruptPin, int iPhotoPin, int iDark)
{
  int iPhotoReading = analogRead(iPhotoPin);     //i.e. analog 0
    //we now use our  'darkLevel' variable to trigger the LED ON.
  if (iPhotoReading > iDark)
    digitalWrite(iInterruptPin, HIGH);          // turn InterruptPin on, else..
  else
    digitalWrite(iInterruptPin, LOW);           // ..turn InterruptPin off 
}//PhotocellTrigger()

/* called when the Interrupt is triggered - records door state */
void DoorOpen()
{
  digitalWrite(iLEDpin, bLEDstate);      // Turn door-open LED ON or OFF..
  EEPROM.write(iAddressCount, bLEDstate);// ..record the incident..
  iAddressCount++;                       // .. increment address count..
  bLEDstate  = !bLEDstate;               // ..& change LED-state ON to OFF or vice versa
}//DoorOpen()
//END

Project 3 -- Minor Project: Design

My MINOR PROJECT has the following hardware design features:

** 3 thermistors on a wiring loom able to be set up inside my fridge.

** 1 photocell on the same wiring loom.

** A Duemilanove Arduino board, 
     to poll the 3 temperatures at around 1 minute intervals,
     with an interrupt feature involving the photocell
     (for when the door is opened - & closed again,
     & the software to save to & retrieve the data from the on-board EEPROM.


The whole project can be independently powered through the USB port - i have a USB power source, but a bit of tweaking may enable power to be supplied by a 9v battery (not sure about this).
    
The software design involves the following:

** Regular polling of the 3 thermistors connected to Analog pins A0, A1, A2.
     Their readings are saved to EEPROM

** An interrupt feature triggered by the photocell connected to Analog pin A3.
     The interrupt is attached to Digital pin 2, 
triggered by the photocell reading  rising above a pre-determined 'darkness' threshold.  
     A LED will be lit & the fact recorded on EEPROM in binary form (1 = open).


** A Serial Monitor connection enabling retrieval of the recorded data on a signal from the serial connection (via SM).


** A software delay enabling the project to be set up & connected to its power source - nothing will happen for about 5 minutes - then the program starts recording data.


** The software delay can be over-ridden by a signal from the SM, when the project is connected to a PC; data retrieval can then begin.


** Data retrieved from the EEPROM is written to the SM, appropriately formatted.
.

Sunday, September 18, 2011

Task 27 -- The Wire Librrary

27. List the main functions of the Wire library.
       Say what they do with examples.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Wire Library Functions
======================

1.    begin()
      begin(address)

Initiates the Wire library and joins I2C bus as master or slave.
Normally called only once.

Parameters: address: the 7-bit slave address (optional);
        if not specified, join the bus as a master.
No returns.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

2.  requestFrom(address, count)

Used by master to request bytes from slave device.
The bytes may then be retrieved with the available() and receive() functions.

Parameters:    address:  the 7-bit address of device to request bytes from
        quantity: the number of bytes to request
No returns.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


3.  beginTransmission(address)

Begin transmission to I2C slave device with address given.
Queue bytes for transmission with send() function.
Transmit bytes by calling endTransmission().

Parameters: address: 7-bit address of device to transmit to
No returns.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


4.  endTransmission()

Ends transmission to slave device begun by beginTransmission()
Actually transmits the bytes queued by send().

No parameters.

Returns: byte, indicating transmission status:

0   success
1   data too long to fit in transmit buffer
2   received NACK on transmit of address
3   received NACK on transmit of data
4   other error.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


5.  send()

Sends data from slave device in response to request from master, or
queues bytes for transmission from master to slave device
(in-between calls to beginTransmission() and endTransmission()).

Parameters: value:      a byte to send (byte)
        string:     a string to send (char *)
        data:       an array of data to send (byte *)
        quantity:     the number of bytes of data to transmit (byte)
No returns.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

6.  byte available()

Returns number of bytes available for retrieval with receive().
Should be called on master device after call to requestFrom(),
or on slave inside the onReceive() handler.

No parameters;
Returns:  number of bytes available for reading.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

7.  byte receive()

Retrieves byte transmitted from slave device to master
after call to requestFrom()
         or transmitted from master to slave.

No parameters;
Returns:  next byte received.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
8.    onReceive(handler)
9.    onRequest(handler)

These are not much used in our projects.

Note: On most Arduino boards,
                   SDA (data line) is on analog input pin 4, and
                   SCL (clock line) is on analog input pin 5.


Reference:  http://arduino.cc/en/Reference/Wire
.

Tuesday, August 30, 2011

Project 2 - Arduino Motor Project - Serial input speed & direction control

Here's the Fritzing diagram, showing pins 9 & 10 used since they have the Pulse Width Modulation (PWM) option enabled on them.


/*
 * Project:      MotorSpin_621project02_1
 * Author:      Jane-Maree Howard
 * Date:         Tuesday 11/10/2011
 * Platform:   Arduino 22
 * Purpose:    To demonstrate Serial input motor control
 * Operation:  Description: The ET-MINI DC-MOTOR board has an H-bridge & a DC motor
 -                          The board's terminals are:
 -                          EN - Enable, must be set at logic "1" for operation.
 -                          IN1- With EN @ "1", IN1 @ "1" rotates the motor to the Right.
 -                          IN2- With EN @ "1", IN2 @ "1" rotates the motor to the Left
 -            
Arduino Libraries: LIB04_KeypressInput; LIB06_PWMmotorSpeed_ETMINI;  
 -            
Setup(): Serial @ 9600 baud; Print heading;            
 -            
Loop():  Via Serial Monitpr, input a PAIR of characters, e.g. r7, ss, L9;
 -                      Press 'Enter' or 'Send';
 -                      Motor direction & speed range are outputted &..
 -                      ..PWMmotorControl(bRight, bLeft, bEnable, bMotor, bSpeed) operates
 -                      the motor according to instruction-pair;

 */
int  iKeyPress = 0;      // for incoming serial data
char chInput;              // for 'char' parameters
// digital control pins for ET-MINI DC-MOTOR
byte bRight    = 10;    // IN1 is pin 10 - rotate Right
byte bLeft     = 9;       // IN2 is pin 9  - rotate Left
byte bEnable   = 13;  // EN  is pin 13 - Enable rotation, must = '1'
byte bMotor    = 0;    // in LIB06_PWMmotorControl(), '0'=STOP, '1'=RIGHT, '11'=LEFT
byte bSpeed    = 0;    // in ditto, PWM duty cycle parameter - initialised to "stop"

void setup()  
{
  Serial.begin(9600);                      //SM @ 9600 baud
  pinMode(bEnable, OUTPUT);   // EN - ENable pin on motorboard
  pinMode(bRight, OUTPUT);     // IN1 - 'RIGHT' pin on motorboard
  pinMode(bLeft, OUTPUT);       // IN2 - 'LEFT' pin on motorboard
  Serial.println("\nEnter your control characters in pairs e.g.: R5, ss");
}//end setup()

void loop()                    
{
  // first input Motor Direction, STOP, RIGHT, or LEFT
  iKeyPress = KeypressInput();
  if (iKeyPress !=0)
  {
    Serial.print("\nInput direction\t");
    chInput   = (char)iKeyPress;
    Serial.println(chInput, BYTE);
    switch (chInput)
    {
      case ('s'):
        bMotor    = 0;
        break;
      case ('S'):
        bMotor    = 0;         
        break;
      case ('r'):
        bMotor    = 1;
        break;
      case ('R'):
        bMotor    = 1;
        break;
      case ('l'):
        bMotor    = 11;
        break;
      case ('L'):
        bMotor    = 11;
        break;     
      default: bMotor    = 0;    
    }//switch()

    // now input Motor Speed on a scale of 1-9
    iKeyPress = KeypressInput();
    Serial.print("Input speed\t");
    chInput   = (char)iKeyPress;
    Serial.println(chInput, BYTE);
    switch (chInput)
    {
      case ('1'):
        bSpeed    = 50;
        break;
      case ('2'):
        bSpeed    = 75;
        break;
      case ('3'):
        bSpeed    = 100;
        break;  
      case ('4'):
        bSpeed    = 125;
        break;
      case ('5'):
        bSpeed    = 150;
        break;
      case ('6'):
        bSpeed    = 175;
        break;    
      case ('7'):
        bSpeed    = 200;
        break; 
      case ('8'):
        bSpeed    = 225;
        break;        
      case ('9'):
        bSpeed    = 255;
        break;     
      default: bMotor    = 0;    
    }//switch()
  }//if()
  /* now that control characters have been entered e.g.L7,
     call PWMmotorControl with all parameters present
  */

  PWMmotorControl(bRight, bLeft, bEnable, bMotor, bSpeed);
}//end loop()
//END


The control characters must be entered as a pair,
otherwise it will not function.

The direction can be upper or lower case.

The duty cycle (input speed 1-9) can in theory range from 0-255, but in practice, anything < 50 won't fire the motor up.
255 represents 100%, or full-speed.







/*
 * Project:    LIB06_PWMmotorSpeed_ETMINI
 * Author:       Jane-Maree Howard
 * Date:          Tuesday 11/10/2011
 * Platform:     Arduino 22
 * Purpose:     To use PWM speed-control for an ET-MINI DC-MOTOR board
 * Operation:  The ET-MINI DC-MOTOR board has an H-bridge & a DC motor
 -                          The board's terminals are:
 -                          EN - Enable, must be set at logic "1" for operation.
 -                          IN1- With EN @ "1", IN1 @ "1" rotates the motor to the Right.
 -                          IN2- With EN @ "1", IN2 @ "1" rotates the motor to the Left  
 -             Declare:     NONE - MUST BE DECLARED IN CONJOINING SKETCH(ES)
 -             Setup():     NONE - MUST BE USED ONLY IN CONJOINING SKETCH(ES)
 -                          (used  only in testing)
 -             Procedure(): void PWMmotorControl(byte,byte,byte,byte,byte);     
 -             Loop():      NONE - MUST BE USED ONLY IN CONJOINING SKETCH(ES)
 -                          (used  only in testing)   
         
 */
//   RotateMotor - CALLED IN MAIN SKETCH
void PWMmotorControl(byte bR, byte bL, byte bEN, byte bMO, byte bSPEED)
{
  /* 
  Rotate ET-MINI DC-MOTOR: bR,bL,bEN are Pins; bMO en/dis-ables;
 
  bSPEED takes values 0-255 as part of the PWM duty cycle;
  analogWrite() is a PWM operation on a Digital pin,
  .            
& has nothing to do with Analog pins or AnalogRead()
  */
  // pause motor to allow change of direction

  delay(20);                        // delay 20 milliseconds
  digitalWrite(bEN,1);      // write '1' to motorboard pin EN - enable motor
  switch (bMO)
  {
    case 0:                          // STOP  - disable motor
      digitalWrite(bEN,0);  // write '0' to motorboard pin EN
      break;
    case 1:                          // rotate RIGHT @
      digitalWrite(bL,0);    // write '0' to motorboard pin IN2 - no rotation left
      analogWrite(bR,bSPEED);   // write to motorboard pin IN1
      break;
    case 11:                       // rotate LEFT @ 
      digitalWrite(bR,0);   // write '0' to motorboard pin IN1 - no rotation right
      analogWrite(bL,bSPEED);   // write to motorboard pin IN2   
      break;
    default:                           // STOP - disable motor
      digitalWrite(bEN,0);    // write '0' to motorboard pin EN - disable motor
  }//switch()case
}//PWMmotorControl()
//END


Go to the following link for the operating software
/*
 * Project:       LIB04_KeypressInput
 * Author:       Jane-Maree Howard
 * Date:           Saturday 08/10/2011
 * Platform:     Arduino 22
 * Purpose:     To make a library function for inputting a key-press via Serial comm link
 * Operation:  Description: inputs a key-press & returns an Integer

.

Thursday, August 25, 2011

Task 14 - Arbitrary byte serial monitor output bit-by-bit

/*
 * Project:    bitwiseByteOutput_task14
 * Author:     Jane-Maree Howard
 * Date:         Wednesday 24/08/2011; modified Sunday 09/10/2011
 * Platform:   Arduino 22
 * Purpose:    To output the bits, one by one, to the
  =                  serial monitor(SM) screen from an arbitrary byte.
 * Operation:  Inputs an arbitrary byte, which is right-shifted 0 to 7 places
 -             successively, bit-wise ANDed with value B01, & each resultant bit is
 -             separately outputted to the SM
 -             Arduino Libraries: LIB04_KeypressInput; LIB05_BitSelect;
 -             Declare: Function bitwiseByte(bByte,iShifts); int iKeyPress; byte bInbyte;
 -             Setup(): Serial @ 9600 baud; headings             
 -             Loop():  Input keypress as arbitrary byte; output byte as BINary;
 -                      output each bit separately
 */
int     iKeyPress = 0;       // for incoming serial data 
byte    bInbyte;
void setup()  
{
  Serial.begin(9600);        // Serial @ 9600 baud
  // print headings
  Serial.println("KEY-PRESS\tBIN\tLSB..................MSB");  
}//end setup()

void loop()                    
{ 
  // send data only when you receive data
  iKeyPress = KeypressInput();       // LIB04_KeypressInput
  if (iKeyPress !=0)
  {
    Serial.print(iKeyPress, BYTE);   // print as ASCII character
    Serial.print("\t\t");                    // print tabs
    bInbyte  = iKeyPress;      //
    Serial.print(bInbyte, BIN);         // print resultant byte as binary
    Serial.print("\t");                      // print tab
    for (int j=0; j<8; j++)                 // now select each bit separately
    {
      bInbyte  = iKeyPress;
      bInbyte  = BitSelect(bInbyte, j);     // LIB05_BitSelect
      Serial.print(bInbyte, BIN);             // ..print each bit..
      Serial.print("  ");                           // ..& 2 spaces
    }//for()
    Serial.println(); 
  }//if()  
}//end loop()
//END


As can be seen, the BIN column entries
are 'mirror-imaged' by the block labelled LSB............MSB since we start with the Least Significant Bit.  Leading zeroes omitted in the BIN column give the output a slightly unbalanced look.

 LIB04_KeypressInput
 see Task 13

 /*
 * Project:    LIB05_BitSelect
 * Author:     Jane-Maree Howard
 * Date:         Sunday 09/10/2011
 * Platform:   Arduino 22
 * Purpose:    To make a library    function for selecting a given bit         from an arbitrary byte
 * Operation:  Bitwise ANDs arbitrary byte with value B01
 -                    after being right-shifted a given number of places
 -             Declare:     NONE - MUST BE DECLARED IN CONJOINING SKETCH(ES)
 -             Setup():     NONE
 -             Procedure(): byte BitSelect(byte, byte);     
 -             Loop():      NONE          
 */
byte BitSelect(byte bByte, byte bShift)
{
  /*  bitwise ANDs parameter bByte with value B01
      after being right-shifted bShift places
      & returns a separate Byte
      CALLED IN MAIN SKETCH  */
  bByte      = bByte >> bShift;
  bByte      = bByte & B01;
  return bByte;
}//BitSelect()
//END

Task 13 - byte left-shifting function

/*
 * Project:      ByteLeftShift_621task13
 * Author:     Jane-Maree Howard
 * Date:         Wednesday 21/09/2011; modified Saturday 08/10/2011
 * Platform:   Arduino 22
 * Purpose:    To left-shift a byte in the parameter postion two places to the left
 -                   then output the original and the final byte.
 * Operation:  Description: Prints headings; inputs character;
 -             Arduino Libraries: LIB04_KeypressInput (see below);
 -             Declare: Function leftShiftByte(bByte,iShifts); int iKeyPress; byte bInbyte;
 -             Setup():             
 -             Loop():                   
 */
int     iKeyPress = 0;       // for incoming serial data 
byte    bInbyte;
void setup()  
{
  Serial.begin(9600);       // Serial @ 9600 baud
  // print headings
  Serial.println("KEY-PRESS\tBIN\tSHIFTED");  
}//end setup()

void loop()                    
{
   // send data only when you receive data
  iKeyPress = KeypressInput();       // LIB04_KeypressInput
(see below)
  if (iKeyPress !=0)
  {
    Serial.print(iKeyPress, BYTE);    // print as ASCII character
    Serial.print("\t\t");                     // print tabs
    bInbyte  = iKeyPress;      //
    Serial.print(bInbyte, BIN);          // print resultant byte as binary
    Serial.print("\t");                        // print tab
    bInbyte  = leftShiftByte(bInbyte,2);  // left-shift 2 places &..
    Serial.println(bInbyte, BIN);             // ..print resultant byte as binary
  }//if()  
}//end loop()

// leftShiftByte() - left-shifts parameter byte iShift places
byte leftShiftByte(byte bByte,int iShift)
{
  bByte  = bByte << iShift;
  return bByte;
}//leftShiftByte()
//END



 The left-shifted byte is clear from the screen-print  
 on the right. 


Leading zeros omitted (in the BIN column & the SHIFTED column) .


Below is my Arduino Library function for Serial input.


 /*
 * Project:     LIB04_KeypressInput
 * Author:     Jane-Maree Howard
 * Date:         Saturday 08/10/2011
 * Platform:   Arduino 22
 * Purpose:    To make a library function for inputting a key-press via Serial comm link
 * Operation:  Description: inputs a key-press & returns an Integer
 -                    Procedure(): int KeypressInput();  no parameters             
 */
int KeypressInput()
{
  /*  inputs a keypress via the Serial comms link
      & returns a non-zero Integer only if there is an input
      CALLED IN MAIN SKETCH  */
  int iKey = 0;
  // send data only when you receive data
  if (Serial.available() > 0)
    iKey = Serial.read();
  return iKey;
}//KeypressInput()


Task-14

Task 12 - byte LSB test function

/*
 * Project:    ByteLSBtest_621task12
 * Author:     Jane-Maree Howard
 * Date:       Wednesday 21/09/2011; modified Saturday 08/10/2011
 * Platform:   Arduino 22
 * Purpose:    Function to say "yes" if the LSB (least significant bit) is a 1
 -              or "no" otherwise. Tested in the main loop.
 * Operation:  Description:  inputs keypress via Serial comm link;
 -                           A function taking the keypress integer as parameter
 -                           logically ANDs it with binary number B01,
 -                           producing a number which is equal to
 -                           either '1' or '0', & prints "yes" or "no" accordingly
 -             Arduino Library: LIB04_KeypressInput; LIB03_BinaryAND;
 -             Declare: Function LSBtest(bByte); (int)iKeyPress; (byte) bInbyte;
 -             Setup(): Serial comms @ 9600 baud; headings;           
 -             Loop():  input keypress; test LSB & print 'yes'/'no' result                 
 */
int     iKeyPress = 0;       // for incoming serial data 
byte    bInbyte;           // function parameter

void setup()  
{
  Serial.begin(9600);      // Serial comms @ 9600 baud
  // print headings
  Serial.println("KEY-PRESS\tBIN\tYES/NO");    
}//end setup()

void loop()                    
{ 
  // send data only when you receive data
  iKeyPress = KeypressInput();      // LIB04_KeypressInput - see below
  if (iKeyPress !=0)
  {
    Serial.print(iKeyPress, BYTE);   // print as ASCII character
    Serial.print("\t\t");                    // print tab      
    Serial.print(iKeyPress, BIN);     // print as BINary
    Serial.print("\t");                      // print tab
    bInbyte  = iKeyPress;
    LSBtest(bInbyte);                      // test LSB 
  }//if()
}//end loop()

// tests parameter's LSB for '1'/'0' & outputs "yes"/"no"
void LSBtest(byte bByte)
{
  // test LSB
  bByte  = BinaryAND(bByte, B01);  //
LIB03_BinaryAND - see below
  // there are only 2 possible values
  if (bByte == 0)
    Serial.println("NO");
  else
    Serial.println("YES");
}//LSBtest()
//END




self-explanatory..

(bit fuzzy tho')















/*
 * Project:    LIB03_BinaryAND
 * Author:     Jane-Maree Howard
 * Date:         Friday 07/10/2011
 * Platform:   Arduino 22
 * Purpose:    To make a library function for bitwise ANDing 2 bytes
 -             Declare:     NONE - MUST BE DECLARED IN CONJOINING SKETCH(ES)
 -             Setup():     NONE     
 -             Loop():      NONE       
 */
byte BinaryAND(byte bB1, byte bB2)
{
  /*  bitwise ANDs 2 Bytes together & returns a separate Byte
  -   CALLED IN MAIN SKETCH  */
  byte bOutByte  = bB1 & bB2;
  return bOutByte;
}//BinaryAdd()
//END

/*
 * Project:    LIB04_KeypressInput
 * Author:     Jane-Maree Howard
 * Date:         Saturday 08/10/2011
 * Platform:   Arduino 22
 * Purpose:    To make a library function for inputting a key-press via Serial comm link  

 -             Declare:     NONE - MUST BE DECLARED IN CONJOINING SKETCH(ES)
 -             Setup():     NONE     
 -             Loop():      NONE    
         
 */
int KeypressInput()
{
  /*  inputs a keypress via the Serial comms link
  -    & returns a non-zero Integer only if there is an input
  -    CALLED IN MAIN SKETCH  */
  int iKey = 0;
  // send data only when you receive data
  if (Serial.available() > 0)
    iKey = Serial.read();
  return iKey;
}//KeypressInput()
//END

Task 11 - bit-ANDing function

/*
 * Project:    BinaryANDing_621task11
 * Author:     Jane-Maree Howard
 * Date:         Wednesday 21/09/2011; modified Friday 07/10/2011
 * Platform:   Arduino 22
 * Purpose:    To demonstrate a function to bitwise AND a byte with B01
 -                   and output the result to the screen.
 -                   Tests in the main loop().
 * Operation: Inputs a byte via Serial comm & 

 -                   function taking a byte as parameter bitwise-ANDs it
 -                   with value B01
 -         Arduino Library: LIB03_BinaryAND - function BinaryAND(byte,byte)

 -                                    LIB04_KeypressInput  
 -             Declare:          byte bInbyte; int iKeyPress;
 -             Setup():          Serial comms @ 9600 baud; print heading              
 -             Loop():           Input a byte via Serial comm & output to SM as BIN;

 -                                   bitwise-AND byte with value B01 & output result to SM.                
 */
int     iKeyPress = 0;     // for incoming serial data 
byte    bInbyte;

void setup()  
{
  Serial.begin(9600);      //Serial @ 9600baud
  // print headings
  Serial.println("KEY-PRESS  BIN\t    AND b01"); 
}//end setup()

void loop()                    
{ 
  // send data only when you receive data
  iKeyPress = KeypressInput();       // LIB04_KeypressInput
  if (iKeyPress !=0)
  {
    Serial.print(iKeyPress, BYTE);   // print as ASCII character
    Serial.print("\t   ");           // print tabs
    bInbyte  = iKeyPress;            //
    Serial.print(bInbyte, BIN);      // print resultant byte as binary
    Serial.print("  ");              // print tab
    bInbyte  = BinaryAND(bInbyte, B01);   // LIB03_BinaryAND
    Serial.println(bInbyte, BIN);         // ..print resultant byte as binary
   }//if()  
}//end loop()
//END


At right is the Serial Monitor output showing what happens to a byte that is bitwise-ANDed with the value B01.

Only the LSB appears, as leading zeroes are ignored.



/*
 * Project:    LIB03_BinaryAND
 * Author:     Jane-Maree Howard
 * Date:         Friday 07/10/2011
 * Platform:   Arduino 22
 * Purpose:    To make a library function for bitwise ANDing 2 bytes
 * Operation: bitwise ANDs 2 parameter bytes & returns a third byte
 -              Declare:     NONE - MUST BE DECLARED IN CONJOINING SKETCH(ES)
 -              Setup():     NONE - MUST BE USED ONLY IN CONJOINING SKETCH(ES)
 -                              (used  only in testing)
 -              Procedure(): byte BinaryAND(byte, byte);     
 -              Loop():      NONE - MUST BE USED ONLY IN CONJOINING SKETCH(ES)
 -                              (used  only in testing)            
 */
byte BinaryAND(byte bB1, byte bB2)
{
  /*  bitwise ANDs 2 Bytes together & returns a separate Byte
      CALLED IN MAIN SKETCH  */
  byte bOutByte  = bB1 & bB2;
  return bOutByte;
}//BinaryAdd()
//END


/*
 * Project:     LIB04_KeypressInput
 * Author:     Jane-Maree Howard
 * Date:         Saturday 08/10/2011
 * Platform:   Arduino 22
 * Purpose:    To make a library function for inputting a key-press via Serial comm link
 * Operation:  inputs a key-press & returns an Integer
 -             Declare:     NONE - MUST BE DECLARED IN CONJOINING SKETCH(ES)
 -             Setup():     NONE - MUST BE USED ONLY IN CONJOINING SKETCH(ES)
 -                               (used  only in testing)
 -             Procedure(): int KeypressInput();  no parameters   
 -             Loop():      NONE - MUST BE USED ONLY IN CONJOINING SKETCH(ES)
 -                              (used  only in testing)            
 */
int KeypressInput()
{
  /*  inputs a keypress via the Serial comms link
      & returns a non-zero Integer only if there is an input
      CALLED IN MAIN SKETCH  */
  int iKey = 0;
  // send data only when you receive data
  if (Serial.available() > 0)
    iKey = Serial.read();
  return iKey;
}//KeypressInput()
//END
 

Wednesday, August 10, 2011

Task 6 - Key-Press program: other serial monitor output

/*
 * Project:    keyPressBrayOutput_621task06
 * Author:     Jane-Maree Howard
 * Date:       Wednesday 21/09/2011
 * Platform:   Arduino 22
 * Purpose:    To input a key-press from computer & output it to a Bray++ serial monitor
 * Operation:  Description:
 *             Declare: iKeyPress (int)
 *             Setup(): Bray++ serial monitor (BSM);  headings
 *             Arduino Library: LIB04_KeypressInput()            
 *             Loop(): reads input; prints character & ASCII codes                                             
 */


The program is exactly the same as in 621task06, except that the Bray++ Terminal monitor is used instead.

The COM port is selected on the PC running the Arduino to be the same as that selected on the opened Bray Terminal.

The line
   Serial.begin(9600); 
                                       is still needed to allow the connection to be made but the Arduino Serial Monitor is NOT opened.


 This is the Bray Terminal monitor.
Unfortunately, it presented me with only 2 COM ports, COM1 & COM3 - neither would work on the Arduino, which would upload only on COM4.

So this'll have to wait until i get home (where i hope i can make it work).