Tuesday, 27 March 2012

Tasks 21 ->>>>

Task 21: Output random numbers between 0 and 100 to the terminal:


void setup(){
  Serial.begin(9600);
}


void loop(){
  Serial.println(random(0,101));
  delay(200);
}

Task 22: dice throwing- output a number between 1 and 6 every second:


void setup(){
  Serial.begin(9600);
}


void loop(){
  Serial.println(random(1,7));
  delay(1000);
}


Task 23: Display number of 6is thrown:


int sixes = 0;
int num = 0;
void setup(){
  Serial.begin(9600);
}


void loop(){
  num = random(1,7);
  if (num == 6){
  sixes++;
}
   Serial.println(num);
  Serial.println();
  Serial.println("Sixes throwen");
  Serial.println(sixes);
  Serial.println();
  delay(1000);
}


Task 24 same as 23 but faster and stops at 25 sixes.


int sixes = 0;
int num = 0;
void setup(){
  Serial.begin(9600);
}


void loop(){


while (sixes < 25){


  num = random(1,7);
  if (num == 6){
  sixes++;
}
   Serial.println(num);
  Serial.println();
  Serial.println("Sixes throwen");
  Serial.println(sixes);
  Serial.println();
  delay(100);
}
}


Task 25: how many throws to get to 100 sixes:


int sixes = 0;


int num = 0;
 int throws = 0;
void setup(){


  Serial.begin(9600);


}


void loop(){


while (sixes < 100){
  num = random(1,7);


  if (num == 6){
  sixes++;
}
throws++;


}


Serial.println("Throws to 100 sixes");
Serial.println(throws);
Serial.println();
delay(10000);
throws = 0;
sixes = 0;
}


Task 26: push button program:

 created 2005
 by DojoDave <http://www.0j0.org>
 modified 30 Aug 2011
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/Button
 */



// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin


// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status


void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);    
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);    
}


void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);


  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {    
    // turn LED on:    
    digitalWrite(ledPin, HIGH);
  }
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}
Task 27 - reverse program operation:
int buttonState = 0;         // variable for reading the pushbutton status


void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);    
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);    
}


void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);


  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:


  if (buttonState == HIGH) {    
    // turn LED off:    
    digitalWrite(ledPin, LOW);  //Program altered so led is off when button pressed
  }
  else {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  }
} 
Task 28 - Output state of button and led to screen.
int buttonState = 0;         // variable for reading the pushbutton status


void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);    
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);   
Serial.begin(9600);  //Serial output setup
}


void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);


  if (buttonState == HIGH) {    
    // turn LED off:    
    digitalWrite(ledPin, LOW);  //Program altered so led is off when button pressed
Serial.Println("Button pressed, LED off") // write output
  }
  else {
    // turn LED on:
    digitalWrite(ledPin, HIGH);


  }
} 


Task 29 - De bouncing:  


As switch contacts are made out of a metal they have the tenancy to bounce or chatter a number of times when the switch is released. Whilst this happens to quickly to observe and the effects often go unnoticed when it comes to sensitive logic circuits it can be interpreted as the switch being pressed and released a number of times.  The effects of this can be countered using a simple delay or a Latch circuit depending on they type of switch in use. 


Task 30 - Buzzer and light circuit:


Task 31 - 


Task 32 -Run String conversion program 
Had to set serial monitor to "NewLine" in order to get it to work


Task 33 - What happens under error conditions?


No number:
Result:
String:
Value:0



Huge Number:
12345678900987654321
Result: 

Value:-597200719
String: 12345678900987654321



String:
abcd
Result:
String:
Value:0



String and number:
abcd1234
Result:
Value:1234
String: 1234



Task 34 - Red Green program:


//This program reads a number from the serial terminal and illuminates a red led if its //larger than 50 and a green led if its less than 50:


int red = 2;
int green = 3;

String inString = ""; // string to hold input

void setup() {
// Initialize serial communications:
Serial.begin(9600);
pinMode(red,OUTPUT);
pinMode(green,OUTPUT);
}

