0% found this document useful (0 votes)
153 views153 pages

Curs Ultim Ardruino

The document contains code examples demonstrating various functions of an Arduino board including reading from a potentiometer and displaying the value on a screen, blinking an LED, reading a push button, fading an LED brightness, reading an analog voltage input, blinking an LED based on a timing function, turning an LED on/off with a push button, debouncing a button, using INPUT_PULLUP with pinMode(), counting button presses, using a tone keyboard with multiple sensors, and playing melodies on multiple speakers using tone().

Uploaded by

Tica Bogdan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
153 views153 pages

Curs Ultim Ardruino

The document contains code examples demonstrating various functions of an Arduino board including reading from a potentiometer and displaying the value on a screen, blinking an LED, reading a push button, fading an LED brightness, reading an analog voltage input, blinking an LED based on a timing function, turning an LED on/off with a push button, debouncing a button, using INPUT_PULLUP with pinMode(), counting button presses, using a tone keyboard with multiple sensors, and playing melodies on multiple speakers using tone().

Uploaded by

Tica Bogdan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 153

G:\aldruino\arduinoSOFTULBUN\examples\

1)citirea de pe un potentiometru si afisare pe ecran


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

void loop() {

// CITESC DE PE INTRAREA analog pin 0:


int sensorValue = analogRead(A0);
// AFISEZ VALOAREA DE PE PIN ZERO :
Serial.println(sensorValue);
delay(1);
}

2) stingrea si aprinderea unui led


void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}

//se repeta stingerea si aprinderea unui led


void loop() {
digitalWrite(LED_BUILTIN, HIGH); // se aprinde ledul
delay(1000); // sta aprinns 1000 de milisecunde
digitalWrite(LED_BUILTIN, LOW); // se stinge
delay(1000); // sta stins 1000 de milisecunde
}

3) citirea unui distribuitor de semnal


int pushButton = 2;

void setup() {

Serial.begin(9600);

pinMode(pushButton, INPUT);
}

void loop() {

int buttonState = digitalRead(pushButton);

Serial.println(buttonState);
delay(1);
}

4)
int led = 9;
int brightness = 0;
int fadeAmount = 5;
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
analogWrite(led, brightness);
brightness = brightness + fadeAmount;
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
delay(30);
}

5)
CITIREA UNEI INTRARI DE TENSIUNE CA VOLTAJ SI AFISARE
void setup() {

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

int sensorValue = analogRead(A0);

float voltage = sensorValue * (5.0 / 1023.0);

Serial.println(voltage);
}

CAPITOLUL II
21) CLIPIREA UNUI LED DUPA VALORILE UNEI FUNCTII
const int ledPin = LED_BUILTIN;// the number of the LED pin
int ledState = LOW;
unsigned long previousMillis = 0;
// constants won't change:
const long interval = 1000;
void setup() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(ledPin, ledState);
}
}

22)
Buton de stingere si aprindere a unui led
const int buttonPin = 2;
const int ledPin = 13;
// variables will change:
int buttonState = 0;
void setup() {
pinMode(ledPin, OUTPUT);

pinMode(buttonPin, INPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
// turn LED on: digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}

23)filtrarea stingerii uni led de la un buton


const int buttonPin = 2;
const int ledPin = 13;
int ledState = HIGH;
int buttonState;
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
}
void loop() {
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
// only toggle the LED if the new button state is HIGH
if (buttonState == HIGH) {
ledState = !ledState;
}
}
}
digitalWrite(ledPin, ledState);
lastButtonState = reading;
}

24) Demonstram ca folosim INPUT_PULLUP cu functia pinMode().


void setup() {
Serial.begin(9600);
pinMode(2, INPUT_PULLUP);
pinMode(13, OUTPUT);
}
void loop() {
int sensorVal = digitalRead(2);
Serial.println(sensorVal);
if (sensorVal == HIGH) {
digitalWrite(13, LOW);
} else {
digitalWrite(13, HIGH);
}
}

25)
Numarare de cate ori apasam un buton
const int buttonPin = 2;
const int ledPin = 13;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState != lastButtonState) {

if (buttonState == HIGH) {
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
} else {
Serial.println("off");
}

delay(50);
}
lastButtonState = buttonState;
if (buttonPushCounter % 4 == 0) {
digitalWrite(
}
ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);

}
26)
Folosirea unei claviaturi audio pentru un difuzor

Fisierul de se importa numit pitches.h

Se va mentiona in sursa intre apostrosfe calea ctre acest fisier


/*************************************************
* Public Constants
*************************************************/

#define NOTE_B0 31
#define NOTE_C1 33
#define NOTE_CS1 35
#define NOTE_D1 37
#define NOTE_DS1 39
#define NOTE_E1 41
#define NOTE_F1 44
#define NOTE_FS1 46
#define NOTE_G1 49
#define NOTE_GS1 52
#define NOTE_A1 55
#define NOTE_AS1 58
#define NOTE_B1 62
#define NOTE_C2 65
#define NOTE_CS2 69
#define NOTE_D2 73
#define NOTE_DS2 78
#define NOTE_E2 82
#define NOTE_F2 87
#define NOTE_FS2 93
#define NOTE_G2 98
#define NOTE_GS2 104
#define NOTE_A2 110
#define NOTE_AS2 117
#define NOTE_B2 123
#define NOTE_C3 131
#define NOTE_CS3 139
#define NOTE_D3 147
#define NOTE_DS3 156
#define NOTE_E3 165
#define NOTE_F3 175
#define NOTE_FS3 185
#define NOTE_G3 196
#define NOTE_GS3 208
#define NOTE_A3 220
#define NOTE_AS3 233
#define NOTE_B3 247
#define NOTE_C4 262
#define NOTE_CS4 277
#define NOTE_D4 294
#define NOTE_DS4 311
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_FS4 370
#define NOTE_G4 392
#define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_AS4 466
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_CS5 554
#define NOTE_D5 587
#define NOTE_DS5 622
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_FS5 740
#define NOTE_G5 784
#define NOTE_GS5 831
#define NOTE_A5 880
#define NOTE_AS5 932
#define NOTE_B5 988
#define NOTE_C6 1047
#define NOTE_CS6 1109
#define NOTE_D6 1175
#define NOTE_DS6 1245
#define NOTE_E6 1319
#define NOTE_F6 1397
#define NOTE_FS6 1480
#define NOTE_G6 1568
#define NOTE_GS6 1661
#define NOTE_A6 1760
#define NOTE_AS6 1865
#define NOTE_B6 1976
#define NOTE_C7 2093
#define NOTE_CS7 2217
#define NOTE_D7 2349
#define NOTE_DS7 2489
#define NOTE_E7 2637
#define NOTE_F7 2794
#define NOTE_FS7 2960
#define NOTE_G7 3136
#define NOTE_GS7 3322
#define NOTE_A7 3520
#define NOTE_AS7 3729
#define NOTE_B7 3951
#define NOTE_C8 4186
#define NOTE_CS8 4435
#define NOTE_D8 4699
#define NOTE_DS8 4978
#include "G:\aldruino\arduinoSOFTULBUN\examples\02.Digital\toneKeyboard\pitches.h"
const int threshold = 10; // minimum reading of the sensors that generates a note
int notes[] = {
NOTE_A4, NOTE_B4, NOTE_C3
};
void setup() {
}
void loop() {
for (int thisSensor = 0; thisSensor < 3; thisSensor++) {
int sensorReading = analogRead(thisSensor);
if (sensorReading > threshold) {
tone(8, notes[thisSensor], 20);
}
}
}
27) Folosind tonuri cu mai multe difuzoare folosind functia tone()

