Showing posts with label serial monitor. Show all posts
Showing posts with label serial monitor. Show all posts

Monday, November 21, 2011

Projects -- Interrupts: Mark II

/*
 * Project:      Project_interrupt
 * Author:      Jane-Maree Howard
 * Date:         Monday 21/11/2011
 * Platform:    Arduino 22
 * Purpose:    To demonstrate an interrupt on Digital pin 3
 * Operation:  Description: Connect a 20kilOhm resistor from
 *                          digital pin3 to digital pin13!
 *                          Earlier problem solved as we now have a hardware feedback
 *                          from OUTPUT digi-pin13 to INPUT digi-pin3,
 *                          to which the interrupt is attached.
 *                          The digital flip-flop occurs every second, is fed to digi-pin3,
 *                          which registers the change & triggers the interrupt,
 *                          which, in turn, calls blink() where the pin state variable is flipped.
 *                          This state change is fed back via digi-pin13 to digi-pin3, triggering
 *                          the interrupt once again.                 
 */
int           iPin13   = 13;
int            iPin3   = 3;
volatile int  iState   = LOW;

void setup()
{
  // open Serial port
  Serial.begin(9600); 
  // set pin13, pin3 as OUTPUTs
  pinMode(iPin13, OUTPUT);
  pinMode(iPin3, INPUT);
  // interrupt1 calls blink() when pin13 flip-flops
  attachInterrupt(1, blink, CHANGE);
  digitalWrite(iPin3, iState);
  Serial.println("\nStart\n");
}//setup()

void loop()
{
  // delay 1 second
  delay(1000);
  // in effect, flip pin13
  Serial.println(iState);
  digitalWrite(iPin13, iState);
  digitalWrite(iPin3, iState);
}//loop()

void blink()
{
  // flip value to trigger interrupt
  iState = !iState;
}//blink()
//END



i finally cracked it!

most annoying though..
..but when i wondered about which pin the interrupt operated on, i went back to the appropriate page.. 

..where i saw that interrupt-0 can be attached to digital pin 2, & interrupt-1 to digital pin 3.

after that, it was pretty much plain sailing - the feedback resistor instead of some weird software, & as can be seen at left, it works beeootifly-thank-yew!

