Friday 30 November 2012

PIC24FJ64GB002 hello world on Microstick II


Had to document the fact i started to dig into the series 24 of the PICs (PIC24FJ64GB002), after some time in the PIC16F (887 and 886 mainly) and some PIC18.

This time, im using the Microstick II board.
My intention is to start looking at the USB stack !!

/*
**
** Hello1.c my first PIC24fj program in C
*/
#include <p24FJ64GB002.h>

// this is the config bits that work for me on my microstick II
_CONFIG1( JTAGEN_OFF        // disable JTAG interface
        & GCP_OFF           // disable general code protection
        & GWRP_OFF          // disable flash write protection
        & ICS_PGx2          // ICSP interface (2=default)
        & FWDTEN_OFF)       // disable watchdog timer

#define DELAY   1600       
// use just 10 to speed up the simulation with MPLAB SIM 

unsigned char count;    // an 8-bit counter (also see chapt.4)

main()
{
    // init control registers
    TRISA = 0xff00; // all PORTA as output
    T1CON = 0x8030; // TMR1 on, prescale 1:256 Tclk/2
    
    // init counter
    count = 0;
    
    // main application loop
    while( 1)
    {
        // increment counter value
        count = count+1;
        
        // output counter value and wait 
        PORTA = count;  
        TMR1 = 0;
        while ( TMR1 < DELAY)
        {
        }
    } // main loop// main



Wednesday 28 November 2012

data logging on an SD card v.2

Even though this kind of logging need'nt be too accurate, i still decided to leave an interrupt driven code variation for time keeping.



/*  A simple data logger for the Arduino   */
/*  After some studying of both codes, i came up with this. 
 This is the v.2, with an timer interrupt to keep time, as 
 oposed to the millis() of arduino !
 These example code is in the public domain.
 http://dubworks.blogspot.co.uk/2012/11/moisture-and-temperature-sensors-data.html
 https://github.com/adafruit/Light-and-Temp-logger
 http://www.engblaze.com/microcontroller-tutorial-avr-and-arduino-timer-interrupts/ */
// this code sets up timer CTC for a 1s  @ 16Mhz Clock
// avr-libc library includes
#include <avr/io.h>
#include <avr/interrupt.h>
#include <SD.h>
// constants won't change. Used here to 
// set pin numbers:
const int ledPin =  13;      // the number of the LED pin
// the digital pins that connect to the LEDs
#define redLEDpin 2
#define greenLEDpin 3
int seconds = 0;
int minutes = 0;
int hour = 0;
int day = 0;
int week=0;
// Variables will change:
int ledState = LOW;             // ledState used to set the LED
int logState = LOW;
// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
int Hours_interval = 0;         // Hours interval 
int Minutes_interval = 0;       // Hours interval 
int log_Minutes_interval = 1;          // interval in mnts at which to log
int log_Hours_interval =4;            // interval in hours at which to log
#define ECHO_TO_SERIAL   1 // echo data to serial port
#define WAIT_TO_START    0 // Wait for serial input in setup()
// The analog pins that connect to the sensors
#define Moisture_sensor_Pin 0           // analog 0
#define tempPin 1                // analog 1
#define BANDGAPREF 14            // special indicator that we want to measure the bandgap
#define aref_voltage 3.3         // we tie 3.3V to ARef and measure it with a multimeter!
#define bandgap_voltage 1.1      // this is not super guaranteed but its not -too- off

// for the data logging shield, we use digital pin 10 for the SD cs line
const int chipSelect = 10;
// the logging file
File logfile;

void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);
  // red LED indicates error
  digitalWrite(redLEDpin, HIGH);
  while(1);
}