Fisierul pitches.h
/*************************************************
* Public Constants
*************************************************/
#define NOTE_B0 31
#define NOTE_C1 33
#define NOTE_CS1 35
#define NOTE_D1 37
#define NOTE_DS1 39
#define NOTE_E1 41
#define NOTE_F1 44
#define NOTE_FS1 46
#define NOTE_G1 49
#define NOTE_GS1 52
#define NOTE_A1 55
#define NOTE_AS1 58
#define NOTE_B1 62
#define NOTE_C2 65
#define NOTE_CS2 69
#define NOTE_D2 73
#define NOTE_DS2 78
#define NOTE_E2 82
#define NOTE_F2 87
#define NOTE_FS2 93
#define NOTE_G2 98
#define NOTE_GS2 104
#define NOTE_A2 110
#define NOTE_AS2 117
#define NOTE_B2 123
#define NOTE_C3 131
#define NOTE_CS3 139
#define NOTE_D3 147
#define NOTE_DS3 156
#define NOTE_E3 165
#define NOTE_F3 175
#define NOTE_FS3 185
#define NOTE_G3 196
#define NOTE_GS3 208
#define NOTE_A3 220
#define NOTE_AS3 233
#define NOTE_B3 247
#define NOTE_C4 262
#define NOTE_CS4 277
#define NOTE_D4 294
#define NOTE_DS4 311
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_FS4 370
#define NOTE_G4 392
#define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_AS4 466
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_CS5 554
#define NOTE_D5 587
#define NOTE_DS5 622
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_FS5 740
#define NOTE_G5 784
#define NOTE_GS5 831
#define NOTE_A5 880
#define NOTE_AS5 932
#define NOTE_B5 988
#define NOTE_C6 1047
#define NOTE_CS6 1109
#define NOTE_D6 1175
#define NOTE_DS6 1245
#define NOTE_E6 1319
#define NOTE_F6 1397
#define NOTE_FS6 1480
#define NOTE_G6 1568
#define NOTE_GS6 1661
#define NOTE_A6 1760
#define NOTE_AS6 1865
#define NOTE_B6 1976
#define NOTE_C7 2093
#define NOTE_CS7 2217
#define NOTE_D7 2349
#define NOTE_DS7 2489
#define NOTE_E7 2637
#define NOTE_F7 2794
#define NOTE_FS7 2960
#define NOTE_G7 3136
#define NOTE_GS7 3322
#define NOTE_A7 3520
#define NOTE_AS7 3729
#define NOTE_B7 3951
#define NOTE_C8 4186
#define NOTE_CS8 4435
#define NOTE_D8 4699
#define NOTE_DS8 4978
Se precizeaza de unde se importa fisierul G:\aldruino\arduinoSOFTULBUN\examples\02.Digital\
toneMelody\pitches.h

#include "G:\aldruino\arduinoSOFTULBUN\examples\02.Digital\toneMelody\pitches.h"
int melody[] = {
NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
int noteDurations[] = {
4, 8, 8, 4, 4, 4, 4, 4
};
void setup() {
for (int thisNote = 0; thisNote < 8; thisNote++) {
int noteDuration = 1000 / noteDurations[thisNote];
tone(8, melody[thisNote], noteDuration);
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
noTone(8);
}
}
void loop() {
}

27)
void setup() {
}
void loop() {
noTone(8);
tone(6, 440, 200);
delay(200);
noTone(6);
tone(7, 494, 500);
delay(500);
noTone(7);
tone(8, 523, 300);
delay(300);
}

28)
Modificarea tonurilor dupa cum pot sa modific analog semnalul
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorReading = analogRead(A0);
Serial.println(sensorReading);
int thisPitch = map(sensorReading, 400, 1000, 120, 1500);
tone(9, thisPitch, 10);
delay(1); // delay in between reads for stability
}

Salvarea fisierelor
CAPITOLUL III
29)

const int analogInPin = A0;


const int analogOutPin = 9;
int sensorValue = 0;
int outputValue = 0;
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
}
void loop() {
sensorValue = analogRead(analogInPin);
outputValue = map(sensorValue, 0, 1023, 0, 255);
analogWrite(analogOutPin, outputValue);
Serial.print("sensor = ");
Serial.print(sensorValue);
Serial.print("\t output = ");
Serial.println(outputValue);

delay(2);
}

30)
int sensorPin = A0;
int ledPin = 13;
int sensorValue = 0;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
sensorValue = analogRead(sensorPin);
digitalWrite(ledPin, HIGH);
delay(sensorValue);
digitalWrite(ledPin, LOW);
delay(sensorValue);
}

31) Pornire si oprire leduri


const int lowestPin = 2;
const int highestPin = 13;
void setup() {
for (int thisPin = lowestPin; thisPin <= highestPin; thisPin++) {
pinMode(thisPin, OUTPUT);
}
}
void loop() {
for (int thisPin = lowestPin; thisPin <= highestPin; thisPin++) {
for (int brightness = 0; brightness < 255; brightness++) {
analogWrite(thisPin, brightness);
delay(2);
}
for (int brightness = 255; brightness >= 0; brightness--) {
analogWrite(thisPin, brightness);
delay(2);
}
delay(100);
}
}

32)
const int sensorPin = A0;
const int ledPin = 9;
int sensorValue = 0;
int sensorMin = 1023;
int sensorMax = 0;
void setup() {
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
while (millis() < 5000) {
sensorValue = analogRead(sensorPin);
if (sensorValue > sensorMax) {
sensorMax = sensorValue;
}
if (sensorValue < sensorMin) {
sensorMin = sensorValue;
}
}
digitalWrite(13, LOW);
}
void loop() {
sensorValue = analogRead(sensorPin);
sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);
sensorValue = constrain(sensorValue, 0, 255);
analogWrite(ledPin, sensorValue);
}

33)

int ledPin = 9; // LED connected to digital pin 9


void setup() {
}
void loop() {
for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
analogWrite(ledPin, fadeValue);
delay(30);
}
for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
analogWrite(ledPin, fadeValue);
delay(30);
}
}

34) Citirea mai multor intrari


const int numReadings = 10;
int readings[numReadings];
int readIndex = 0;
int total = 0;
int average = 0;
int inputPin = A0;
void setup() {
Serial.begin(9600);
for (int thisReading = 0; thisReading < numReadings; thisReading++) {
readings[thisReading] = 0;
}
}
void loop() {
total = total - readings[readIndex];
readings[readIndex] = analogRead(inputPin);
total = total + readings[readIndex];
readIndex = readIndex + 1;
if (readIndex >= numReadings) {
readIndex = 0;
}
average = total / numReadings;
Serial.println(average);
delay(1);
}

Capitolul III

35)
Demonstrarea functiilor externe
void setup() {
Serial.begin(9600);
while (!Serial) {
;
}
Serial.println("ASCII Table ~ Character Map");
}
int thisByte = 33;
void loop() {
Serial.write(thisByte);
Serial.print(", dec: ");
Serial.print(thisByte)
Serial.print(", hex: ");
Serial.print(thisByte, HEX);
Serial.print(", oct: ");
Serial.print(thisByte, OCT);
Serial.print(", bin: ");
Serial.println(thisByte, BIN);
if (thisByte == 126) {
while (true) {
continue;
}
}
thisByte++;
}

36)
const int ledPin = 9; // the pin that the LED is attached to
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
byte brightness;
if (Serial.available()) {
brightness = Serial.read();
analogWrite(ledPin, brightness);
}
}
import processing.serial.*;
Serial port;
void setup() {
size(256, 150);

println("Available serial ports:");


println(Serial.list());
select the port
}
void draw() {
for (int i = 0; i < 256; i++) {
stroke(i);
line(i, 0, i, 150);
}
as
port.write(mouseX);
}

37)
void setup() {
// initialize the serial communication:
Serial.begin(9600);
}

void loop() {
// send the value of analog input 0:
Serial.println(analogRead(A0));
delay(2);
}

import processing.serial.*;

Serial myPort;
int xPos = 1;
float inByte = 0;

void setup () {
size(400, 300);
println(Serial.list());
myPort = new Serial(this, Serial.list()[0], 9600);
:
myPort.bufferUntil('\n');

background(0);
}
void draw () {
);
line(xPos, height, xPos, height - inByte);

if (xPos >= width) {


xPos = 0;
background(0);
} else {
// increment the horizontal position:
xPos++;
}
}
void serialEvent (Serial myPort) {

String inString = myPort.readStringUntil('\n');


if (inString != null) {
inString = trim(inString);
inByte = float(inString);
println(inByte);
inByte = map(inByte, 0, 1023, 0, height);
}
}
38) maxim/minim pentru valorile unui senzor
const int sensorPin = A0;
const int ledPin = 9;

int sensorValue = 0;
int sensorMin = 1023;
int sensorMax = 0;
void setup() {
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
while (millis() < 5000) {
sensorValue = analogRead(sensorPin);

if (sensorValue > sensorMax) {


sensorMax = sensorValue;
}
if (sensorValue < sensorMin) {
sensorMin = sensorValue;
}
}

digitalWrite(13, LOW);
}
void loop() {
sensorValue = analogRead(sensorPin);
sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);
sensorValue = constrain(sensorValue, 0, 255);
analogWrite(ledPin, sensorValue);
}

39) iesire (PWM pin) cu LED.