void loop() {
// Read serial input:
while (Serial.available() > 0) {
int inChar = Serial.read();
if (isDigit(inChar)) {
// convert the incoming byte to a char
// and add it to the string:
inString += (char)inChar;
}
// if you get a newline, print the string,
// then the string's value:
if (inChar == '\n') {
if (inString.toInt() > 50)
  {
    digitalWrite(red,HIGH);
    digitalWrite(green,LOW);
  }
if (inString.toInt() < 50)
  {
    digitalWrite(red,LOW);
    digitalWrite(green,HIGH);
  }

inString = "";
}
}
}




Task 35 - Random led flasher
Generated a number between 0 and 100 if the number is less than 50 the green led lights if the number is larger than 50 the red led lights:


int red = 2;
int green = 3;
long rndNum;

void setup() {
// Initialize serial communications:
Serial.begin(9600);

pinMode(red,OUTPUT);
pinMode(green,OUTPUT);
}

void loop() {

rndNum = random(101);
if (rndNum > 50)
  {
    digitalWrite(red,HIGH);
    digitalWrite(green,LOW);
  }
if (rndNum < 50)
  {
    digitalWrite(red,LOW);
    digitalWrite(green,HIGH);
  }

delay(1000);
}



Task 36 - Simple guessing game:
Generates a number between 0 and 100 and accepts a users guess, if the users guess is larger than the number the red led is illuminated otherwise the green led is illuminated, if the number is correctly guessed then both leds are illuminated:

int red = 2;
int green = 3;

String inString = ""; // string to hold input
long rndNum;
long guess;
void setup() {
// Initialize serial communications:
Serial.begin(9600);
pinMode(red,OUTPUT);
pinMode(green,OUTPUT);
}

void loop() {
// Read serial input:

rndNum = random(101);

while (guess != rndNum)
{
  while (Serial.available() > 0) {
  int inChar = Serial.read();
  if (isDigit(inChar)) {
 
  inString += (char)inChar;
  }
 
  if (inChar == '\n') {
   guess = inString.toInt();
  
  if (guess > rndNum)
    {
      digitalWrite(red,HIGH);
      digitalWrite(green,LOW);
    }
  if (guess < rndNum)
    {
      digitalWrite(red,LOW);
      digitalWrite(green,HIGH);
    }
    if (guess == rndNum)
    {
      digitalWrite(red,HIGH);
      digitalWrite(green,HIGH);
    }
  
  inString = "";
  }
  }
}
}


Task 37 More complex guessing game:
Allows the user to guess the number as before,  gives feedback as to how many guesses the user has made, when the user gets the number correct they are congratulated and their total number of guesses is displayed along with the mystery number:

int red = 2;
int green = 3;

String inString = ""; // string to hold input
long rndNum;
long guess;
int noGuesses = 0;
void setup() {
// Initialize serial communications:
Serial.begin(9600);
pinMode(red,OUTPUT);
pinMode(green,OUTPUT);
}

void loop() {
// Read serial input:
noGuesses = 0;
rndNum = random(101);

while (guess != rndNum)
{
  while (Serial.available() > 0) {
  int inChar = Serial.read();
  if (isDigit(inChar)) {
 
  inString += (char)inChar;
  }
 
  if (inChar == '\n') {
   guess = inString.toInt();
   noGuesses++;
  if (guess > rndNum)
    {
      digitalWrite(red,HIGH);
      digitalWrite(green,LOW);
    }
  if (guess < rndNum)
    {
      digitalWrite(red,LOW);
      digitalWrite(green,HIGH);
    }
    if (guess == rndNum) // If guess correct alert user and return
    {
      digitalWrite(red,HIGH);
      digitalWrite(green,HIGH);
      Serial.println();
      Serial.print ("Well Done, The number was ");
      Serial.print (rndNum);
       Serial.println();
       Serial.print ("You took ");
       Serial.print (noGuesses);
       Serial.print (" guesses to get the number");
       Serial.println();
       inString = "";
       return;
    } 

    Serial.print("you guessed: ");
    Serial.print(guess);
    Serial.println();
    Serial.print("so far you have made ");
    Serial.print(noGuesses);
    Serial.print(" guesses");
    Serial.println("");

  inString = "";
  }
  }
}
}