on to my next problem: how can i use LDR hardware to trigger an interrupt (for my "fridge door open" stuff!

{sigh of relief!}.

Projects -- Interrupts

/* example of interrupt function using Arduino 22 */

int                 iPin   = 13;
volatile int  iState = LOW;

void setup()
{
  // open Serial
  Serial.begin(9600); 
  // set pin13 as OUTPUT
  pinMode(iPin, OUTPUT);
  // interrupt1 calls blink() when pin13 flip-flops
  attachInterrupt(1, blink, CHANGE);
  digitalWrite(iPin, 1);
  Serial.println("\nStart\n");
}//setup()

void loop()
{
  // delay 1 second
  delay(1000);
  // in effect, flip pin13
  Serial.println(iState);
  digitalWrite(iPin, iState);
}//loop()

void blink()
{
  // flip value to trigger interrupt
  iState = !iState;
}//blink()
//END







i have been trying to get this interrupt program to work - it doesn't alternate the way i think/assume it should.


it just changes at random, sometimes acting like a touch or proximity switch!

i'm baffled :-?



here's where the example code came from - i've modified it to produce a serial monitor output, & inserted another digitalWrite() statement in the setup to try to get the thing triggering regularly..

..but it doesn't {sigh}..

Tuesday, November 15, 2011

Test Schedule

Well, to start with, here's some test information. Bit scary.. i had the erroneous impression it'd be next week, but it isn't!

Here's some hardware pics & the ATmega328 datasheet..
..& the pin-mapping between the ATmega328 & the Arduino..

We're getting lotsa questions on this.
Here's a schematic of the Duemilanove..
..& the Uno schematic.
 .

Sunday, November 6, 2011

Project 4 -- Major Project: initial survey..

Since this project involves THERMISTORS, i've gone to my other tech blog to see what i've done there.

And this entry has a handy data-table ^..^ .

The idea is to make a strip of about 4 or 5 thermistors to hang inside the door of my fridge; i want to see how much colder it is at the bottom compared to the top.

I know it is colder at the bottom, because meat keeps longer there, & sometimes starts to freeze, whereas it never does  that nearer the top.

I need some of that ribbon cable to 'insert' the thermistors into, & also to transmit data to the analog pins on my Arduino.  i also have a USB power supply, so i could actually do some data-logging over an extended period & save the data to EEPROM for later retrieval & display (& just by chance i've found a LED-strip with about 10 LEDs on it that i'd forgotten i had!).

I'd like to add TWI to a 24LCxx if i can, as that would allow more data to be stored.

A photo-cell (these entries) could tell me when the fridge door was opened.

Another little wrinkle would be to average all the thermistor readings at any one time, &  switch on a motor, say, if the average temperature rises above a preset value.

First things first, however: i need to set up the thermistor strip, write the basic software, & get that part working;  i can add bells & whistles later.

Wednesday, October 26, 2011

Task 40 - Timer0 Polling routine - toggle LED on/off

/*
 * Project:      Timer_0_Polling_Experiment
 * Author:      Peter Brook tidied by Jane-Maree Howard on..
 * Date:          ..Wednesday 26/10/2011
 * Platform:    Arduino 22
 * Purpose:     To visually demonstrate Timer0 polling
 * Operation:  Polls Timer0 prescaled by 1024; toggles LED on/off every second
 *      Declare: toggle variable; counter vble; ToggleLED() routine 
 *      Setup():  Serial port @9600baud; Prints opening statement; delays 5 seconds
 *                      set TImerMaSK0 to zero - turn of Timer0 interrupt;
 *                      set Timer/CounterControlRegister0B to DEC5; prescaler /s by 1024;
 *      Loop():    idle until TimerInterruptFlagRegister0 == 1;
 *                      reset TIFR0; count 1 'tick'(from 0 to 60, 61 'ticks');
 *                      @ 60'ticks', reset 'ticks' & toggle LED on/off
 */
int     state = 1;        // LED toggle vble - init. OFF!      
byte  ticks = 0;        // counts up towards 60, the LED toggle value

void setup()
{
  Serial.begin(9600);  // Serial port @ 9600 baud
  Serial.println("\n\tInitial state is OFF\n\t");
  delay(5000);            // wait 5 seconds 
  // initialize digital pin 13 as an output.
  // Pin 13 has an LED connected on most Arduino boards:

  pinMode(13, OUTPUT);
  //after this, can't use 'delay() any more
  TIMSK0 = 0;          // turn off Interrupt for Timer0
  TCCR0B = 5;         // Prescaler divides by 1024;  BIN101 = DEC5
}//setup()

void loop()
{
   while(byte(TIFR0 &0x01) ==0) // loop till flag goes up
   {/* do nothing */}                       
   TIFR0 = 1;                // clear flag
   ticks++;                     // count a tick
 
   if (ticks == 60)          // preset value
   {
      ticks=0;                  // reset 'ticks'
      Serial.print("\tTT ");
      ToggleLED();        // toggle LED
   }//if()
}// loop()

void ToggleLED()
{
  if (state==1)
  {
    digitalWrite(13,LOW);                    // LED turns OFF
    state = 0;                                          // toggle 'state' vble
    Serial.print("I've toggled OFF");   // Serial Monitor o/p
  }//if()
  else
  {
    digitalWrite(13,HIGH);                    // LED turns ON
    state=1;                                             // toggle 'state' vble
    Serial.println("I've toggled ON "); // Serial Monitor o/p
  }//else()
}//ToggleLED() 



In the code, the initial state of the on-board LED (pin 13) is OFF.


The SM output records the first toggle ("TT") & the LED
(of course ) stays OFF.

From then on, the LED's recorded toggled state matches that of the on-board LED (pin 13)

Thursday, October 20, 2011

Task 38a - using the I2C bus with an EEPROM 24LC64 addressed differently

I've added a line to the earlier code coz i want to make it easier to change the device address.


 In this particular case:
  A0 is LOW;
  A1 is HIGH;
  A2 is LOW.


This device needs to be addressed as 0x52
(see code changes below)


#include {Wire.h}           // I2C library - usual brackets warning

byte  LCaddress  = 0x52;    // 24LC64 device address
:
:
// now write the char-string to the EEPROM - NOTE 0x52:address pin A1 is HIGH
i2c_eeprom_write_page(LCaddress, 0, (byte *)somedata, sizeof(somedata));
:
:
// now access the first address (0) from the memory
 byte b = i2c_eeprom_read_byte(LCaddress, 0);   //NOTE 0x52:address pin A1 is HIGH
:
:
 addr++;                //..next address &..
//..access next address from the memory.
b = i2c_eeprom_read_byte(LCaddress, addr);      //NOTE 0x52:address pin A1 is HIGH
:
:
etcetera..

& i've changed the input data just to make sure the program's doing what it should be doing..
 
char somedata[] = "Jane-Maree's EEPROM data";  // - 24 characters..



And this is what it does..










..& when i've written..

byte  LCaddress  = 0x51;    // 24LC64 device address


 ..it's because.. 

  A0 is HIGH;
  A1 is LOW;
  A2 is LOW.


..& this device needs to be addressed as 0x51..



..producing this  ==} 