int ledPin = 9; // LED connected to digital pin 9
void setup() {

}
void loop() {
for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
analogWrite(ledPin, fadeValue);
delay(30);
}
for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
analogWrite(ledPin, fadeValue);
delay(30);
}
}
40) multiple citiri de la o intrare analoaga
const int numReadings = 10;
int readings[numReadings];
int readIndex = 0;
int total = 0;
int average = 0;
int inputPin = A0;
void setup() {
Serial.begin(9600);
for (int thisReading = 0; thisReading < numReadings; thisReading++) {
readings[thisReading] = 0;
}
}

void loop() {
total = total - readings[readIndex];
readings[readIndex] = analogRead(inputPin);
total = total + readings[readIndex];
readIndex = readIndex + 1;
if (readIndex >= numReadings) {
readIndex = 0;
}
average = total / numReadings;
Serial.println(average);
delay(1);
}
CAPITOLUL IV
G:\aldruino\arduinoSOFTULBUN\examples\04.Communication
41) miscarea mouseului schimba lumina unui led
const int numReadings = 10;
int readings[numReadings];
int readIndex = 0;
int total = 0;
int average = 0;
int inputPin = A0;
void setup() {
Serial.begin(9600);
for (int thisReading = 0; thisReading < numReadings; thisReading++) {
readings[thisReading] = 0;
}
}

const int ledPin = 9; // the pin that the LED is attached to


void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
byte brightness;
if (Serial.available()) {
brightness = Serial.read();
analogWrite(ledPin, brightness);
}
}

43) Trimiterea unui mesaj prin MIDI ul unui instrument muzical


void setup() {
Serial.begin(31250);
}
void loop() {
for (int note = 0x1E; note < 0x5A; note ++) {
noteOn(0x90, note, 0x45);
delay(100);
noteOn(0x90, note, 0x00);
delay(100);
}
}

void noteOn(int cmd, int pitch, int velocity) {


Serial.write(cmd);
Serial.write(pitch);
Serial.write(velocity);
}

44)
Stingerea unui LED daca trimitem date spre placa Arduino si procesare cu Max/MSP.
PRIMUL PROGRAM DE RULAT
const int ledPin = 13;
int incomingByte;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
if (Serial.available() > 0) {
incomingByte = Serial.read();
if (incomingByte == 'H') {
digitalWrite(ledPin, HIGH);
}
if (incomingByte == 'L') {
digitalWrite(ledPin, LOW);
}
}
}

45x)
TRIMITEREA mai multor variabile care sa apleze o procedura
int firstSensor = 0;
int secondSensor = 0;
int thirdSensor = 0;
int inByte = 0;

void setup() {
Serial.begin(9600);
while (!Serial) {
;
}
pinMode(2, INPUT);
establishContact();
}

void loop() {
if (Serial.available() > 0) {
inByte = Serial.read();
firstSensor = analogRead(A0) / 4;
delay(10);
secondSensor = analogRead(1) / 4;
thirdSensor = map(digitalRead(2), 0, 1, 0, 255);
Serial.write(firstSensor);
Serial.write(secondSensor);
Serial.write(thirdSensor);
}
}
void establishContact() {
while (Serial.available() <= 0) {
Serial.print('A'); // send a capital A
delay(300);
}
}
46 x)
Trimiterea de mesaje ascii prin mai multe proceduri

int firstSensor = 0;
int secondSensor = 0;
int thirdSensor = 0;
int inByte = 0;
void setup() {
// start serial port at 9600 bps and wait for port to open:
Serial.begin(9600);
while (!Serial) {
;
}
pinMode(2, INPUT); // digital sensor is on digital pin 2
establishContact(); // send a byte to establish contact until receiver responds
}
void loop() {
if (Serial.available() > 0) {
inByte = Serial.read();
firstSensor = analogRead(A0);
secondSensor = analogRead(A1);
thirdSensor = map(digitalRead(2), 0, 1, 0, 255);
Serial.print(firstSensor);
Serial.print(",");
Serial.print(secondSensor);
Serial.print(",");
Serial.println(thirdSensor);
}
}
void establishContact() {
while (Serial.available() <= 0) {
Serial.println("0,0,0"); // send an initial string
delay(300);
}
}

47x)
Trimiterea mai multor variabile catre Arduino si catre calculator dar procesate de Max/MSP.

const int redPin = A0;


const int greenPin = A1;
const int bluePin = A2;

void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print(analogRead(redPin));
Serial.print(",");
Serial.print(analogRead(greenPin));
Serial.print(",");
Serial.println(analogRead(bluePin));
}

CAPITOLUL V
51)
const int ledPin = 9; // the pin that the LED is attached to
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
byte brightness;
if (Serial.available()) {
brightness = Serial.read();
analogWrite(ledPin, brightness);
}
}

52)
TRIMITERE de date si grafice pentru procesare
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(analogRead(A0));
delay(2);
}

53)
Mesaje MIDI trimise catre un port serial
void setup() {
Serial.begin(31250);
}
void loop() {
for (int note = 0x1E; note < 0x5A; note ++) {
delay(100);
noteOn(0x90, note, 0x00);
delay(100);
}
}

void noteOn(int cmd, int pitch, int velocity) {


Serial.write(cmd);
Serial.write(pitch);
Serial.write(velocity);
}
55)
Oprirea unui led LED pornirea si oprirea de catre Arduino si procesarea de catre Max/MSP.
const int ledPin = 13;
int incomingByte;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
if (Serial.available() > 0) {
incomingByte = Serial.read();
if (incomingByte == 'H') {
digitalWrite(ledPin, HIGH);
}
if (incomingByte == 'L') {
digitalWrite(ledPin, LOW);
}
}
}

56)
Apelari multiple la proceduri
int firstSensor = 0;
int secondSensor = 0;
int thirdSensor = 0;
int inByte = 0;
void setup() {
Serial.begin(9600);
while (!Serial) {
;
}
pinMode(2, INPUT);
establishContact();
}
void loop() {
if (Serial.available() > 0) {
inByte = Serial.read();
firstSensor = analogRead(A0) / 4;
delay(10);
secondSensor = analogRead(1) / 4;
thirdSensor = map(digitalRead(2), 0, 1, 0, 255);
Serial.write(firstSensor);
Serial.write(secondSensor);
Serial.write(thirdSensor);
}
}
void establishContact() {
while (Serial.available() <= 0) {
Serial.print('A'); // send a capital A
delay(300);
}
}

57)
Transmitere de parametrii prin referinta(rezultat)
int firstSensor = 0;
int secondSensor = 0;
int thirdSensor = 0;
int inByte = 0;
void setup() {
Serial.begin(9600);
while (!Serial) {
;
}
pinMode(2, INPUT);
establishContact();
}
void loop() {
if (Serial.available() > 0) {
inByte = Serial.read();
firstSensor = analogRead(A0);
secondSensor = analogRead(A1);
thirdSensor = map(digitalRead(2), 0, 1, 0, 255);
Serial.print(firstSensor);
Serial.print(",");
Serial.print(secondSensor);
Serial.print(",");
Serial.println(thirdSensor);
}
}
void establishContact() {
while (Serial.available() <= 0) {
Serial.println("0,0,0");
delay(300);
}
}

Capitolul VI
61)
Read an ADXL3xx accelerometer.
const int groundpin = 18;
const int powerpin = 19;
const int xpin = A3;
const int ypin = A2;
const int zpin = A1;

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

pinMode(groundpin, OUTPUT);
pinMode(powerpin, OUTPUT);
digitalWrite(groundpin, LOW);
digitalWrite(powerpin, HIGH);
}

void loop() {
Serial.print(analogRead(xpin));
Serial.print("\t");
Serial.print(analogRead(ypin));
Serial.print("\t");
Serial.print(analogRead(zpin));
Serial.println();
delay(100);
}

62) Detect knocks with a piezo element.


const int ledPin = 13;
const int knockSensor = A0;
const int threshold = 100;
int sensorReading = 0;
int ledState = LOW;

void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}

void loop() {

sensorReading = analogRead(knockSensor);

if (sensorReading >= threshold) {

ledState = !ledState;

digitalWrite(ledPin, ledState);

Serial.println("Knock!");
}
delay(100);
}

64)
Two-axis accelerometer.
const int xPin = 2; // X output of the accelerometer
const int yPin = 3; // Y output of the accelerometer

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

pinMode(xPin, INPUT);
pinMode(yPin, INPUT);
}

void loop() {

int pulseX, pulseY;

int accelerationX, accelerationY;

pulseX = pulseIn(xPin, HIGH);


pulseY = pulseIn(yPin, HIGH);

accelerationX = ((pulseX / 10) - 500) * 8;


accelerationY = ((pulseY / 10) - 500) * 8;

Serial.print(accelerationX);

Serial.print("\t");
Serial.print(accelerationY);
Serial.println();

delay(100);
}