Task 38:
Arduino memory types:

Flash memory :
where the arduino "sketch" is stored, there is 32kb available for the user to strore programs on the ATMega328.
SRAM: 
Where variables are created and stored during run time, the ATMega328 had 2048 Bytes available for storage. This memory space is volatile and its contents are lost after power is removed.
EEPROM: 
User available memory space where long term memory can be stored, this memory has a limited number or write cycles (approx 100,000) the ATMega328 has 1024 Bytes of EEPROM available. 

Task 39:
Processor Flash Memory RAM EEPROM
AVR Tiny 4 500 Bytes 3 Bytes NONE
ATMega 32K 2048 Bytes 1024 Bytes
ATmega2560 256K 8Kb 4Kb


Task 40:
First 512 bytes of EEPROM Memory:
Byte 1 = 1 - I have used this one before
Bytes 2 - 512 are equal to 255

Data Logger Task:
Using the Arduinos internal EEPROM as a data store I will log 48 hours worth of light readings, The MEGA328 has 1kb of space available which equates to a total of 1000 possible readings of a byte each. I will take a reading every 5 minutes as light levels don't change that dramatically. In 48 hours there are 2880 minutes which will give me a total of 576 samples after a period of 48 hours at a sampling rate of 5 minutes as discussed above. 

The below code takes a light reading every 5 minutes and writes it to the Arduinos EEPROM. After 576 consecutive samples have been taken a red led is illuminated to alert me that 48 hours has elapsed:
Time in hours =  (loggingPeriod * samplesTaken ) /  60
Time in hours = (5 * 576) / 60 = 48

#include <EEPROM.h>
int lightPin = 0; // Pin for light readings
int doneLed = 2; // Pin for Done led
int powerLed = 3; // Pin for power led
long interval = 300000; //every 5 mins
long previousMillis = 0; 
int count = 0;

void setup(){
 pinMode(powerLed,OUTPUT);
 pinMode(lightPin,INPUT);
 pinMode(doneLed,OUTPUT);
 digitalWrite(powerLed,HIGH);
 Serial.begin(9600);
}

void loop(){
 
  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval) {
   previousMillis = currentMillis; 

   writeValue(getLight());
 
   Serial.println(getLight()); 
   Serial.println(count);
}   
 
}

int getLight(){
  int light = analogRead(lightPin);
  int lightScaled = map(light, 0, 1023, 0, 255);
  return lightScaled;
}

void writeValue(int value){
  if (count <=576){
    EEPROM.write(count,value);
    count++;
  }else{
  digitalWrite(doneLed,HIGH); //Complete
  }
 
}

Logger Data Dump Code:
This code will return all the readings stored in the Arduinos EEPROM.


#include <EEPROM.h>
int count = 0;

void setup(){
  Serial.begin(9600);
  Serial.println("Light Reading");
}

void loop(){
    while (count <= 576){
    Serial.println(EEPROM.read(count));
    count++ ; 
  } 

 }


Results: 
After the logger was set up and left for 48 hours the data dump code was uploaded to recover the readings obtained over the 48 hours: 
 
 The logger was started at mid day on day one and left to run for 2 full days at which point the red "Done" light illuminated to alert me that 48 hours had elapsed. 

The graph above shows graphically how the light levels varied over the period of 48 hours. From the above graph it appears that the light levels rise and fall very sharply however this graph is showing data from a period of 48 hours so it very condensed. 

The second graph below shows a "Sunset" over a period of 2 hours:

  

In the first graph, the peaks observed during the dark periods are people turning lights on it the room with the logger, if this data is extrapolated out it can be determined exactly how long the light was on. 



 
  