i've got pikkies of the breadboard arrangement clearly (i hope) showing the connections to A0, A1, & A2.


Everything else is unchanged..







Wednesday, October 19, 2011

Task 38.1 - using the I2C bus with an EEPROM 24LC64: software edit

/*
 * Project:      eeprom_fromWeb
 * Author:      hkhijhe - tidied even more by Jane-Maree Howard
 * Date:         01/10/2010
 * Platform:   Arduino 22
 * Purpose:    To demonstrate use of the I2C bus with an EEPROM 24LC64
 -             "You were issued with an eeprom 24LC64 IC.
 -              This is a TWI memory that you connect to SCL and SDA on the Arduino.
 -              Run the program from the blog.
 -              Show your code changes and the serial monitor output in your blog".
 * Operation:  Because this chip is I2C,
 -               it only uses Arduino analog pins 4 & 5 (SDA and SCL),
 -               and of course the power (5V) and GND.
 -             Connect as follows:
 -                Arduino pin 4 to EEPROM pin 5
 -                Arduino pin 5 to EEPROM pin 6
 -                Arduino 5V to EEPROM pin 8
 -                Arduino GND to EEPROM pin 1,2,3,4
 -             Be sure to leave pin 7 of the EEPROM open or tie it to GND,
 -               otherwise the EEPROM will be write protected.
 -             Include: Wire.h - the I2C library
 -             Declare: various i2c_eeprom_read.. i2c_eeprom_write.. procedures
 -             Setup(): Opens the Wire connection, the Serial connection,
 -                      writes a char-string to the EEPROM, & prints heading
 -                      NOTE: the char-string has length = 28
 -             Loop():  Reads from the EEPROM, & prints, one byte at a time, & repeats                
 */