64)
Detecting objects with an ultrasonic range finder.
const int pingPin = 7;

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

void loop() {

long duration, inches, cm;

pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);

pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);

inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);

Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();

delay(100);
}

long microsecondsToInches(long microseconds) {


return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {

return microseconds / 29 / 2;
}

Capitolul VII
71)
How to make an LED bar graph.
const int analogPin = A0; // the pin that the potentiometer is attached to
const int ledCount = 10; // the number of LEDs in the bar graph

int ledPins[] = {
2, 3, 4, 5, 6, 7, 8, 9, 10, 11
};

void setup() {

for (int thisLed = 0; thisLed < ledCount; thisLed++) {


pinMode(ledPins[thisLed], OUTPUT);
}
}

void loop() {

int sensorReading = analogRead(analogPin);


int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);

for (int thisLed = 0; thisLed < ledCount; thisLed++) {

if (thisLed < ledLevel) {


digitalWrite(ledPins[thisLed], HIGH);
}

else {
digitalWrite(ledPins[thisLed], LOW);
}
}
}

72)
How to control an 8x8 matrix of LEDs.
const int row[8] = {
2, 7, 19, 5, 13, 18, 12, 16
};

const int col[8] = {


6, 11, 10, 3, 17, 4, 8, 9
};

int pixels[8][8];

int x = 5;
int y = 5;

void setup() {

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


pinMode(col[thisPin], OUTPUT);
pinMode(row[thisPin], OUTPUT);

digitalWrite(col[thisPin], HIGH);
}

// initialize the pixel matrix:


for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
pixels[x][y] = HIGH;
}
}
}

void loop() {

readSensors();

refreshScreen();
}

void readSensors() {

pixels[x][y] = HIGH;

x = 7 - map(analogRead(A0), 0, 1023, 0, 7);


y = map(analogRead(A1), 0, 1023, 0, 7);

pixels[x][y] = LOW;

}
void refreshScreen() {

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

digitalWrite(row[thisRow], HIGH);

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

int thisPixel = pixels[thisRow][thisCol];

digitalWrite(col[thisCol], thisPixel);

if (thisPixel == LOW) {
digitalWrite(col[thisCol], HIGH);
}
}

digitalWrite(row[thisRow], LOW);
}
}

Capitolul VIII
81)// Add Strings together in a variety of ways.

String stringOne, stringTwo, stringThree;


void setup() {

Serial.begin(9600);
while (!Serial) {
;
}
stringOne = String("You added ");
stringTwo = String("this string");
stringThree = String();

Serial.println("\n\nAdding Strings together (concatenation):");


Serial.println();
}

void loop() {

stringThree = stringOne + 123;


Serial.println(stringThree); // prints "You added 123"

stringThree = stringOne + 123456789;


Serial.println(stringThree); // prints "You added 123456789"

stringThree = stringOne + 'A';


Serial.println(stringThree);

stringThree = stringOne + "abc";


Serial.println(stringThree);

stringThree = stringOne + stringTwo;


Serial.println(stringThree);

int sensorValue = analogRead(A0);


stringOne = "Sensor value: ";
stringThree = stringOne + sensorValue;
Serial.println(stringThree); // prints "Sensor Value: 401" or whatever value analogRead(A0) has

stringOne = "millis() value: ";


stringThree = stringOne + millis();
Serial.println(stringThree); // prints "The millis: 345345" or whatever value millis() has

while (true);
}

82)

void setup() {

Serial.begin(9600);
while (!Serial) {
;
}

Serial.println("send any byte and I'll tell you everything I can


about it");
Serial.println();
}

void loop() {

if (Serial.available() > 0) {
int thisChar = Serial.read();

Serial.print("You sent me: \'");


Serial.write(thisChar);
Serial.print("\' ASCII Value: ");
Serial.println(thisChar);

if (isAlphaNumeric(thisChar)) {
Serial.println("it's alphanumeric");
}
if (isAlpha(thisChar)) {
Serial.println("it's alphabetic");
}
if (isAscii(thisChar)) {
Serial.println("it's ASCII");
}
if (isWhitespace(thisChar)) {
Serial.println("it's whitespace");
}
if (isControl(thisChar)) {
Serial.println("it's a control character");
}
if (isDigit(thisChar)) {
Serial.println("it's a numeric digit");
}
if (isGraph(thisChar)) {
Serial.println("it's a printable character that's not white-
space");
}
if (isLowerCase(thisChar)) {
Serial.println("it's lower case");
}
if (isPrintable(thisChar)) {
Serial.println("it's printable");
}
if (isPunct(thisChar)) {
Serial.println("it's punctuation");
}
if (isSpace(thisChar)) {
Serial.println("it's a space character");
}
if (isUpperCase(thisChar)) {
Serial.println("it's upper case");
}
if (isHexadecimalDigit(thisChar)) {
Serial.println("it's a valid hexadecimaldigit (i.e. 0 - 9, a -
F, or A - F)");
}

Serial.println();
Serial.println("Give me another byte:");
Serial.println();
}
}

83)

String stringOne, stringTwo;

void setup() {

Serial.begin(9600);
while (!Serial) {
;
}

stringOne = String("Sensor ");


stringTwo = String("value");

Serial.println("\n\nAppending to a String:");
Serial.println();
}

void loop() {
Serial.println(stringOne); // prints "Sensor "

stringOne += stringTwo;
Serial.println(stringOne); // prints "Sensor value"

stringOne += " for input ";


Serial.println(stringOne); // prints "Sensor value for input"

stringOne += 'A';
Serial.println(stringOne); // prints "Sensor value for input A"

stringOne += 0;
Serial.println(stringOne); // prints "Sensor value for input A0"

stringOne += ": ";


Serial.println(stringOne); // prints "Sensor value for input"

stringOne += analogRead(A0);
Serial.println(stringOne); // prints "Sensor value for input A0: 456" or whatever analogRead(A0) is

Serial.println("\n\nchanging the Strings' values");


stringOne = "A long integer: ";
stringTwo = "The millis(): ";

stringOne += 123456789;
Serial.println(stringOne); // prints "A long integer: 123456789"

stringTwo.concat(millis());
Serial.println(stringTwo); // prints "The millis(): 43534" or whatever the value of the millis() is

while (true);
}

84)
// Change the case of a String.

void setup() {

Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

Serial.println("\n\nString case changes:");


Serial.println();
}

void loop() {

String stringOne = "<html><head><body>";


Serial.println(stringOne);
stringOne.toUpperCase();
Serial.println(stringOne);

String stringTwo = "</BODY></HTML>";


Serial.println(stringTwo);
stringTwo.toLowerCase();
Serial.println(stringTwo);
while (true);
}

85)
// Get/set the value of a specific character in a String.

void setup() {

Serial.begin(9600);
while (!Serial) {
;
}

Serial.println("\n\nString charAt() and setCharAt():");


}

void loop() {

String reportString = "SensorReading: 456";


Serial.println(reportString);

char mostSignificantDigit = reportString.charAt(15);

String message = "Most significant digit of the sensor reading is: ";
Serial.println(message + mostSignificantDigit);

Serial.println();

reportString.setCharAt(13, '=');
Serial.println(reportString);
while (true);
}

86)
// Compare Strings alphabetically.

String stringOne, stringTwo;

void setup() {

Serial.begin(9600);
while (!Serial) {
;
}

stringOne = String("this");
stringTwo = String("that");

Serial.println("\n\nComparing Strings:");
Serial.println();

void loop() {

if (stringOne == "this") {
Serial.println("StringOne == \"this\"");
}

if (stringOne != stringTwo) {
Serial.println(stringOne + " =! " + stringTwo);
}

stringOne = "This";
stringTwo = "this";
if (stringOne != stringTwo) {
Serial.println(stringOne + " =! " + stringTwo);
}

if (stringOne.equals(stringTwo)) {
Serial.println(stringOne + " equals " + stringTwo);
} else {
Serial.println(stringOne + " does not equal " + stringTwo);
}

if (stringOne.equalsIgnoreCase(stringTwo)) {
Serial.println(stringOne + " equals (ignoring case) " + stringTwo);
} else {
Serial.println(stringOne + " does not equal (ignoring case) " + stringTwo);
}

stringOne = "1";
int numberOne = 1;
if (stringOne.toInt() == numberOne) {
Serial.println(stringOne + " = " + numberOne);
}

stringOne = "2";
stringTwo = "1";
if (stringOne >= stringTwo) {
Serial.println(stringOne + " >= " + stringTwo);
}

stringOne = String("Brown");
if (stringOne < "Charles") {
Serial.println(stringOne + " < Charles");
}

if (stringOne > "Adams") {


Serial.println(stringOne + " > Adams");
}

if (stringOne <= "Browne") {


Serial.println(stringOne + " <= Browne");
}

if (stringOne >= "Brow") {


Serial.println(stringOne + " >= Brow");
}

stringOne = "Cucumber";
stringTwo = "Cucuracha";
if (stringOne.compareTo(stringTwo) < 0) {
Serial.println(stringOne + " comes before " + stringTwo);
} else {
Serial.println(stringOne + " comes after " + stringTwo);
}

delay(10000);
while (true) {
stringOne = "Sensor: ";
stringTwo = "Sensor: ";

stringOne += analogRead(A0);
stringTwo += analogRead(A5);

if (stringOne.compareTo(stringTwo) < 0) {
Serial.println(stringOne + " comes before " + stringTwo);
} else {
Serial.println(stringOne + " comes after " + stringTwo);

}
}
}
-----------------------------------------
87)
//How to initialize String objects.

