HaydnAllbutt.com.au header image 2

Some Arduino Code for Class

September 25th, 2018 · No Comments

Simple RGB LED Code

int redLedPin = 10;
int greenLedPin = 9;
int blueLedPin = 11;

void setup() {
pinMode(redLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(blueLedPin, OUTPUT);
}

void loop() {
analogWrite(blueLedPin, 255);
analogWrite(greenLedPin, 80);
analogWrite(redLedPin, 255);

delay(500);
}

 

LED RGB Code with a colour change loop

/*
Adafruit Arduino – Lesson 3. RGB LED
*/

int redPin = 11;
int greenPin = 10;
int bluePin = 9;

void setup()
{
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}

void loop()
{
setColor(255, 0, 0); // red
delay(50);
setColor(0, 255, 0); // green
delay(50);
setColor(0, 0, 255); // blue
delay(50);
setColor(255, 255, 0); // yellow
delay(50);
setColor(80, 0, 80); // purple
delay(50);
setColor(0, 255, 255); // aqua
delay(50);
}

void setColor(int red, int green, int blue)
{
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}

 

Frequencies for Musical Notes

https://pages.mtu.edu/~suits/notefreqs.html

 

Simple Tone – Play once

For this project try to design a piece of music.  You will need to work out how long you will play each of the note types, and how long the space between each note will be.

Code:

const int buzzer = 9; //buzzer to arduino pin 9

void setup(){
pinMode(buzzer, OUTPUT); // Set buzzer – pin 9 as an output

tone(buzzer, 500); // Send 1KHz sound signal…
delay(1000); // …for 1 sec
noTone(buzzer); // Stop sound…
delay(500); // …for 1sec

 

tone(buzzer, 250); // Send 1KHz sound signal…
delay(1000); // …for 1 sec
noTone(buzzer); // Stop sound…
delay(1000); // …for 1sec

}

void loop(){

}

Twinkle Twinkle

int speakerPin = 11;

int length = 15; // the number of notes

//twinkle twinkle little star

char notes[] = “ccggaag ffeeddc ggffeed ggffeed ccggaag ffeeddc “; // a space represents a rest

int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };

int tempo = 300;

void playTone(int tone, int duration) {

for (long i = 0; i < duration * 1000L; i += tone * 2) {

digitalWrite(speakerPin, HIGH);

delayMicroseconds(tone);

digitalWrite(speakerPin, LOW);

delayMicroseconds(tone);

}

}

 

void playNote(char note, int duration) {

char names[] = { ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘a’, ‘b’, ‘C’ };

int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };

// play the tone corresponding to the note name

for (int i = 0; i < 8; i++) {

if (names[i] == note) {

playTone(tones[i], duration);

}

}

}

void setup() {

pinMode(speakerPin, OUTPUT);

}

 

void loop() {

for (int i = 0; i < length; i++) {

if (notes[i] == ‘ ‘) {

delay(beats[i] * tempo); // rest

} else {

playNote(notes[i], beats[i] * tempo);

}

// pause between notes

delay(tempo / 2);

}

}

 

 

Tags: Uncategorized