#include {Wire.h}               //I2C library-usual brackets warning

  void setup()
  {
    // a char-string of data to write to the EEPROM - 28 characters long!!
    char someData[] = "this is data from the eeprom";
   /*
    char somedata[] = "this is Jane-Maree's eeprom data"; - 32 characters..
     .. & it bombs.  Gibberish - I've tried it!  See WARNING below..
   */
    Wire.begin();                 // Wire connection initialised
    Serial.begin(9600);       // Serial connection @ 9600 baud
    // now write the char-string to the EEPROM
    i2c_eeprom_write_page(0x50, 0, (byte *)someData, sizeof(someData));
    delay(10);                     //add a small delay..
    // ..& print a heading
    Serial.println("\nMemory written");
    Serial.println("\nNow read memory & print to Serial port");
  } //setup()

  void loop()
  {
    int addr=0;               // address parameter, starts @ 0
    // now access the first address (0) from the memory
    byte b = i2c_eeprom_read_byte(0x50, 0);
    // while there are non-zero bytes..
    while (b!=0)
    {
      Serial.print((char)b); //..print content as char to serial port..
      addr++;                      //..next address &..
      //..access next address from the memory.
      b = i2c_eeprom_read_byte(0x50, addr);
    }//while ()
    Serial.println(" ");     // new line..
    delay(2000);               // ..2 second delay, & start again!
  } //loop()


   /*
    WARNING: address is a page address, 6-bit end will wrap around
    also, data can be maximum of about 30 bytes,
    because the Wire library has a buffer of 32 bytes
  */
  void i2c_eeprom_write_page( int deviceAddress, unsigned int eeAddressPage, byte* data, byte length )
  {
    Wire.beginTransmission(deviceAddress);
    Wire.send((int)(eeAddressPage >> 8));       // MSB
    Wire.send((int)(eeAddressPage & 0xFF));  // LSB
    byte c;
    for ( c = 0; c < length; c++)
      Wire.send(data[c]);
    Wire.endTransmission();
  } //i2c_eeprom_write_page()


  byte i2c_eeprom_read_byte( int deviceAddress, unsigned int eeAddress )
  {
    byte rdata = 0xFF;
  
    //ask device by address for data
    Wire.beginTransmission(deviceAddress);
    Wire.send((int)(eeAddress >> 8));             // MSB
    Wire.send((int)(eeAddress & 0xFF));           // LSB
    Wire.endTransmission();
  
    Wire.requestFrom(deviceAddress,1);
    if (Wire.available())
      rdata = Wire.receive();
    return rdata;
  } //i2c_eeprom_read_byte()

// END

Tuesday, October 18, 2011

Task 38 - using the I2C bus with an EEPROM 24LC64

(The post following this one goes into different device addresses)
The address given in the original code - below, more or less - has the 24LC64 connected as follows:

Pin A0 is LOW;
Pin A1 is LOW;
Pin A2 is LOW.

This requires the device address to be 0x50.

Later, we will see devices connected so that they are to be addressed as  0x51  &  0x52, merely by varying  the LOW/HIGH status of A0, A1, & A2.


This is how several devices can be connected to the same I2C bus - they are addressed differently.
/*
 * Project:      eeprom_fromWeb
 * Author:      hkhijhe - tidied by Jane-Maree Howard
 * Date:         01/10/2010
 * Platform:   Arduino 22
 * Purpose:    To demonstrate use of the I2C bus with an EEPROM 24LC64
 -             "You were issued with an eeprom 24LC64 IC.
 -              This is a TWI memory that you connect to SCL and SDA on the Arduino.
 -              Run the program from the blog.
 -              Show your code changes and the serial monitor output in your blog
". 
 * Operation:  Because this chip is I2C,
 -               it only uses Arduino analog pins 4 & 5 (SDA and SCL),
 -               and of course the power (5V) and GND.
 -             Connect as follows:
 -                Arduino pin 4 to EEPROM pin 5
 -                Arduino pin 5 to EEPROM pin 6
 -                Arduino 5V to EEPROM pin 8
 -                Arduino GND to EEPROM pin 1,2,3,4
 -             Be sure to leave pin 7 of the EEPROM open or tie it to GND,
 -               otherwise the EEPROM will be write protected.
 -             Include: Wire.h - the I2C library
 -             Declare: various i2c_eeprom_read.. i2c_eeprom_write.. procedures
 -             Setup(): Opens the Wire connection, the Serial connection,
 -                      writes a char-string to the EEPROM, & prints heading
 -                      NOTE: the char-string has length = 28
 -             Loop():  Reads from the EEPROM, & prints, one byte at a time, & repeats                 
 */