void setup() {

Serial.begin(9600);
while (!Serial) {
;
}

Serial.println("\n\nString Constructors:");
Serial.println();
}
void loop() {

String stringOne = "Hello String";


Serial.println(stringOne);

stringOne = String('a');
Serial.println(stringOne);

String stringTwo = String("This is a string");


Serial.println(stringTwo);

stringOne = String(stringTwo + " with more");

Serial.println(stringOne);

stringOne = String(13);
Serial.println(stringOne);

stringOne = String(analogRead(A0), DEC);

Serial.println(stringOne);

stringOne = String(45, HEX);

Serial.println(stringOne);

stringOne = String(255, BIN);


Serial.println(stringOne);

stringOne = String(millis(), DEC);

Serial.println(stringOne);

stringOne = String(5.698, 3);


Serial.println(stringOne);

stringOne = String(5.698, 2);


Serial.println(stringOne);

while (true);

88)
//Look for the first/last instance of a character in a String.

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

Serial.println("\n\nString indexOf() and lastIndexOf() functions:");


Serial.println();
}

void loop() {

String stringOne = "<HTML><HEAD><BODY>";


int firstClosingBracket = stringOne.indexOf('>');
Serial.println("The index of > in the string " + stringOne + " is " + firstClosingBracket);

stringOne = "<HTML><HEAD><BODY>";
int secondOpeningBracket = firstClosingBracket + 1;
int secondClosingBracket = stringOne.indexOf('>', secondOpeningBracket);
Serial.println("The index of the second > in the string " + stringOne + " is " + secondClosingBracket);

stringOne = "<HTML><HEAD><BODY>";
int bodyTag = stringOne.indexOf("<BODY>");
Serial.println("The index of the body tag in the string " + stringOne + " is " + bodyTag);

stringOne = "<UL><LI>item<LI>item<LI>item</UL>";
int firstListItem = stringOne.indexOf("<LI>");
int secondListItem = stringOne.indexOf("<LI>", firstListItem + 1);
Serial.println("The index of the second list tag in the string " + stringOne + " is " + secondListItem);

int lastOpeningBracket = stringOne.lastIndexOf('<');


Serial.println("The index of the last < in the string " + stringOne + " is " + lastOpeningBracket);

int lastListItem = stringOne.lastIndexOf("<LI>");


Serial.println("The index of the last list tag in the string " + stringOne + " is " + lastListItem);

stringOne = "<p>Lorem ipsum dolor sit amet</p><p>Ipsem</p><p>Quod</p>";


int lastParagraph = stringOne.lastIndexOf("<p");
int secondLastGraf = stringOne.lastIndexOf("<p", lastParagraph - 1);
Serial.println("The index of the second to last paragraph tag " + stringOne + " is " + secondLastGraf);
while (true);
}

89)
// Examples of how to use length() in a String.

String txtMsg = "";


unsigned int lastStringLength = txtMsg.length();

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

Serial.println("\n\nString length():");
Serial.println();
}

void loop() {

while (Serial.available() > 0) {


char inChar = Serial.read();
txtMsg += inChar;
}

if (txtMsg.length() != lastStringLength) {
Serial.println(txtMsg);
Serial.println(txtMsg.length());

if (txtMsg.length() < 140) {


Serial.println("That's a perfectly acceptable text message");
} else {
Serial.println("That's too long for a text message.");
}

lastStringLength = txtMsg.length();
}
}

90)
// Get and trim the length of a String.

void setup() {

Serial.begin(9600);
while (!Serial) {
;
}

Serial.println("\n\nString length() and trim():");


Serial.println();
}

void loop() {

String stringOne = "Hello! ";


Serial.print(stringOne);
Serial.print("<--- end of string. Length: ");
Serial.println(stringOne.length());

stringOne.trim();
Serial.print(stringOne);
Serial.print("<--- end of trimmed string. Length: ");
Serial.println(stringOne.length());

while (true);
}

91)
// Replace individual characters in a String.

void setup() {

Serial.begin(9600);
while (!Serial) {
;
}

Serial.println("\n\nString replace:\n");
Serial.println();
}

void loop() {
String stringOne = "<html><head><body>";
Serial.println(stringOne);

String stringTwo = stringOne;

stringTwo.replace("<", "</");

Serial.println("Original string: " + stringOne);


Serial.println("Modified string: " + stringTwo);

String normalString = "bookkeeper";


Serial.println("normal: " + normalString);
String leetString = normalString;
leetString.replace('o', '0');
leetString.replace('e', '3');
Serial.println("l33tspeak: " + leetString);

while (true);
}