void setup()
{ 
  // initialize Timer1
  cli();          // disable global interrupts
  TCCR1A = 0;     // set entire TCCR1A register to 0
  TCCR1B = 0;     // same for TCCR1B
  // set compare match register to desired timer count:
  OCR1A = 15624;
  // turn on CTC mode:
  TCCR1B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR1B |= (1 << CS10);
  TCCR1B |= (1 << CS12);
  // enable timer compare interrupt:
  TIMSK1 |= (1 << OCIE1A);
  // enable global interrupts:
  sei();
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
  Serial.println();
  // use debugging LEDs
  pinMode(redLEDpin, OUTPUT);
  pinMode(greenLEDpin, OUTPUT);
#if WAIT_TO_START
  Serial.println("Type any character to start");
  while (!Serial.available());
#endif //WAIT_TO_START
  // initialize the SD card
  Serial.print("Initializing SD card...");
  // make sure that the default chip select pin is set to
  // output, even if you don't use it:
  pinMode(10, OUTPUT);
  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    error("Card failed, or not present");
  }
  Serial.println("card initialized.");
  // create a new file
  char filename[] = "LOGGER00.CSV";
  for (uint8_t i = 0; i < 100; i++) {
    filename[6] = i/10 + '0';
    filename[7] = i%10 + '0';
    if (! SD.exists(filename)) {
      // only open a new file if it doesn't exist
      logfile = SD.open(filename, FILE_WRITE); 
      break;  // leave the loop!
    }
  }
  if (! logfile) {
    error("couldnt create file");
  }  
  {
    Serial.print("Logging to: ");
    Serial.println(filename);
  }
  logfile.println("time,moisture,temp,vcc");    
#if ECHO_TO_SERIAL
  Serial.println("time,moisture,temp,vcc");
#endif //ECHO_TO_SERIAL
  // If you want to set the aref to something other than 5v
  analogReference(EXTERNAL);  
}

void log_to_sd()
{
  logState = LOW;
  //Log code to sd card 
  logfile.print(minutes);           // mnts since start
  logfile.print("mnts, "); 
  logfile.print(hour);           // hours since start
  logfile.print("hrs, ");  
  logfile.print(day);           // days since start
  logfile.print("dd, "); 
  logfile.print(week);           // weeks since start
  logfile.print("Week, ");  
#if ECHO_TO_SERIAL
  Serial.print(minutes);         // mnts since start
  Serial.print("mnts, ");  
  Serial.print(hour);         // hours since start
  Serial.print("hrs, "); 
  Serial.print(day);         // days since start
  Serial.print("dd, "); 
  Serial.print(week);         // weeks since start
  Serial.print("Week, "); 
#endif 
  analogRead(Moisture_sensor_Pin);
  delay(10); 
  int Moisture_sensor_PinReading = analogRead(Moisture_sensor_Pin);  
  analogRead(tempPin); 
  delay(10);
  int tempReading = analogRead(tempPin);    
  // converting that reading to voltage, for 3.3v arduino use 3.3, for 5.0, use 5.0
  float voltage = tempReading * aref_voltage / 1024;  
  float temperatureC = (voltage - 0.5) * 100 ;
  //float temperatureF = (temperatureC * 9 / 5) + 32; // uncomment the beggining of this line for F
  logfile.print("Moisture, ");    
  logfile.print(Moisture_sensor_PinReading);
  logfile.print("Temp, ");    
  logfile.print(temperatureC);
#if ECHO_TO_SERIAL
  Serial.print("Moisture, ");   
  Serial.print(Moisture_sensor_PinReading);
  Serial.print("Temp, ");    
  Serial.print(temperatureC);
#endif //ECHO_TO_SERIAL
  // Log the estimated 'VCC' voltage by measuring the internal 1.1v ref
  analogRead(BANDGAPREF); 
  delay(10);
  int refReading = analogRead(BANDGAPREF); 
  float supplyvoltage = (bandgap_voltage * 1024) / refReading; 

  logfile.print("Supply_V, ");
  logfile.print(supplyvoltage);
#if ECHO_TO_SERIAL
  Serial.print("Supply_V, ");   
  Serial.print(supplyvoltage);
#endif // ECHO_TO_SERIAL
  logfile.println();
#if ECHO_TO_SERIAL
  Serial.println();
#endif // ECHO_TO_SERIAL
  digitalWrite(greenLEDpin, LOW);
  // blink LED to show we are syncing data to the card & updating FAT!
  digitalWrite(redLEDpin, HIGH);
  logfile.flush();
  digitalWrite(redLEDpin, LOW);
}