Tuesday, 6 March 2012

LED Dice / number game

Led Dice / Number Game

User guesses a number using left hand button and rolls the dice using right hand button. 

Number selection and simulated dice rolling accomplished with array of 6 LED's.  User feedback via RGB LED.

If user guesses correctly RGB LED illuminates green otherwise it illuminates red:



Source code:

int leds[] = {13,12,11,10,9,8}; // dice leds array
int rollSw = 2; //roll dice switch
int selSw = 1; // select "number" switch
int val = 0; //value used for switch press detection
int val1 = 0;
long num = 0; //
int count = 0; // count for number selected by user

int red = 6; //red led
int green = 7; //green led

void setup(){
    pinMode (rollSw, INPUT); //roll dice switch
    pinMode (selSw, INPUT); // Select Number switch
    pinMode(red,OUTPUT); //Red LED
    pinMode(green,OUTPUT); //Green LED   
  for(int i = 0; i <=5 ; i++)//loop through array of number leds setting pins to output
  {
    pinMode(leds[i], OUTPUT);
   
  
  }
}

void loop(){
val = digitalRead(rollSw); // Read Roll Switch
if (val == LOW){rollDie();}; // Roll dice if switch pressed

val1 = digitalRead(selSw); // Read Select Switch
if (val1 == LOW && count <= 5 ){ // If switch pressed and count not > 5 select leds
  
allOff(); // turn any exitsing leds off
   
   digitalWrite(leds[count], HIGH); // turn next led in sequence on
 
   count++; // count up in sequence
   delay(200); // delay to prevent button bounce
  }else if (count > 5){count = 0;digitalWrite(leds[5], LOW); } // if count > 5 turn off last led, reset count
}

void rollDie(){ // roll dice subroutine
allOff(); // turn off any leds

for (int i = 0; i <=24; i++ ){; //roll dice 24 times
num = random(0,6); // generate random number between 0 - 5;
digitalWrite(leds[num], HIGH); //set selected led on
delay(80); // wait
digitalWrite(leds[num], LOW); // turn selected led off
}
digitalWrite(leds[num], HIGH); // roll finnished - set final led on
 if (num == (count-1)){digitalWrite(green,HIGH);} // if final led = user slected led turn on green led
 else {digitalWrite(red,HIGH);} // else turn on red led
 count = 0;//reset count
}

void allOff(){ // turn all leds off
  digitalWrite(red, LOW);   //turn red off
  digitalWrite(green, LOW);  //turn green off
   for(int i = 0; i <=5 ; i++) // loop through dice led array - turn all off
  {
    digitalWrite(leds[i], LOW);
   
   
  
  }
}
 



Saturday, 25 February 2012

Arduino LED multiplexer

0-6 count
 

0 - 19 count driving both displays together





Basic Arduino LED multiplexer using 74HC595 chip and 5 x 7 segment display (5 individual displays with 7 segments each) pulled from an old DVD recorder, currently has 2 displays counting but could easily be expanded to include all 5 displays.


Monday, 20 February 2012

Tasks 11 - 20

Arduino Programs:

Task 11 - Single LED Blink:

Created 1 June 2005
 By David Cuartielles
 http://arduino.cc/en/Tutorial/Blink  based on an orginal by H. Barragan for the Wiring i/o board  */
int ledPin =  13;    // LED connected to digital pin 13

// The setup() method runs once, when the sketch starts

void setup()   {              

 // initialize the digital pin as an output:
 pinMode(ledPin, OUTPUT);
}

// the loop() method runs over and over again,

// as long as the Arduino has power

void loop()                   

{

 digitalWrite(ledPin, HIGH);   // set the LED on
 delay(1000);                  // wait for a second
 digitalWrite(ledPin, LOW);    // set the LED off
 delay(1000);                  // wait for a second
}

 

Task 12 - Single LED Blink - Timing Variation:


Same as above program with minor change, after every 10 blinks led turns off for 10 seconds and then carries on blinking