93)
// Check which characters/substrings a given String starts or ends with.
/*
String startWith() and endsWith()

Examples of how to use startsWith() and endsWith() in a String

created 27 Jul 2010


modified 2 Apr 2012
by Tom Igoe

This example code is in the public domain.

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

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

// send an intro:
Serial.println("\n\nString startsWith() and endsWith():");
Serial.println();
}

void loop() {
// startsWith() checks to see if a String starts with a particular substring:
String stringOne = "HTTP/1.1 200 OK";
Serial.println(stringOne);
if (stringOne.startsWith("HTTP/1.1")) {
Serial.println("Server's using http version 1.1");
}

// you can also look for startsWith() at an offset position in the string:
stringOne = "HTTP/1.1 200 OK";
if (stringOne.startsWith("200 OK", 9)) {
Serial.println("Got an OK from the server");
}

// endsWith() checks to see if a String ends with a particular character:


String sensorReading = "sensor = ";
sensorReading += analogRead(A0);
Serial.print(sensorReading);
if (sensorReading.endsWith("0")) {
Serial.println(". This reading is divisible by ten");
} else {
Serial.println(". This reading is not divisible by ten");
}
while (true);
}

95)
//Look for "phrases" within a given String.

void setup() {

Serial.begin(9600);
while (!Serial) {
;
}

// send an intro:
Serial.println("\n\nString substring():");
Serial.println();
}

void loop() {
String stringOne = "Content-Type: text/html";
Serial.println(stringOne);

if (stringOne.substring(19) == "html") {
Serial.println("It's an html file");
}

if (stringOne.substring(14, 18) == "text") {


Serial.println("It's a text-based file");
}

while (true);
}

96)

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

void setup() {

Serial.begin(9600);
while (!Serial) {
;
}

Serial.println("\n\nString toInt():");
Serial.println();
}

void loop() {

while (Serial.available() > 0) {


int inChar = Serial.read();
if (isDigit(inChar)) {

inString += (char)inChar;
}

if (inChar == '\n') {
Serial.print("Value:");
Serial.println(inString.toInt());
Serial.print("String: ");
Serial.println(inString);
inString = "";
}
}
}

Capitolul 10)
101)

int switchstate = 0;

void setup() {

pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);

pinMode(2, INPUT);
}

void loop() {

switchstate = digitalRead(2);

if (switchstate == LOW) {
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
digitalWrite(5, LOW);
}

else {
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(5, HIGH);

delay(250);
digitalWrite(4, HIGH);
digitalWrite(5, LOW);

delay(250);
}
}

102)

const int sensorPin = A0;

const float baselineTemp = 20.0;

void setup() {

Serial.begin(9600);

for (int pinNumber = 2; pinNumber < 5; pinNumber++) {


pinMode(pinNumber, OUTPUT);
digitalWrite(pinNumber, LOW);
}
}

void loop() {

int sensorVal = analogRead(sensorPin);


Serial.print("sensor Value: ");
Serial.print(sensorVal);

float voltage = (sensorVal / 1024.0) * 5.0;

Serial.print(", Volts: ");


Serial.print(voltage);

Serial.print(", degrees C: ");


float temperature = (voltage - .5) * 100;
Serial.println(temperature);

if (temperature < baselineTemp + 2) {


digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
}
else if (temperature >= baselineTemp + 2 && temperature < baselineTemp + 4) {
digitalWrite(2, HIGH);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
}
else if (temperature >= baselineTemp + 4 && temperature < baselineTemp + 6) {
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
}
else if (temperature >= baselineTemp + 6) {
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
}
delay(1);
}

103)

const int sensorPin = A0;

const float baselineTemp = 20.0;

void setup() {

Serial.begin(9600);

for (int pinNumber = 2; pinNumber < 5; pinNumber++) {


pinMode(pinNumber, OUTPUT);
digitalWrite(pinNumber, LOW);
}
}

void loop() {

int sensorVal = analogRead(sensorPin);

Serial.print("sensor Value: ");


Serial.print(sensorVal);
float voltage = (sensorVal / 1024.0) * 5.0;

Serial.print(", Volts: ");


Serial.print(voltage);

Serial.print(", degrees C: ");


float temperature = (voltage - .5) * 100;
Serial.println(temperature);

if (temperature < baselineTemp + 2) {


digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
}
else if (temperature >= baselineTemp + 2 && temperature < baselineTemp + 4) {
digitalWrite(2, HIGH);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
}
else if (temperature >= baselineTemp + 4 && temperature < baselineTemp + 6) {
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
}
else if (temperature >= baselineTemp + 6) {
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
}
delay(1);
}
104)

const int greenLEDPin = 9;


const int redLEDPin = 10;
const int blueLEDPin = 11;

const int redSensorPin = A0;


const int greenSensorPin = A1;
const int blueSensorPin = A2;

int redValue = 0;
int greenValue = 0;
int blueValue = 0;

int redSensorValue = 0;
int greenSensorValue = 0;
int blueSensorValue = 0;

void setup() {

Serial.begin(9600);

pinMode(greenLEDPin, OUTPUT);
pinMode(redLEDPin, OUTPUT);
pinMode(blueLEDPin, OUTPUT);
}

void loop() {

redSensorValue = analogRead(redSensorPin);
delay(5);

greenSensorValue = analogRead(greenSensorPin);

delay(5);

blueSensorValue = analogRead(blueSensorPin);

Serial.print("raw sensor Values \t red: ");


Serial.print(redSensorValue);
Serial.print("\t green: ");
Serial.print(greenSensorValue);
Serial.print("\t Blue: ");
Serial.println(blueSensorValue);

redValue = redSensorValue / 4;
greenValue = greenSensorValue / 4;
blueValue = blueSensorValue / 4;

Serial.print("Mapped sensor Values \t red: ");


Serial.print(redValue);
Serial.print("\t green: ");
Serial.print(greenValue);
Serial.print("\t Blue: ");
Serial.println(blueValue);

analogWrite(redLEDPin, redValue);
analogWrite(greenLEDPin, greenValue);
analogWrite(blueLEDPin, blueValue);
}
105)

#include <Servo.h>

Servo myServo;

int const potPin = A0;


int potVal;
int angle;

void setup() {
myServo.attach(9);
Serial.begin(9600);
}

void loop() {
potVal = analogRead(potPin);

Serial.print("potVal: ");
Serial.print(potVal);

angle = map(potVal, 0, 1023, 0, 179);

Serial.print(", angle: ");


Serial.println(angle);

myServo.write(angle);

delay(15);
}

106)

int sensorValue;

int sensorLow = 1023;

int sensorHigh = 0;

const int ledPin = 13;

void setup() {

pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);

while (millis() < 5000) {


sensorValue = analogRead(A0);
if (sensorValue > sensorHigh) {
sensorHigh = sensorValue;
}
// record the minimum sensor value
if (sensorValue < sensorLow) {
sensorLow = sensorValue;
}
}

digitalWrite(ledPin, LOW);
}

void loop() {
sensorValue = analogRead(A0);

int pitch = map(sensorValue, sensorLow, sensorHigh, 50, 4000);

tone(8, pitch, 20);

delay(10);
}

107)

int notes[] = {262, 294, 330, 349};

void setup() {

Serial.begin(9600);
}

void loop() {

int keyVal = analogRead(A0);

Serial.println(keyVal);

if (keyVal == 1023) {

tone(8, notes[0]);
} else if (keyVal >= 990 && keyVal <= 1010) {

tone(8, notes[1]);
} else if (keyVal >= 505 && keyVal <= 515) {

tone(8, notes[2]);
} else if (keyVal >= 5 && keyVal <= 10) {

tone(8, notes[3]);
} else {

noTone(8);
}
}

107)

const int switchPin = 8;

unsigned long previousTime = 0; // store the last time an LED was updated
int switchState = 0; // the current switch state
int prevSwitchState = 0; // the previous switch state
int led = 2; // a variable to refer to the LEDs

long interval = 600000; // interval at which to light the next LED

void setup() {

for (int x = 2; x < 8; x++) {


pinMode(x, OUTPUT);
}

pinMode(switchPin, INPUT);
}

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

if (currentTime - previousTime > interval) {

previousTime = currentTime;

digitalWrite(led, HIGH);

led++;

if (led == 7) {

}
}

switchState = digitalRead(switchPin);

if (switchState != prevSwitchState) {

for (int x = 2; x < 8; x++) {


digitalWrite(x, LOW);
}

led = 2;

previousTime = currentTime;
}

prevSwitchState = switchState;
}

108)

const int switchPin = 2;


const int motorPin = 9;

int switchState = 0;

void setup() {

pinMode(motorPin, OUTPUT);

pinMode(switchPin, INPUT);
}

void loop() {

switchState = digitalRead(switchPin);

if (switchState == HIGH) {

digitalWrite(motorPin, HIGH);
} else {

digitalWrite(motorPin, LOW);
}
}

109)

const int controlPin1 = 2;


const int controlPin2 = 3;
const int enablePin = 9;
const int directionSwitchPin = 4;
const int onOffSwitchStateSwitchPin = 5;
const int potPin = A0;

// create some variables to hold values from your inputs


int onOffSwitchState = 0;
int previousOnOffSwitchState = 0;
int directionSwitchState = 0;
int previousDirectionSwitchState = 0;

int motorEnabled = 0;
int motorSpeed = 0;
int motorDirection = 1;

void setup() {
// initialize the inputs and outputs
pinMode(directionSwitchPin, INPUT);
pinMode(onOffSwitchStateSwitchPin, INPUT);
pinMode(controlPin1, OUTPUT);
pinMode(controlPin2, OUTPUT);
pinMode(enablePin, OUTPUT);

digitalWrite(enablePin, LOW);
}

void loop() {

onOffSwitchState = digitalRead(onOffSwitchStateSwitchPin);
delay(1);
directionSwitchState = digitalRead(directionSwitchPin);

motorSpeed = analogRead(potPin) / 4;

if (onOffSwitchState != previousOnOffSwitchState) {

if (onOffSwitchState == HIGH) {
motorEnabled = !motorEnabled;
}
}

if (directionSwitchState != previousDirectionSwitchState) {

if (directionSwitchState == HIGH) {
motorDirection = !motorDirection;
}
}

if (motorDirection == 1) {
digitalWrite(controlPin1, HIGH);
digitalWrite(controlPin2, LOW);
} else {
digitalWrite(controlPin1, LOW);
digitalWrite(controlPin2, HIGH);
}

if (motorEnabled == 1) {

analogWrite(enablePin, motorSpeed);
} else {
analogWrite(enablePin, 0);
}

previousDirectionSwitchState = directionSwitchState;

previousOnOffSwitchState = onOffSwitchState;
}

110) // calea este E:\aldruino\arduinoSOFTULBUN\examples\10.StarterKit_BasicKit\p11_CrystalBall

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const int switchPin = 6;

int switchState = 0;

int prevSwitchState = 0;

int reply;

void setup() {

lcd.begin(16, 2);

pinMode(switchPin, INPUT);
lcd.print("Ask the");

lcd.setCursor(0, 1);

lcd.print("Crystal Ball!");
}

void loop() {

switchState = digitalRead(switchPin);

if (switchState != prevSwitchState) {

if (switchState == LOW) {

reply = random(8);

lcd.clear();

lcd.setCursor(0, 0);

lcd.print("the ball says:");

lcd.setCursor(0, 1);

switch (reply) {
case 0:
lcd.print("Yes");
break;

case 1:
lcd.print("Most likely");
break;

case 2:
lcd.print("Certainly");
break;

case 3:
lcd.print("Outlook good");
break;

case 4:
lcd.print("Unsure");
break;

case 5:
lcd.print("Ask again");
break;

case 6:
lcd.print("Doubtful");
break;

case 7:
lcd.print("No");
break;
}
}
}

prevSwitchState = switchState;
}
111)

#include <Servo.h>

Servo myServo;

const int piezo = A0;


const int switchPin = 2;
const int yellowLed = 3;
const int greenLed = 4;
const int redLed = 5;

int knockVal;

int switchVal;

const int quietKnock = 10;


const int loudKnock = 100;

bool locked = false;

int numberOfKnocks = 0;

void setup() {

myServo.attach(9);

pinMode(yellowLed, OUTPUT);
pinMode(redLed, OUTPUT);
pinMode(greenLed, OUTPUT);

pinMode(switchPin, INPUT);

Serial.begin(9600);

digitalWrite(greenLed, HIGH);

myServo.write(0);

Serial.println("the box is unlocked!");


}

void loop() {

if (locked == false) {

switchVal = digitalRead(switchPin);

if (switchVal == HIGH) {

locked = true;

digitalWrite(greenLed, LOW);
digitalWrite(redLed, HIGH);

myServo.write(90);

Serial.println("the box is locked!");

delay(1000);
}
}

if (locked == true) {

knockVal = analogRead(piezo);

if (numberOfKnocks < 3 && knockVal > 0) {

if (checkForKnock(knockVal) == true) {

numberOfKnocks++;
}

Serial.print(3 - numberOfKnocks);
Serial.println(" more knocks to go");
}
if (numberOfKnocks >= 3) {

locked = false;

myServo.write(0);

delay(20);

digitalWrite(greenLed, HIGH);
digitalWrite(redLed, LOW);
Serial.println("the box is unlocked!");

numberOfKnocks = 0;
}
}
}

bool checkForKnock(int value) {

if (value > quietKnock && value < loudKnock) {

digitalWrite(yellowLed, HIGH);
delay(50);
digitalWrite(yellowLed, LOW);

Serial.print("Valid knock of value ");


Serial.println(value);
return true;
}

else {

Serial.print("Bad knock value ");


Serial.println(value);

return false;
}
}

112)

void setup() {

Serial.begin(9600);
}

void loop() {

Serial.write(analogRead(A0) / 4);
delay(1);
}

112)

const int optoPin = 2;

void setup() {
pinMode(optoPin, OUTPUT);
}

void loop() {
digitalWrite(optoPin, HIGH);

delay(15);

digitalWrite(optoPin, LOW);
delay(21000);
}

SURSA ARDRUINO

#include "Arduino.h"
#undef SERIAL

#define PROG_FLICKER true

#define SPI_CLOCK (1000000/6)

#if defined(ARDUINO_ARCH_AVR)

#if SPI_CLOCK > (F_CPU / 128)


#define USE_HARDWARE_SPI
#endif

#endif

#ifndef ARDUINO_HOODLOADER2

#define RESET 10 // Use pin 10 to reset the target rather than SS


#define LED_HB 9
#define LED_ERR 8
#define LED_PMODE 7

#ifdef USE_OLD_STYLE_WIRING

#define PIN_MOSI 11
#define PIN_MISO 12
#define PIN_SCK 13

#endif

#else

#define RESET 4
#define LED_HB 7
#define LED_ERR 6
#define LED_PMODE 5

#endif

#ifndef PIN_MOSI
#define PIN_MOSI MOSI
#endif

#ifndef PIN_MISO
#define PIN_MISO MISO
#endif

#ifndef PIN_SCK
#define PIN_SCK SCK
#endif

// Force bitbanged SPI if not using the hardware SPI pins:


#if (PIN_MISO != MISO) || (PIN_MOSI != MOSI) || (PIN_SCK != SCK)
#undef USE_HARDWARE_SPI
#endif

#ifdef SERIAL_PORT_USBVIRTUAL
#define SERIAL SERIAL_PORT_USBVIRTUAL
#else
#define SERIAL Serial
#endif

#define BAUDRATE 19200

#define HWVER 2
#define SWMAJ 1
#define SWMIN 18

// STK Definitions
#define STK_OK 0x10
#define STK_FAILED 0x11
#define STK_UNKNOWN 0x12
#define STK_INSYNC 0x14
#define STK_NOSYNC 0x15
#define CRC_EOP 0x20 //ok it is a space...

void pulse(int pin, int times);

#ifdef USE_HARDWARE_SPI
#include "SPI.h"
#else

#define SPI_MODE0 0x00

class SPISettings {
public:
// clock is in Hz
SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) : clock(clock) {
(void) bitOrder;
(void) dataMode;
};

private:
uint32_t clock;

friend class BitBangedSPI;


};

class BitBangedSPI {
public:
void begin() {
digitalWrite(PIN_SCK, LOW);
digitalWrite(PIN_MOSI, LOW);
pinMode(PIN_SCK, OUTPUT);
pinMode(PIN_MOSI, OUTPUT);
pinMode(PIN_MISO, INPUT);
}

void beginTransaction(SPISettings settings) {


pulseWidth = (500000 + settings.clock - 1) / settings.clock;
if (pulseWidth == 0)
pulseWidth = 1;
}

void end() {}

uint8_t transfer (uint8_t b) {


for (unsigned int i = 0; i < 8; ++i) {
digitalWrite(PIN_MOSI, (b & 0x80) ? HIGH : LOW);
digitalWrite(PIN_SCK, HIGH);
delayMicroseconds(pulseWidth);
b = (b << 1) | digitalRead(PIN_MISO);
digitalWrite(PIN_SCK, LOW); // slow pulse
delayMicroseconds(pulseWidth);
}
return b;
}

private:
unsigned long pulseWidth; // in microseconds
};
static BitBangedSPI SPI;

#endif

void setup() {
SERIAL.begin(BAUDRATE);

pinMode(LED_PMODE, OUTPUT);
pulse(LED_PMODE, 2);
pinMode(LED_ERR, OUTPUT);
pulse(LED_ERR, 2);
pinMode(LED_HB, OUTPUT);
pulse(LED_HB, 2);

int error = 0;
int pmode = 0;
// address for reading and writing, set by 'U' command
unsigned int here;
uint8_t buff[256]; // global block storage

#define beget16(addr) (*addr * 256 + *(addr+1) )


typedef struct param {
uint8_t devicecode;
uint8_t revision;
uint8_t progtype;
uint8_t parmode;
uint8_t polling;
uint8_t selftimed;
uint8_t lockbytes;
uint8_t fusebytes;
uint8_t flashpoll;
uint16_t eeprompoll;
uint16_t pagesize;
uint16_t eepromsize;
uint32_t flashsize;
}
parameter;

parameter param;

uint8_t hbval = 128;


int8_t hbdelta = 8;
void heartbeat() {
static unsigned long last_time = 0;
unsigned long now = millis();
if ((now - last_time) < 40)
return;
last_time = now;
if (hbval > 192) hbdelta = -hbdelta;
if (hbval < 32) hbdelta = -hbdelta;
hbval += hbdelta;
analogWrite(LED_HB, hbval);
}

static bool rst_active_high;

void reset_target(bool reset) {


digitalWrite(RESET, ((reset && rst_active_high) || (!reset && !rst_active_high)) ? HIGH : LOW);
}

void loop(void) {

if (pmode) {
digitalWrite(LED_PMODE, HIGH);
} else {
digitalWrite(LED_PMODE, LOW);
}

if (error) {
digitalWrite(LED_ERR, HIGH);
} else {
digitalWrite(LED_ERR, LOW);
}

heartbeat();
if (SERIAL.available()) {
avrisp();
}
}

uint8_t getch() {
while (!SERIAL.available());
return SERIAL.read();
}
void fill(int n) {
for (int x = 0; x < n; x++) {
buff[x] = getch();
}
}

#define PTIME 30
void pulse(int pin, int times) {
do {
digitalWrite(pin, HIGH);
delay(PTIME);
digitalWrite(pin, LOW);
delay(PTIME);
} while (times--);
}

void prog_lamp(int state) {


if (PROG_FLICKER) {
digitalWrite(LED_PMODE, state);
}
}

uint8_t spi_transaction(uint8_t a, uint8_t b, uint8_t c, uint8_t d) {


SPI.transfer(a);
SPI.transfer(b);
SPI.transfer(c);
return SPI.transfer(d);
}

void empty_reply() {
if (CRC_EOP == getch()) {
SERIAL.print((char)STK_INSYNC);
SERIAL.print((char)STK_OK);
} else {
error++;
SERIAL.print((char)STK_NOSYNC);
}
}

void breply(uint8_t b) {
if (CRC_EOP == getch()) {
SERIAL.print((char)STK_INSYNC);
SERIAL.print((char)b);
SERIAL.print((char)STK_OK);
} else {
error++;
SERIAL.print((char)STK_NOSYNC);
}
}

void get_version(uint8_t c) {
switch (c) {
case 0x80:
breply(HWVER);
break;
case 0x81:
breply(SWMAJ);
break;
case 0x82:
breply(SWMIN);
break;
case 0x93:
breply('S'); // serial programmer
break;
default:
breply(0);
}
}

void set_parameters() {

param.devicecode = buff[0];
param.revision = buff[1];
param.progtype = buff[2];
param.parmode = buff[3];
param.polling = buff[4];
param.selftimed = buff[5];
param.lockbytes = buff[6];
param.fusebytes = buff[7];
param.flashpoll = buff[8];

param.eeprompoll = beget16(&buff[10]);
param.pagesize = beget16(&buff[12]);
param.eepromsize = beget16(&buff[14]);

param.flashsize = buff[16] * 0x01000000


+ buff[17] * 0x00010000
+ buff[18] * 0x00000100
+ buff[19];

rst_active_high = (param.devicecode >= 0xe0);


}

void start_pmode() {

reset_target(true);
pinMode(RESET, OUTPUT);
SPI.begin();
SPI.beginTransaction(SPISettings(SPI_CLOCK, MSBFIRST, SPI_MODE0));

digitalWrite(PIN_SCK, LOW);
delay(20); // discharge PIN_SCK, value arbitrarily chosen
reset_target(false);

delayMicroseconds(100);
reset_target(true);
delay(50); // datasheet: must be > 20 msec
spi_transaction(0xAC, 0x53, 0x00, 0x00);
pmode = 1;
}

void end_pmode() {
SPI.end();
// We're about to take the target out of reset so configure SPI pins as input
pinMode(PIN_MOSI, INPUT);
pinMode(PIN_SCK, INPUT);
reset_target(false);
pinMode(RESET, INPUT);
pmode = 0;
}

void universal() {
uint8_t ch;

fill(4);
ch = spi_transaction(buff[0], buff[1], buff[2], buff[3]);
breply(ch);
}

void flash(uint8_t hilo, unsigned int addr, uint8_t data) {


spi_transaction(0x40 + 8 * hilo,
addr >> 8 & 0xFF,
addr & 0xFF,
data);
}
void commit(unsigned int addr) {
if (PROG_FLICKER) {
prog_lamp(LOW);
}
spi_transaction(0x4C, (addr >> 8) & 0xFF, addr & 0xFF, 0);
if (PROG_FLICKER) {
delay(PTIME);
prog_lamp(HIGH);
}
}

unsigned int current_page() {


if (param.pagesize == 32) {
return here & 0xFFFFFFF0;
}
if (param.pagesize == 64) {
return here & 0xFFFFFFE0;
}
if (param.pagesize == 128) {
return here & 0xFFFFFFC0;
}
if (param.pagesize == 256) {
return here & 0xFFFFFF80;
}
return here;
}

void write_flash(int length) {


fill(length);
if (CRC_EOP == getch()) {
SERIAL.print((char) STK_INSYNC);
SERIAL.print((char) write_flash_pages(length));
} else {
error++;
SERIAL.print((char) STK_NOSYNC);
}
}

uint8_t write_flash_pages(int length) {


int x = 0;
unsigned int page = current_page();
while (x < length) {
if (page != current_page()) {
commit(page);
page = current_page();
}
flash(LOW, here, buff[x++]);
flash(HIGH, here, buff[x++]);
here++;
}

commit(page);

return STK_OK;
}

#define EECHUNK (32)


uint8_t write_eeprom(unsigned int length) {

unsigned int start = here * 2;


unsigned int remaining = length;
if (length > param.eepromsize) {
error++;
return STK_FAILED;
}
while (remaining > EECHUNK) {
write_eeprom_chunk(start, EECHUNK);
start += EECHUNK;
remaining -= EECHUNK;
}
write_eeprom_chunk(start, remaining);
return STK_OK;
}

uint8_t write_eeprom_chunk(unsigned int start, unsigned int length) {


// this writes byte-by-byte, page writing may be faster (4 bytes at a time)
fill(length);
prog_lamp(LOW);
for (unsigned int x = 0; x < length; x++) {
unsigned int addr = start + x;
spi_transaction(0xC0, (addr >> 8) & 0xFF, addr & 0xFF, buff[x]);
delay(45);
}
prog_lamp(HIGH);
return STK_OK;
}

void program_page() {
char result = (char) STK_FAILED;
unsigned int length = 256 * getch();
length += getch();
char memtype = getch();
// flash memory @here, (length) bytes
if (memtype == 'F') {
write_flash(length);
return;
}
if (memtype == 'E') {
result = (char)write_eeprom(length);
if (CRC_EOP == getch()) {
SERIAL.print((char) STK_INSYNC);
SERIAL.print(result);
} else {
error++;
SERIAL.print((char) STK_NOSYNC);
}
return;
}
SERIAL.print((char)STK_FAILED);
return;
}

uint8_t flash_read(uint8_t hilo, unsigned int addr) {


return spi_transaction(0x20 + hilo * 8,
(addr >> 8) & 0xFF,
addr & 0xFF,
0);
}

char flash_read_page(int length) {


for (int x = 0; x < length; x += 2) {
uint8_t low = flash_read(LOW, here);
SERIAL.print((char) low);
uint8_t high = flash_read(HIGH, here);
SERIAL.print((char) high);
here++;
}
return STK_OK;
}

char eeprom_read_page(int length) {


// here again we have a word address
int start = here * 2;
for (int x = 0; x < length; x++) {
int addr = start + x;
uint8_t ee = spi_transaction(0xA0, (addr >> 8) & 0xFF, addr & 0xFF, 0xFF);
SERIAL.print((char) ee);
}
return STK_OK;
}

void read_page() {
char result = (char)STK_FAILED;
int length = 256 * getch();
length += getch();
char memtype = getch();
if (CRC_EOP != getch()) {
error++;
SERIAL.print((char) STK_NOSYNC);
return;
}
SERIAL.print((char) STK_INSYNC);
if (memtype == 'F') result = flash_read_page(length);
if (memtype == 'E') result = eeprom_read_page(length);
SERIAL.print(result);
}

void read_signature() {
if (CRC_EOP != getch()) {
error++;
SERIAL.print((char) STK_NOSYNC);
return;
}
SERIAL.print((char) STK_INSYNC);
uint8_t high = spi_transaction(0x30, 0x00, 0x00, 0x00);
SERIAL.print((char) high);
uint8_t middle = spi_transaction(0x30, 0x00, 0x01, 0x00);
SERIAL.print((char) middle);
uint8_t low = spi_transaction(0x30, 0x00, 0x02, 0x00);
SERIAL.print((char) low);
SERIAL.print((char) STK_OK);
}

void avrisp() {
uint8_t ch = getch();
switch (ch) {
case '0': // signon
error = 0;
empty_reply();
break;
case '1':
if (getch() == CRC_EOP) {
SERIAL.print((char) STK_INSYNC);
SERIAL.print("AVR ISP");
SERIAL.print((char) STK_OK);
}
else {
error++;
SERIAL.print((char) STK_NOSYNC);
}
break;
case 'A':
get_version(getch());
break;
case 'B':
fill(20);
set_parameters();
empty_reply();
break;
case 'E':
fill(5);
empty_reply();
break;
case 'P':
if (!pmode)
start_pmode();
empty_reply();
break;
case 'U':
here = getch();
here += 256 * getch();
empty_reply();
break;

case 0x60:
getch();
getch();
empty_reply();
break;
case 0x61:
getch();
empty_reply();
break;

case 0x64:
program_page();
break;

case 0x74:
read_page();
break;

case 'V':
universal();
break;
case 'Q': //0x51
error = 0;
end_pmode();
empty_reply();
break;

case 0x75: //STK_READ_SIGN 'u'


read_signature();
break;

case CRC_EOP:
error++;
SERIAL.print((char) STK_NOSYNC);
break;

default:
error++;
if (CRC_EOP == getch())
SERIAL.print((char)STK_UNKNOWN);
else
SERIAL.print((char)STK_NOSYNC);
}
}

You might also like