void loop()
{
  // we have a working Timer
  // Routines in the loop: keeping time 
  // set the LED with the ledState of the variable:
  digitalWrite(ledPin, ledState);
  //Keeping time :60 seconds=1minute
  if (seconds==60){
    seconds=0;// Reset seconds, so we do not end up with massive numbers
    minutes = minutes += 1;//Increment 1 minute
    Minutes_interval = Minutes_interval += 1;/*Timer for variable for 
     log, in minutes*/
  }
  //keeping time: 60 minutes=1hour
  if (minutes==60){
    minutes = 0;// Reset minutes, so we do not end up with massive numbers
    hour= hour += 1;//increment 1 hour
    Hours_interval = Hours_interval += 1;/*Timer for variable for 
     log, in minutes*/
  }
  //Keeping time :24 hours = 1 day
  if (hour == 24){
    day = day += 1;//increment 1 day
    hour= 0;// Reset hours, so we do not end up with massive numbers
    minutes = 0;// Reset minutes
  }
  /*Keeping time :7 days = 1 week. 
   This is as far as i gone for logging purposes.  Can keep a quite accurate
   log of the sensors, while the deviation in time is quite minimal */
  if (day == 7 && hour== 23 && minutes == 59 && seconds==59){
    day = 0;// Reset days, so we do not end up with massive numbers
    week = week +=1;//increment 1 week
  };
  /* When the interrup timer gets activated, our log state will trigger 
   both, in turn */
  /* log_Hours_interval if hours prefered; i included both, just in case, 
   for code's readability sake */
  if ( Minutes_interval ==log_Minutes_interval ){
    Minutes_interval =0;//reset the last interval
    Hours_interval = 0; //reset the last interval
    logState = HIGH; // if the LOG is off turn it on and vice-versa:
  }
  // Actual log routine
  if (logState == HIGH){
    log_to_sd(); 
  }  
}

ISR(TIMER1_COMPA_vect)
{
  seconds= seconds += 1; // Increment one second
  // if the LED is off turn it on and vice-versa:
  if (ledState == LOW)
    ledState = HIGH;
  else
    ledState = LOW; 
}

Tuesday 27 November 2012

Moisture and temperature sensors data logging on an SD card


Moisture and Temperature sensor data logger (temperature sensor TMP36)  on an SD card ( Using SPI protocol)







/*  A simple data logger for the Arduino analog pins  */
/*  After some studying of both codes, i came up with this.
 These example code is in the public domain.
 http://dubworks.blogspot.co.uk/2012/11/moisture-and-temperature-sensors-data.html
 https://github.com/adafruit/Light-and-Temp-logger
 http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
 */
#include <SD.h>
// constants won't change. Used here to 
// set pin numbers:
const int ledPin =  13;      // the number of the LED pin
// the digital pins that connect to the LEDs
#define redLEDpin 2
#define greenLEDpin 3
int seconds = 0;
int minutes = 0;
int hour = 0;
int day = 0;
int week=0;
// Variables will change:
int ledState = LOW;             // ledState used to set the LED
int logState = LOW;
long previousMillis = 0;        // will store last time time increment was updated
// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 1000;// interval at which to increment a second (milliseconds)
int Hours_interval = 0;         // Hours interval 
int Minutes_interval = 0;       // Hours interval 
int log_Minutes_interval = 1;          // interval in mnts at which to log
int log_Hours_interval =4;            // interval in hours at which to log
#define ECHO_TO_SERIAL   1 // echo data to serial port
#define WAIT_TO_START    0 // Wait for serial input in setup()

// The analog pins that connect to the sensors
#define Moisture_sensor_Pin 0           // analog 0
#define tempPin 1                // analog 1
#define BANDGAPREF 14            // special indicator that we want to measure the bandgap

#define aref_voltage 3.3         // we tie 3.3V to ARef and measure it with a multimeter!
#define bandgap_voltage 1.1      // this is not super guaranteed but its not -too- off


// for the data logging shield, we use digital pin 10 for the SD cs line
const int chipSelect = 10;

// the logging file
File logfile;

void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);

  // red LED indicates error
  digitalWrite(redLEDpin, HIGH);

  while(1);
}


void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);

  Serial.begin(9600);
  Serial.println();

  // use debugging LEDs
  pinMode(redLEDpin, OUTPUT);
  pinMode(greenLEDpin, OUTPUT);

#if WAIT_TO_START
  Serial.println("Type any character to start");
  while (!Serial.available());