void loop()
{

for (int i = 0; i <= 10; i++){  // blink for 10 times

digitalWrite(ledPin, HIGH);   // set the LED on
 delay(1000);                  // wait for a second
 digitalWrite(ledPin, LOW);    // set the LED off
 delay(1000);              // wait for a second
}
 delay(10000);         //wait 10 seconds
}


Task 13 - Led mostly off Program:

Initialization code same as classic blink:
Led on for 1 second, off for 10
void loop()                   
{

 digitalWrite(ledPin, HIGH);   // set the LED on
 delay(1000);                  // wait for a second
 digitalWrite(ledPin, LOW);    // set the LED off
 delay(10000);                  // wait for a second
 Task 14 - Led mostly on Program:

Initialization code same as classic blink:
Led on for 10 seconds, off for 1

void loop()                   
{

 digitalWrite(ledPin, HIGH);   // set the LED on
 delay(10000);                  // wait for a second
 digitalWrite(ledPin, LOW);    // set the LED off
 delay(1000);                  // wait for a second

Task 15 - External LED

Code Same as above examples however uses an external LED placed on breadboard and connected to pin 13 of the arduino in conjunction with a 330ohm current limiting resistor.


Task 16 - Classic 2 LED

Classic 2 LED blink program:

By David Cuartielles. Adapted by Peter Brook
based on an orginal by H. Barragan for the Wiring i/o board
*/
int ledPin = 13; // LED connected to digital pin 13
int redLedPin = 12; // LED connected to digital pin 13
int del =500;
// The setup() method runs once, when the sketch starts
void setup() {
// initialize the digital pin as an output:
pinMode(ledPin, OUTPUT);
pinMode(redLedPin, OUTPUT);
}
// the loop() method runs over and over again,
// as long as the Arduino has power
void loop()
{
digitalWrite(ledPin, HIGH); // set the LED on
digitalWrite(redLedPin, LOW); // set the LED Off
delay(del); // wait
digitalWrite(ledPin, LOW); // set the LED off
digitalWrite(redLedPin, HIGH); // set the LED on
delay(del); // wait
}

Task 17 - 2 LED's blinking in unison


Same basic program as above however changes made to loop segment so LED's blink in unison:

void loop()
{
digitalWrite(ledPin, HIGH); // set the LED on
digitalWrite(redLedPin, HIGH); // set the LED on
delay(del); // wait
digitalWrite(ledPin, LOW); // set the LED off
digitalWrite(redLedPin, LOW); // set the LEDoff
delay(del); // wait
}

Task 18 - 2 LED's Individual speed


Individual speed control for LED's:
Using internal running timer in mills as reference:
 --------------------------------------------------------
Thanks to Arduino language reference: 
--------------------------------------------------------

int redLed = 7; // define red led
int yellowLed = 6; // define yellow led
unsigned long time;

int ledStateRed = LOW;             // ledState used to set the LED
long previousTimeRed = 0;
int intervalRed = 10000;

int ledStateYellow = LOW;             // ledState used to set the LED
long previousTimeYellow = 0;
int intervalYellow = 250;

void setup(){
pinMode(redLed, OUTPUT); // red led setup as output
pinMode(yellowLed, OUTPUT); // yellow led setup as output

}

void loop()
{
   
   time = millis();
  
   if(time - previousTimeRed > intervalRed) { //Time running

    previousTimeRed = time; 

    if (ledStateRed == LOW)
      ledStateRed = HIGH;
    else
      ledStateRed = LOW;


    digitalWrite(redLed, ledStateRed);
  }
 
  if(time - previousTimeYellow > intervalYellow) {

    previousTimeYellow= time; 

    if (ledStateYellow == LOW)
      ledStateYellow = HIGH;
    else
      ledStateYellow = LOW;

    digitalWrite(yellowLed, ledStateYellow);
  }

}


Task 19 - ASCII Printing program:

Copied from :http://arduino.cc/en/Tutorial/ASCIITable  and run on Arduino uno