#include {Wire.h}               //I2C library-usual brackets warning
 
  void setup()
  {
    // a char-string of data to write to the EEPROM - 28 characters long!!
    char somedata[] = "this is data from the eeprom";

   /*
    char somedata[] = "this is Jane-Maree's eeprom data"; - 32 characters..
     .. & it bombs.  Gibberish - I've tried it!  See WARNING below..

   */
    Wire.begin();                 // Wire connection initialised
    Serial.begin(9600);       // Serial connection @ 9600 baud
    // now write the char-string to the EEPROM
    i2c_eeprom_write_page(0x50, 0, (byte *)somedata, sizeof(somedata));
    delay(10);                     //add a small delay..
    // ..& print a heading
    Serial.println("\nMemory written");
    Serial.println("\nNow read memory & print to Serial port");
  } //setup()

  void loop()
  {
    int addr=0;               // address parameter, starts @ 0
    // now access the first address (0) from the memory
    byte b = i2c_eeprom_read_byte(0x50, 0);
    // while there are non-zero bytes..
    while (b!=0)
    {
      Serial.print((char)b); //..print content to serial port..
      addr++;                      //..next address &..
      //..access next address from the memory.
      b = i2c_eeprom_read_byte(0x50, addr);
    }//while ()
    Serial.println(" ");     // new line..
    delay(2000);               // ..2 second delay, & start again!
  } //loop()
 

  void i2c_eeprom_write_byte( int deviceaddress, unsigned int eeaddress, byte data )
  {
    int rdata = data;
    Wire.beginTransmission(deviceaddress);
    Wire.send((int)(eeaddress >> 8));             // MSB
    Wire.send((int)(eeaddress & 0xFF));        // LSB
    Wire.send(rdata);
    Wire.endTransmission();
  } //i2c_eeprom_write_byte()

  /*
    WARNING: address is a page address, 6-bit end will wrap around
    also, data can be maximum of about 30 bytes,
    because the Wire library has a buffer of 32 bytes
  */
  void i2c_eeprom_write_page( int deviceaddress, unsigned int eeaddresspage, byte* data, byte length )
  {
    Wire.beginTransmission(deviceaddress);
    Wire.send((int)(eeaddresspage >> 8));       // MSB
    Wire.send((int)(eeaddresspage & 0xFF));  // LSB
    byte c;
    for ( c = 0; c < length; c++)
      Wire.send(data[c]);
    Wire.endTransmission();
  } //i2c_eeprom_write_page()

  byte i2c_eeprom_read_byte( int deviceaddress, unsigned int eeaddress )
  {
    byte rdata = 0xFF;
   
    Wire.beginTransmission(deviceaddress);
    Wire.send((int)(eeaddress >> 8));             // MSB
    Wire.send((int)(eeaddress & 0xFF));        // LSB
    Wire.endTransmission();
   
    Wire.requestFrom(deviceaddress,1);
    if (Wire.available())
      rdata = Wire.receive();
    return rdata;
  } //i2c_eeprom_read_byte()

  // maybe let's not read more than 30 or 32 bytes at a time! See NOTE!
  void i2c_eeprom_read_buffer( int deviceaddress, unsigned int eeaddress, byte *buffer, int length )
  {
    Wire.beginTransmission(deviceaddress);
    Wire.send((int)(eeaddress >> 8));          // MSB
    Wire.send((int)(eeaddress & 0xFF));     // LSB
    Wire.endTransmission();
   
    Wire.requestFrom(deviceaddress,length);
    int c = 0;
    for ( c = 0; c < length; c++ )
      if (Wire.available())
        buffer[c] = Wire.receive();          
  } //i2c_eeprom_read_buffer()



You can see the gibberish along the top, caused by a buffer over-run.

i think this was what happened earlier, when i was 'experimenting'.

When all else fails, 
   Read The Instructions.

Now i need to figure out how to get around that buffer problem - i've not yet understood how to add a C-header file (.h) & C-file (.cpp)..

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: schematic

this is the best i could do - i don't know how to make circuit jumper in Fritzing but it should be obvious that that's what they are, not connections..

The 3 'wriggly' things are Peltier elements (Thermistors)

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

Saturday, September 24, 2011

Task 32 -- the Triple Axis Accelerometer

"Find the post on the Triple Axis Accelerometer. 
 This is an example of a sensor we have to deal with.   
 Find out more information about this sensor 
 and compose a schematic illustrating how you would use an Arduino to (record) real acceleration in     
 three dimensions and display the outputs. 
 Your blog output should contain a schematic and code." 