#endif //WAIT_TO_START

  // initialize the SD card
  Serial.print("Initializing SD card...");
  // make sure that the default chip select pin is set to
  // output, even if you don't use it:
  pinMode(10, OUTPUT);
  // see if the card is present and can be initialized:
  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    error("Card failed, or not present");
  }

  Serial.println("card initialized.");

  // create a new file
  char filename[] = "LOGGER00.CSV";
  for (uint8_t i = 0; i < 100; i++) {
    filename[6] = i/10 + '0';
    filename[7] = i%10 + '0';
    if (! SD.exists(filename)) {
      // only open a new file if it doesn't exist
      logfile = SD.open(filename, FILE_WRITE); 
      break;  // leave the loop!
    }
  }
  if (! logfile) {
    error("couldnt create file");
  }
  {
    Serial.print("Logging to: ");
    Serial.println(filename);
  }
  logfile.println("time,moisture,temp,vcc");    
#if ECHO_TO_SERIAL
  Serial.println("time,moisture,temp,vcc");
#endif //ECHO_TO_SERIAL

  // If you want to set the aref to something other than 5v
  analogReference(EXTERNAL);  
}

void loop()
{
  // here is where you'd put code that needs to be running all the time.

 
  unsigned long currentMillis = millis();


  if (seconds==60){
    seconds=0;
    minutes = minutes += 1;
    // hour= hour += 1;
    Minutes_interval = Minutes_interval += 1;
  }
  if (minutes==60){
    minutes = 0;
    hour= hour += 1;
    Minutes_interval =0;
Hours_interval = Hours_interval += 1;   }   if (hour == 24){     day = day += 1;     hour= 0;     minutes = 0;   }   if (day == 7 && hour== 23 && minutes == 59 && seconds==59){     day = 0;     week = week +=1;   }   if(currentMillis - previousMillis > interval) {     // save the last time you incremented     previousMillis = currentMillis;        seconds= seconds += 1;     // if the LED is off turn it on and vice-versa:     if (ledState == LOW)       ledState = HIGH;     else       ledState = LOW;     // set the LED with the ledState of the variable:     digitalWrite(ledPin, ledState);   }   //log_Hours_interval if hours prefered   if ( Hours_interval ==log_Hours_interval ){     Minutes_interval =0;//reset the last interval     Hours_interval = 0; //reset the last interval     logState = HIGH; // if the LOG is off turn it on and vice-versa:   }   if (logState == HIGH){     logState = LOW;     //Log code to sd card     logfile.print(minutes); // mnts since start     logfile.print("mnts, ");     logfile.print(hour); // hours since start     logfile.print("hrs, ");     logfile.print(day); // days since start     logfile.print("dd, ");     logfile.print(week); // weeks since start     logfile.print("Week, "); #if ECHO_TO_SERIAL     Serial.print(minutes); // mnts since start     Serial.print("mnts, ");     Serial.print(hour); // hours since start     Serial.print("hrs, ");     Serial.print(day); // days since start     Serial.print("dd, ");     Serial.print(week); // weeks since start     Serial.print("Week, "); #endif      analogRead(Moisture_sensor_Pin);     delay(10);     int Moisture_sensor_PinReading = analogRead(Moisture_sensor_Pin);     analogRead(tempPin);     delay(10);     int tempReading = analogRead(tempPin);     // converting that reading to voltage, for 3.3v arduino use 3.3, for 5.0, use 5.0     float voltage = tempReading * aref_voltage / 1024;     float temperatureC = (voltage - 0.5) * 100 ;     //float temperatureF = (temperatureC * 9 / 5) + 32; // uncomment the beggining of this line for F     logfile.print("Moisture, ");     logfile.print(Moisture_sensor_PinReading);     logfile.print("Temp, ");     logfile.print(temperatureC); #if ECHO_TO_SERIAL     Serial.print("Moisture, ");     Serial.print(Moisture_sensor_PinReading);     Serial.print("Temp, ");     Serial.print(temperatureC); #endif //ECHO_TO_SERIAL     // Log the estimated 'VCC' voltage by measuring the internal 1.1v ref     analogRead(BANDGAPREF);     delay(10);     int refReading = analogRead(BANDGAPREF);     float supplyvoltage = (bandgap_voltage * 1024) / refReading;     logfile.print("Supply_V, ");     logfile.print(supplyvoltage); #if ECHO_TO_SERIAL     Serial.print("Supply_V, ");     Serial.print(supplyvoltage); #endif // ECHO_TO_SERIAL     logfile.println(); #if ECHO_TO_SERIAL     Serial.println(); #endif // ECHO_TO_SERIAL     digitalWrite(greenLEDpin, LOW);     // blink LED to show we are syncing data to the card & updating FAT!     digitalWrite(redLEDpin, HIGH);     logfile.flush();     digitalWrite(redLEDpin, LOW);   } }

Friday 23 November 2012

Chips die

I just had to share these beauties with you all !!
Pictures( with much more on their website) are from http://zeptobars.ru/en/
First we have 
the 
STMicroelectronics NE556

chip - dual 555 timer.

74HC595 — 8-bit shift register:



ATmega8
— 
one of the most popular 8-bit microcontrollers.


LM1117 

— 

low-dropout linear regulator:


Sunday 11 November 2012

DubWorks Alpha II Arduino Dub siren Open Source Code



Some ideas from 
http://www.beavisaudio.com/projects/digital/ArduinoPunkConsole/
and
http://mechomaniac.com/ArduinoNoiseBoxSynth



/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Licensed under the BSD 3-Clause license:
http://www.opensource.org/licenses/BSD-3-Clause
Copyright (c) 2012, http://dubworks.blogspot.com
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the RobotGrrl.com nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * DubWorks Alpha II  * After seveveral weeks of research, and the idea of using a 4046 
VCO along with the Arduino http://dubworks.blogspot.co.uk
 * a Pot to control the rate of the PWM
 * a Pot to fine tune the rate of the PWM
 and another at the entrance of the 4046
 * Circuits:
 * Potentiometer X2 attached to analog input #
 * center pin of the Potentiometer to the analog pin
 * one side pin (either one) to ground
 * the other side pin to +5V
 * digital output 11 out conected to a 4046 VCO 
 * Also Pin 11 on board Audio out
 * * * The LCD circuit: * * *  
 * LCD RS pin to digital pin 8
 * LCD Enable pin to digital pin 9
 * LCD D4 pin to digital pin 4
 * LCD D5 pin to digital pin 5
 * LCD D6 pin to digital pin 6
 * LCD D7 pin to digital pin 7
 * LCD R/W pin to ground
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 */

#include <avr/io.h>
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
// Variables will change:
int UpdateDisplayState ;             // DisplayState used to set the Display
long previousMillis = 0;        // will store last time LCD was updated;Siren also uses it !
// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
int interval = 500;           // interval at which to update the LCD display
// interval at which to update display (milliseconds)
const int MAX_Freq = 3000; //max Frequency of the siren wail
const int MIN_Freq = 70; //min Frequency of the siren wail


int Freq_SKIP ; //Frequency skip variable
int pitchval = 1;
const int PIN_RATE = 0;  // variable for speed rate
const int PIN_ModePot = 1;  // Analog port to read values for Menu of Mode
const int PIN_ModeAdjust = 2;  //Fine tuning of sweep changes of pattern
const int PIN_PwmOut = 11;    // Pin 11 on board Audio out
int MODE_CUT = 0; 
int MODE_SOFTCUT = 125;
int MODE_SqWave = 250;
int MODE_UpDOWN = 375;
int MODE_RANDOM = 500;
int MODE_Freq = 625;
int MODE_Adjustable = 750;
int MODE_SIREN = 825;
int RAND_LOW_THRESHOLD = 30;
int RAND_HIGH_THRESHOLD = 255;

int tempoValue = 0;
int AdjustValue =0 ;
int PatternMode = 0;
int Adjust = 0;
int tempo = 0;
int oldTempo;
int oldPatternMode;

void setup ()
{
  pinMode (PIN_PwmOut, OUTPUT); /* Pin 11 on board */
  pinMode (PIN_RATE, INPUT);
  pinMode (PIN_ModePot, INPUT);
  pinMode (PIN_ModeAdjust, INPUT);

  randomSeed (analogRead (0));

  lcd.begin(16, 2);  // set up the LCD's number of columns and rows
  LCD_Init();        // Init our lcd
  StartupMessage();  // our starting up message
}

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

  bool controlsChanged = false;
  tempo = analogRead (PIN_RATE) * 1.9;

  if (currentMillis - previousMillis > interval) {
    // save the last time you updated the LCD 
    previousMillis = currentMillis;   

    // if the UpdateDisplayState is off turn it on and vice-versa:
    if (UpdateDisplayState == 0){
      UpdateDisplayState = 1;
      UpdateDisplay();    //  update the LCD display
    }
    else {
      UpdateDisplayState = 0;
    }
  }
  else if(PatternMode == MODE_CUT)
  {
    // chop Wave mode
    digitalWrite (PIN_PwmOut, HIGH); //Pin 11 on board, digitalWrite (PIN_PwmOut, HIGH);
    delay (tempo);
    digitalWrite (PIN_PwmOut, LOW);  //Pin 11 on board , digitalWrite(PIN_PwmOut, LOW);
    delay (tempo);
    CheckControls();
  }
  else if (PatternMode == MODE_SOFTCUT)
  {
    analogWrite (PIN_PwmOut, 25);
    delay (tempo/9);
    analogWrite (PIN_PwmOut, 50);
    delay (tempo/9);
    analogWrite (PIN_PwmOut, 75);
    delay (tempo/9);
    analogWrite (PIN_PwmOut, 100);
    delay (tempo/9);
    analogWrite (PIN_PwmOut, 150);
    delay (tempo/9);
    analogWrite (PIN_PwmOut, 180);
    delay (tempo/9);
    analogWrite (PIN_PwmOut, 255);
    delay (tempo/9 );

    CheckControls();
  }
  else if (PatternMode == MODE_SqWave)
  {
    int counter = 0;
    // fake sine Wave mode
    for(counter = 0 ; counter <= 255; counter+=20)
    {
      analogWrite(PIN_PwmOut, counter);
      if (Adjust >500)
      {
        delay (tempo/20);
      }
      else
      {
        delay (tempo/40);
        analogWrite(PIN_PwmOut, 125);
        delay (tempo/20);
      }
      CheckControls();
    }
    for (counter = 0; counter >= 100; counter-20)
    {
      analogWrite (PIN_PwmOut, counter);
      if (Adjust >500)
      {
        delay (tempo/20);
      }
      else
      {
        delay (tempo/40);
        analogWrite(PIN_PwmOut, 125);

      }
      CheckControls();//CheckControls();
    }

  }
  else if (PatternMode == MODE_RANDOM)
  {
    // random mode, get a random number between thresholds
    int randNumber = random(RAND_LOW_THRESHOLD, RAND_HIGH_THRESHOLD);
    analogWrite (PIN_PwmOut, randNumber);
    delay (tempo/2);
    analogWrite (PIN_PwmOut, 255 - randNumber);
    delay (tempo/2);
    CheckControls();
  }

  else if (PatternMode == MODE_Freq)
  {
    int randNumber = random(Adjust,Adjust*2);
    Freqout (randNumber, tempo);
    CheckControls();
  }
  else if (PatternMode == MODE_UpDOWN)
  {
    int counter = 0;

    for (counter = 0; counter <= 255; counter += 125)
    {
      analogWrite (PIN_PwmOut, counter);
      delay (tempo/10);
    }
    for (counter = 255; counter >=0; counter -= 125)
    {
      analogWrite (PIN_PwmOut, counter);
      delay (tempo/10);
      CheckControls();
    }
  }
  else if (PatternMode == MODE_Adjustable)
  {
    int fixed = analogRead (PIN_ModeAdjust);
    Freqout (fixed, tempo/2);
    Freqout (1024-fixed, tempo/2);
    CheckControls();
  }
  else if (PatternMode == MODE_SIREN)
  {
    siren();
    CheckControls();
  }
}






void siren()
{
  CheckControls(); //check controls to set mode
  updateFreqSkip(); //updates our Frequency sweeping in the siren 
  unsigned long siren_start_time = millis(); //attaches start time to current millis
  int Freq; //current Frequency at sweep

  do
  {
    for (Freq=MIN_Freq; Freq<=MAX_Freq; Freq+=Freq_SKIP) /* Attributing the values to Freq 
     min and max values, and add the frequency skip value*/
    {
      tone(PIN_PwmOut, Freq); /* Tone on our pin with selected frequency */
      delay(tempo/10);  /* delay with the value given by the variable tempo on CheckControls() */
      updateFreqSkip();  /* as controls might have changed the value of frequencu sweep, we check it again */

    }
    CheckControls();  /* calling void CheckControls() to check all analog imput states */

    for (Freq=MAX_Freq; Freq>=MIN_Freq; Freq-=Freq_SKIP)
    {
      tone(PIN_PwmOut, Freq);  /* Tone on our pin with selected frequency */
      delay(tempo/10);  /* delay with the value given by the variable tempo on CheckControls() */
      updateFreqSkip();  /* as controls might have changed the value of frequencu sweep, we check it again */
    }
    CheckControls();  /* calling void CheckControls() to check all analog imput states */

  }
  while (millis() - siren_start_time < 5000L);
}

void updateFreqSkip() //creating a function we can call that updates the Freq_SKIP
{
  if (PIN_RATE >= 800) //up to analog value (A0) of 800, fast sweep
  { 
    Freq_SKIP = 20 ;
  }
  else 
  {
    Freq_SKIP = 40;  //slow sweep above A0 value of 800
  }
}





void UpdateDisplay()
{
  lcd.clear();
  lcd.print ("Rate:");
  lcd.print (tempoValue);
  lcd.print (" Adj:");
  lcd.print (AdjustValue);
  lcd.setCursor(0, 1);
  // Update the display and the status LEDs with the current mode
  if (PatternMode == MODE_CUT)
  {
    lcd.print (" Cut");
  }
  else if (PatternMode == MODE_SOFTCUT)
  {
    lcd.print (" Soft Cut");
  }
  else if (PatternMode == MODE_SqWave)
  {
    lcd.print (" Sq Wave");
  }
  else if (PatternMode == MODE_RANDOM)
  {
    lcd.print (" Random");
  }
  else if (PatternMode == MODE_UpDOWN)
  {
    lcd.print (" Up/Down");
  }
  else if (PatternMode == MODE_Freq)
  {
    lcd.print (" FreqOut");
  }
  else if (PatternMode == MODE_Adjustable)
  {
    lcd.print (" Adjustable");
  }
  else if (PatternMode == MODE_SIREN)
  {
    lcd.print (" Siren");
  }
}


void LCD_Init()
{
  lcd.print ("DubWorks Research");
  lcd.setCursor(0, 1);
  lcd.print(" Presents...");
  // delay at the end of the full loop:
  delay (2500);
  lcd.clear();
}


void CheckControls()
{
  // cache previous state
  oldTempo = tempo;
  oldPatternMode = PatternMode;

  //Analog reads necessary...Self explanatory
  tempo = analogRead (PIN_RATE);  //Rate of speed PIN_RATE is pin Analog 0
  if (tempo>=0 && tempo <=112)              // Variable until 112 = menu 1
  {
    tempoValue = 1;
  }
  else if (tempo >112 && tempo<=250)         // Variable until >112&&<=250 = menu 2
  {
    tempoValue = 2;
  }
  else if (tempo > 250 && tempo<=362)        // Variable > 250 & < 362 = menu 3
  {
    tempoValue = 3;
  }
  else if (tempo > 362 && tempo<=474)        // Variable > 362 && < 474 = menu 4
  {
    tempoValue = 4;
  }
  else if (tempo > 474 && tempo<586)        // Variable > 474 & < 586 = menu 5
  {
    tempoValue = 5;
  }
  else if (tempo >586 && tempo<=698)        // Variable >586 & < 698 = menu 6

  {
    tempoValue = 6;            
  }
  else if (tempo >698 && tempo<=710)        // Variable >698 & < 825 = menu 7
  {
    tempoValue = 7;
  }
  else if (tempo >710 && tempo<=822)                  // Variable above 710 = menu 8
  {
    tempoValue = 8;
  }
  else if (tempo >822 && tempo<=924)                // Variable above 822 = menu 9
  {
    tempoValue = 9;
  }
  else if ( tempo<=924 )                // Variable above 924 = menu 10
  {
    tempoValue = 10;
  }

  /*  Trying to keepthings neat in the display; PIN_ModeAdjust is Analog pin 2                                    
   */


  Adjust = analogRead (PIN_ModeAdjust);  //Adjust=fine tune of swing in changes

  if (Adjust>=0 && Adjust <=112)              // Variable until 125 = menu 1
  {
    AdjustValue = 1;
  }
  else if (Adjust >112 && Adjust<=250)         // Variable until 125 = menu 2
  {
    AdjustValue = 2;
  }
  else if (Adjust > 250 && Adjust<=362)        // Variable > 250 & < 375 = menu 3
  {
    AdjustValue = 3;
  }
  else if (Adjust > 362 && Adjust<=474)        // Variable > 375 && < 500 = menu 4
  {
    AdjustValue = 4;
  }
  else if (Adjust > 474 && Adjust<586)        // Variable > 500 & < 625 = menu 5
  {
    AdjustValue = 5;
  }
  else if (Adjust >586 && Adjust<=698)        // Variable >625 & < 750 = menu 6

  {
    AdjustValue = 6;            
  }
  else if (Adjust >698 && Adjust<=710)        // Variable >750 & < 825 = menu 7
  {
    AdjustValue = 7;
  }
  else if (Adjust >710 && Adjust<=822)                  // Variable above 825 = menu 7
  {
    AdjustValue = 8;
  }
  else if (Adjust >822 && Adjust<=924)                // Variable above 825 = menu 7
  {
    AdjustValue = 9;
  }
  else if ( Adjust<=924 )                // Variable above 825 = menu 7
  {
    AdjustValue = 10;
  }
  /*  Menu pot on Anaog Pin 1                                   
   */
  int v = analogRead (PIN_ModePot);  //Analog read to give value for menu variable
  if (v >=0 && v <=125)              // Variable until 125 = menu 1
  {
    PatternMode = MODE_CUT;
  }
  else if (v >125 && v<=250)         // Variable until 125 = menu 2
  {
    PatternMode = MODE_SOFTCUT;
  }
  else if (v > 250 && v<=375)        // Variable > 250 & < 375 = menu 3
  {
    PatternMode = MODE_SqWave;
  }
  else if (v > 375 && v<=500)        // Variable > 375 && < 500 = menu 4
  {
    PatternMode = MODE_UpDOWN;
  }
  else if (v > 500 && v<625)        // Variable > 500 & < 625 = menu 5
  {
    PatternMode = MODE_RANDOM;
  }
  else if (v >625 && v<=750)        // Variable >625 & < 750 = menu 6

  {
    PatternMode = MODE_Freq;            
  }
  else if (v >750 && v<=825)        // Variable >750 & < 825 = menu 7
  {
    PatternMode = MODE_Adjustable;
  }
  else if (v >825)                  // Variable above 825 = menu 8
  {
    PatternMode = MODE_SIREN;
  }
}


//Freqout code by Paul Badger
// Freq - Frequency value
// t - time duration of tone
void Freqout(int Freq, int t)
{

  int hperiod; //calculate 1/2 period in us
  long cycles, i;

  // subtract 7 us to make up for digitalWrite overhead - determined empirically
  hperiod = (500000 / ((Freq - 7) * pitchval));

  // calculate cycles
  cycles = ((long)Freq * (long)t) / 1000; // calculate cycles

  for (i=0; i<= cycles; i++)
  { // play note for t ms
    digitalWrite (PIN_PwmOut, HIGH); //Pin 11 on board, digitalWrite (PIN_PwmOut, HIGH);
    delayMicroseconds(hperiod);
    digitalWrite(PIN_PwmOut, LOW);//Pin 11 on board, digitalWrite (PIN_PwmOut, HIGH);  //digitalWrite(PIN_PwmOut, LOW);
    delayMicroseconds(hperiod - 1); // - 1 to make up for fractional microsecond in digitaWrite overhead
  }
}


// Set up the boot up message, this only needs to be
// flashed once
void StartupMessage()
{
  lcd.clear();
  lcd.print ("DubWorks Alpha II");
  lcd.setCursor(0, 1);
  lcd.print("    Rev.1");
  // delay at the end of the full loop:
  delay(2000);
  for (int positionCounter = 0; positionCounter < 16; positionCounter++) {
    // scroll one position left:
    lcd.scrollDisplayLeft(); 
    // wait a bit:
    delay(500);
  }

  lcd.clear();
  lcd.setCursor(0, 1);
  lcd.print(" Loading...");
  // delay at the end of the full loop:
  delay(2000);
  lcd.clear();
}

*UPDATE-This code was part of a bigger project, but here it is a schematic you can test it with. Sound is continuous, as the switch was provided by other part of the circuit, but you can still have fun testing it, if you wish to. 
~click on image for better viewing

* * The LCD circuit: * * *  
 * LCD RS pin to digital pin 8
 * LCD Enable pin to digital pin 9
 * LCD D4 pin to digital pin 4
 * LCD D5 pin to digital pin 5
 * LCD D6 pin to digital pin 6
 * LCD D7 pin to digital pin 7
 * LCD R/W pin to ground
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)