Umm, here's my post on the hardware (with pikkie!).

Now we should have a schematic.. 
(Fritzing is good for drawing schematics!)

Here's the datasheet.. 

..& a circuit diagram (courtesy of Fritzing) showing how the accelerometer is connected to an Arduino board & external power source (not complicated at all, is it)


Wednesday, September 7, 2011

Task 20 - Motor spinning at different rates using PWM: software & output

/*
 * Project:      MotorSpin_621task20
 * Author:       Jane-Maree Howard
 * Date:          Wednesday 07/09/2011
 * Platform:      Arduino 22
 * Purpose:      To demonstrate control of a DC motor
 * Operation:   Description: The motor is a ET-MINI DC-MOTOR board.
                            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:     Pin variables (byte), delay multiplier (int); pulse width & mark-space varibles (int)
         Setup():     Serial.begin = 9600 baud; initialise digital control pins as outputs
         Procedure(): RotateMotor(params) takes 3 bytes (for the motor) & an integer ('space')        
         Loop():      Within a 'for'-loop, set RotateMotor() parameters & steadily decrease 

                            the mark-space ratio,  thus increasing the motor speed 
                            until mark:zero is reached, i.e. full speed;              
 */
byte bRight    = 10;        // IN1 is pin 10 - rotate Right
byte bLeft     = 8;           // IN2 is pin 8  - rotate Left
byte bEnable   = 13;      // EN  is pin 13 - Enable rotation, must = '1'
int iDelay     = 1000;     // delay variable
int iPulse     = 4;            // pulse width
int iFreq      = 1;            // (mark-)space variable

void setup()  
{
  Serial.begin(9600);    //SM @ 9600baud
  //initialise digital control pins as outputs
  pinMode(bRight, OUTPUT);    // IN1
  pinMode(bLeft,  OUTPUT);     // IN2
  pinMode(bEnable, OUTPUT);  // EN 
}//end setup()

void loop()                    
{
  for (int j=100; j>=0; j--)   // slowly decrease mark-space ratio, increasing speed
  {
    Serial.print("Mark-space ratio is 4 - ");
    Serial.println(j);
    RotateMotor(1,0,1,j);     // rotate motor Right @ set speed..
  }//for()   
}//end loop()

// RotateMotor()
void RotateMotor(byte bR, byte bL, byte bE, int iSlow)
{
  /*the 3 byte variables enable motor, 'iSlow' regulates speed in that
    the larger the 'space' variable the longer the mark-space ratio is,
    & so the slower the motor turns */
  digitalWrite(bRight, bR);    // write to motorboard pin IN1
  digitalWrite(bLeft, bL);      // write to motorboard pin IN2
  digitalWrite(bEnable, bE);  // write to motorboard pin EN - enable motor
  delay(iPulse);                       // 'pulse' motor for 'iPulse' milliseconds, 

                                               // 4ms is the minimum for function
  digitalWrite(bEnable, 0);    // write zero to motorboard pin EN - disable motor..
  delay(iFreq*iSlow);             // .. for 'iFreq' milliseconds
}//RotateMotor()
//END




The mark-space ratio begins at 4 - 100,
i.e. the motor receives a 4 millisecond impulse, then is disabled (EN=0) for 100 milliseconds - the result is a rather jerky turning motion.


From experience, it was found that a 4 millisecond impulse was the minimum needed to turn the motor at all - with shorter pulses it just twitched but did not rotate.


The for-loop begins with its count variable set at 100 & decreases to 0; this variable is set as a parameter for the RotateMotor(), in which it performs the role of the 'space' variable in a mark-space ratio. As this ratio decreases (i.e. the 'space' gets shorter relative to the fixed 'mark' variable), the speed of the motor increases, until it reaches full-speed (mark-space=4-0).


The motor thus begins turning slowly, gradually speeding up until it reaches full speed; then the loop() repeats itself & the slow-increase-fast cycle begins again.


The image at right clearly shows the serial monitor output, with its constant 'mark' & varying 'space' variables, beginning at 100 & decreasing to 0.