29
Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input on pin 0, prints the result to the Serial Monitor. Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu). Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground. This example code is in the public domain. http://www.arduino.cc/en/Tutorial/AnalogReadSerial */ // the setup routine runs once when you press reset: void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } // the loop routine runs over and over again forever: void loop() { // read the input on analog pin 0: int sensorValue = analogRead(A0); // print out the value you read: Serial.println(sensorValue); delay(1); // delay in between reads for stability } (2)Basics Blink /* Blink Turns an LED on for one second, then off for one second, repeatedly.

Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

  • Upload
    others

  • View
    14

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

Arduino_Sketch_sample

(1)Basics AnalogReadSerial

/*

AnalogReadSerial

Reads an analog input on pin 0, prints the result to the Serial Monitor.

Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).

Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and

ground.

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/AnalogReadSerial

*/

// the setup routine runs once when you press reset:

void setup() {

// initialize serial communication at 9600 bits per second:

Serial.begin(9600);

}

// the loop routine runs over and over again forever:

void loop() {

// read the input on analog pin 0:

int sensorValue = analogRead(A0);

// print out the value you read:

Serial.println(sensorValue);

delay(1); // delay in between reads for stability

}

(2)Basics Blink

/*

Blink

Turns an LED on for one second, then off for one second, repeatedly.

Page 2: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO

it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to

the correct LED pin independent of which board is used.

If you want to know what pin the on-board LED is connected to on your Arduino

model, check the Technical Specs of your board at:

https://www.arduino.cc/en/Main/Products

modified 8 May 2014

by Scott Fitzgerald

modified 2 Sep 2016

by Arturo Guadalupi

modified 8 Sep 2016

by Colby Newman

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Blink

*/

// the setup function runs once when you press reset or power the board

void setup() {

// initialize digital pin LED_BUILTIN as an output.

pinMode(LED_BUILTIN, OUTPUT);

}

// the loop function runs over and over again forever

void loop() {

digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)

delay(1000); // wait for a second

digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage

LOW

delay(1000); // wait for a second

}

(3)Basics

/*

DigitalReadSerial

Page 3: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

Reads a digital input on pin 2, prints the result to the Serial Monitor

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/DigitalReadSerial

*/

// digital pin 2 has a pushbutton attached to it. Give it a name:

int pushButton = 2;

// the setup routine runs once when you press reset:

void setup() {

// initialize serial communication at 9600 bits per second:

Serial.begin(9600);

// make the pushbutton's pin an input:

pinMode(pushButton, INPUT);

}

// the loop routine runs over and over again forever:

void loop() {

// read the input pin:

int buttonState = digitalRead(pushButton);

// print out the state of the button:

Serial.println(buttonState);

delay(1); // delay in between reads for stability

}

(4)Basics

/*

DigitalReadSerial

Reads a digital input on pin 2, prints the result to the Serial Monitor

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/DigitalReadSerial

Page 4: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

*/

// digital pin 2 has a pushbutton attached to it. Give it a name:

int pushButton = 2;

// the setup routine runs once when you press reset:

void setup() {

// initialize serial communication at 9600 bits per second:

Serial.begin(9600);

// make the pushbutton's pin an input:

pinMode(pushButton, INPUT);

}

// the loop routine runs over and over again forever:

void loop() {

// read the input pin:

int buttonState = digitalRead(pushButton);

// print out the state of the button:

Serial.println(buttonState);

delay(1); // delay in between reads for stability

}

(5)Basics

/*

Fade

This example shows how to fade an LED on pin 9 using the analogWrite()

function.

The analogWrite() function uses PWM, so if you want to change the pin you're

using, be sure to use another PWM capable pin. On most Arduino, the PWM pins

are identified with a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Fade

*/

Page 5: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

int led = 9; // the PWM pin the LED is attached to

int brightness = 0; // how bright the LED is

int fadeAmount = 5; // how many points to fade the LED by

// the setup routine runs once when you press reset:

void setup() {

// declare pin 9 to be an output:

pinMode(led, OUTPUT);

}

// the loop routine runs over and over again forever:

void loop() {

// set the brightness of pin 9:

analogWrite(led, brightness);

// change the brightness for next time through the loop:

brightness = brightness + fadeAmount;

// reverse the direction of the fading at the ends of the fade:

if (brightness <= 0 || brightness >= 255) {

fadeAmount = -fadeAmount;

}

// wait for 30 milliseconds to see the dimming effect

delay(30);

}

(6)Basics

/*

ReadAnalogVoltage

Reads an analog input on pin 0, converts it to voltage, and prints the result to the

Serial Monitor.

Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).

Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and

ground.

Page 6: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/ReadAnalogVoltage

*/

// the setup routine runs once when you press reset:

void setup() {

// initialize serial communication at 9600 bits per second:

Serial.begin(9600);

}

// the loop routine runs over and over again forever:

void loop() {

// read the input on analog pin 0:

int sensorValue = analogRead(A0);

// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):

float voltage = sensorValue * (5.0 / 1023.0);

// print out the value you read:

Serial.println(voltage);

}

(7)Digital

/*

Blink without Delay

Turns on and off a light emitting diode (LED) connected to a digital pin,

without using the delay() function. This means that other code can run at the

same time without being interrupted by the LED code.

The circuit:

- Use the onboard LED.

- Note: Most Arduinos have an on-board LED you can control. On the UNO, MEGA

and ZERO it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN

is set to the correct LED pin independent of which board is used.

If you want to know what pin the on-board LED is connected to on your

Arduino model, check the Technical Specs of your board at:

https://www.arduino.cc/en/Main/Products

Page 7: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

created 2005

by David A. Mellis

modified 8 Feb 2010

by Paul Stoffregen

modified 11 Nov 2013

by Scott Fitzgerald

modified 9 Jan 2017

by Arturo Guadalupi

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

*/

// constants won't change. Used here to set a pin number:

const int ledPin = LED_BUILTIN;// the number of the LED pin

// Variables will change:

int ledState = LOW; // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time

// The value will quickly become too large for an int to store

unsigned long previousMillis = 0; // will store last time LED was updated

// constants won't change:

const long interval = 1000; // interval at which to blink (milliseconds)

void setup() {

// set the digital pin as output:

pinMode(ledPin, OUTPUT);

}

void loop() {

// here is where you'd put code that needs to be running all the time.

Page 8: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

// check to see if it's time to blink the LED; that is, if the difference

// between the current time and last time you blinked the LED is bigger than

// the interval at which you want to blink the LED.

unsigned long currentMillis = millis();

if (currentMillis - previousMillis >= interval) {

// save the last time you blinked the LED

previousMillis = currentMillis;

// 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);

}

}

(8)Digital

/*

Button

Turns on and off a light emitting diode(LED) connected to digital pin 13,

when pressing a pushbutton attached to pin 2.

The circuit:

- LED attached from pin 13 to ground

- pushbutton attached to pin 2 from +5V

- 10K resistor attached to pin 2 from ground

- Note: on most Arduinos there is already an LED on the board

attached to pin 13.

created 2005

Page 9: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

by DojoDave <http://www.0j0.org>

modified 30 Aug 2011

by Tom Igoe

This example code is in the public domain.

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

*/

// constants won't change. They're used here to set pin numbers:

const int buttonPin = 2; // the number of the pushbutton pin

const int ledPin = 13; // the number of the LED pin

// variables will change:

int buttonState = 0; // variable for reading the pushbutton status

void setup() {

// initialize the LED pin as an output:

pinMode(ledPin, OUTPUT);

// initialize the pushbutton pin as an input:

pinMode(buttonPin, INPUT);

}

void loop() {

// read the state of the pushbutton value:

buttonState = digitalRead(buttonPin);

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

if (buttonState == HIGH) {

// turn LED on:

digitalWrite(ledPin, HIGH);

} else {

// turn LED off:

digitalWrite(ledPin, LOW);

}

}

Page 10: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

(9)Digital

/*

Debounce

Each time the input pin goes from LOW to HIGH (e.g. because of a push-button

press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's a

minimum delay between toggles to debounce the circuit (i.e. to ignore noise).

The circuit:

- LED attached from pin 13 to ground

- pushbutton attached from pin 2 to +5V

- 10 kilohm resistor attached from pin 2 to ground

- Note: On most Arduino boards, there is already an LED on the board connected

to pin 13, so you don't need any extra components for this example.

created 21 Nov 2006

by David A. Mellis

modified 30 Aug 2011

by Limor Fried

modified 28 Dec 2012

by Mike Walters

modified 30 Aug 2016

by Arturo Guadalupi

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Debounce

*/

// constants won't change. They're used here to set pin numbers:

const int buttonPin = 2; // the number of the pushbutton pin

const int ledPin = 13; // the number of the LED pin

// Variables will change:

int ledState = HIGH; // the current state of the output pin

Page 11: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

int buttonState; // the current reading from the input pin

int lastButtonState = LOW; // the previous reading from the input pin

// the following variables are unsigned longs because the time, measured in

// milliseconds, will quickly become a bigger number than can be stored in an int.

unsigned long lastDebounceTime = 0; // the last time the output pin was toggled

unsigned long debounceDelay = 50; // the debounce time; increase if the output

flickers

void setup() {

pinMode(buttonPin, INPUT);

pinMode(ledPin, OUTPUT);

// set initial LED state

digitalWrite(ledPin, ledState);

}

void loop() {

// read the state of the switch into a local variable:

int reading = digitalRead(buttonPin);

// check to see if you just pressed the button

// (i.e. the input went from LOW to HIGH), and you've waited long enough

// since the last press to ignore any noise:

// If the switch changed, due to noise or pressing:

if (reading != lastButtonState) {

// reset the debouncing timer

lastDebounceTime = millis();

}

if ((millis() - lastDebounceTime) > debounceDelay) {

// whatever the reading is at, it's been there for longer than the debounce

// delay, so take it as the actual current state:

// if the button state has changed:

Page 12: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

if (reading != buttonState) {

buttonState = reading;

// only toggle the LED if the new button state is HIGH

if (buttonState == HIGH) {

ledState = !ledState;

}

}

}

// set the LED:

digitalWrite(ledPin, ledState);

// save the reading. Next time through the loop, it'll be the lastButtonState:

lastButtonState = reading;

}

(10)Digital DigitalInputPullup

/*

Input Pull-up Serial

This example demonstrates the use of pinMode(INPUT_PULLUP). It reads a digital

input on pin 2 and prints the results to the Serial Monitor.

The circuit:

- momentary switch attached from pin 2 to ground

- built-in LED on pin 13

Unlike pinMode(INPUT), there is no pull-down resistor necessary. An internal

20K-ohm resistor is pulled to 5V. This configuration causes the input to read

HIGH when the switch is open, and LOW when it is closed.

created 14 Mar 2012

by Scott Fitzgerald

This example code is in the public domain.

Page 13: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

http://www.arduino.cc/en/Tutorial/InputPullupSerial

*/

void setup() {

//start serial connection

Serial.begin(9600);

//configure pin 2 as an input and enable the internal pull-up resistor

pinMode(2, INPUT_PULLUP);

pinMode(13, OUTPUT);

}

void loop() {

//read the pushbutton value into a variable

int sensorVal = digitalRead(2);

//print out the value of the pushbutton

Serial.println(sensorVal);

// Keep in mind the pull-up means the pushbutton's logic is inverted. It goes

// HIGH when it's open, and LOW when it's pressed. Turn on pin 13 when the

// button's pressed, and off when it's not:

if (sensorVal == HIGH) {

digitalWrite(13, LOW);

} else {

digitalWrite(13, HIGH);

}

}

(11)Digital StateChangeDetection

/*

State change detection (edge detection)

Often, you don't need to know the state of a digital input all the time, but

you just need to know when the input changes from one state to another.

For example, you want to know when a button goes from OFF to ON. This is called

state change detection, or edge detection.

Page 14: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

This example shows how to detect when a button or button changes from off to on

and on to off.

The circuit:

- pushbutton attached to pin 2 from +5V

- 10 kilohm resistor attached to pin 2 from ground

- LED attached from pin 13 to ground (or use the built-in LED on most

Arduino boards)

created 27 Sep 2005

modified 30 Aug 2011

by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/ButtonStateChange

*/

// this constant won't change:

const int buttonPin = 2; // the pin that the pushbutton is attached to

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

// Variables will change:

int buttonPushCounter = 0; // counter for the number of button presses

int buttonState = 0; // current state of the button

int lastButtonState = 0; // previous state of the button

void setup() {

// initialize the button pin as a input:

pinMode(buttonPin, INPUT);

// initialize the LED as an output:

pinMode(ledPin, OUTPUT);

// initialize serial communication:

Serial.begin(9600);

}

Page 15: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

void loop() {

// read the pushbutton input pin:

buttonState = digitalRead(buttonPin);

// compare the buttonState to its previous state

if (buttonState != lastButtonState) {

// if the state has changed, increment the counter

if (buttonState == HIGH) {

// if the current state is HIGH then the button went from off to on:

buttonPushCounter++;

Serial.println("on");

Serial.print("number of button pushes: ");

Serial.println(buttonPushCounter);

} else {

// if the current state is LOW then the button went from on to off:

Serial.println("off");

}

// Delay a little bit to avoid bouncing

delay(50);

}

// save the current state as the last state, for next time through the loop

lastButtonState = buttonState;

// turns on the LED every four button pushes by checking the modulo of the

// button push counter. the modulo function gives you the remainder of the

// division of two numbers:

if (buttonPushCounter % 4 == 0) {

digitalWrite(ledPin, HIGH);

} else {

digitalWrite(ledPin, LOW);

}

}

(12)Digital toneKeyboard

Page 16: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

/*

Keyboard

Plays a pitch that changes based on a changing analog input

circuit:

- three force-sensing resistors from +5V to analog in 0 through 5

- three 10 kilohm resistors from analog in 0 through 5 to ground

- 8 ohm speaker on digital pin 8

created 21 Jan 2010

modified 9 Apr 2012

by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Tone3

*/

#include "pitches.h"

const int threshold = 10; // minimum reading of the sensors that generates a note

// notes to play, corresponding to the 3 sensors:

int notes[] = {

NOTE_A4, NOTE_B4, NOTE_C3

};

void setup() {

}

void loop() {

for (int thisSensor = 0; thisSensor < 3; thisSensor++) {

// get a sensor reading:

int sensorReading = analogRead(thisSensor);

Page 17: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

// if the sensor is pressed hard enough:

if (sensorReading > threshold) {

// play the note corresponding to this sensor:

tone(8, notes[thisSensor], 20);

}

}

}

(13)Digital toneMelody

/*

Melody

Plays a melody

circuit:

- 8 ohm speaker on digital pin 8

created 21 Jan 2010

modified 30 Aug 2011

by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Tone

*/

#include "pitches.h"

// notes in the melody:

int melody[] = {

NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4

};

// note durations: 4 = quarter note, 8 = eighth note, etc.:

int noteDurations[] = {

4, 8, 8, 4, 4, 4, 4, 4

Page 18: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

};

void setup() {

// iterate over the notes of the melody:

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

// to calculate the note duration, take one second divided by the note type.

//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.

int noteDuration = 1000 / noteDurations[thisNote];

tone(8, melody[thisNote], noteDuration);

// to distinguish the notes, set a minimum time between them.

// the note's duration + 30% seems to work well:

int pauseBetweenNotes = noteDuration * 1.30;

delay(pauseBetweenNotes);

// stop the tone playing:

noTone(8);

}

}

void loop() {

// no need to repeat the melody.

}

(14)Digital toneMultiple

/*

Multiple tone player

Plays multiple tones on multiple pins in sequence

circuit:

- three 8 ohm speakers on digital pins 6, 7, and 8

created 8 Mar 2010

by Tom Igoe

based on a snippet from Greg Borenstein

Page 19: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Tone4

*/

void setup() {

}

void loop() {

// turn off tone function for pin 8:

noTone(8);

// play a note on pin 6 for 200 ms:

tone(6, 440, 200);

delay(200);

// turn off tone function for pin 6:

noTone(6);

// play a note on pin 7 for 500 ms:

tone(7, 494, 500);

delay(500);

// turn off tone function for pin 7:

noTone(7);

// play a note on pin 8 for 300 ms:

tone(8, 523, 300);

delay(300);

}

(15)Digital tonePitchFlower

/*

Pitch follower

Plays a pitch that changes based on a changing analog input

circuit:

- 8 ohm speaker on digital pin 9

Page 20: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

- photoresistor on analog 0 to 5V

- 4.7 kilohm resistor on analog 0 to ground

created 21 Jan 2010

modified 31 May 2012

by Tom Igoe, with suggestion from Michael Flynn

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Tone2

*/

void setup() {

// initialize serial communications (for debugging only):

Serial.begin(9600);

}

void loop() {

// read the sensor:

int sensorReading = analogRead(A0);

// print the sensor reading so you know its range

Serial.println(sensorReading);

// map the analog input range (in this case, 400 - 1000 from the photoresistor)

// to the output pitch range (120 - 1500Hz)

// change the minimum and maximum input numbers below depending on the range

// your sensor's giving:

int thisPitch = map(sensorReading, 400, 1000, 120, 1500);

// play the pitch:

tone(9, thisPitch, 10);

delay(1); // delay in between reads for stability

}

(16)Analog AnalogInOutSreal

/*

Analog input, analog output, serial output

Page 21: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

Reads an analog input pin, maps the result to a range from 0 to 255 and uses

the result to set the pulse width modulation (PWM) of an output pin.

Also prints the results to the Serial Monitor.

The circuit:

- potentiometer connected to analog pin 0.

Center pin of the potentiometer goes to the analog pin.

side pins of the potentiometer go to +5V and ground

- LED connected from digital pin 9 to ground

created 29 Dec. 2008

modified 9 Apr 2012

by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/AnalogInOutSerial

*/

// These constants won't change. They're used to give names to the pins used:

const int analogInPin = A0; // Analog input pin that the potentiometer is attached to

const int analogOutPin = 9; // Analog output pin that the LED is attached to

int sensorValue = 0; // value read from the pot

int outputValue = 0; // value output to the PWM (analog out)

void setup() {

// initialize serial communications at 9600 bps:

Serial.begin(9600);

}

void loop() {

// read the analog in value:

sensorValue = analogRead(analogInPin);

// map it to the range of the analog out:

outputValue = map(sensorValue, 0, 1023, 0, 255);

Page 22: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

// change the analog out value:

analogWrite(analogOutPin, outputValue);

// print the results to the Serial Monitor:

Serial.print("sensor = ");

Serial.print(sensorValue);

Serial.print("¥t output = ");

Serial.println(outputValue);

// wait 2 milliseconds before the next loop for the analog-to-digital

// converter to settle after the last reading:

delay(2);

}

(17)Sensors ADXL3xx

/*

ADXL3xx

Reads an Analog Devices ADXL3xx accelerometer and communicates the

acceleration to the computer. The pins used are designed to be easily

compatible with the breakout boards from SparkFun, available from:

http://www.sparkfun.com/commerce/categories.php?c=80

The circuit:

- analog 0: accelerometer self test

- analog 1: z-axis

- analog 2: y-axis

- analog 3: x-axis

- analog 4: ground

- analog 5: vcc

created 2 Jul 2008

by David A. Mellis

modified 30 Aug 2011

by Tom Igoe

This example code is in the public domain.

Page 23: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

http://www.arduino.cc/en/Tutorial/ADXL3xx

*/

// these constants describe the pins. They won't change:

const int groundpin = 18; // analog input pin 4 -- ground

const int powerpin = 19; // analog input pin 5 -- voltage

const int xpin = A3; // x-axis of the accelerometer

const int ypin = A2; // y-axis

const int zpin = A1; // z-axis (only on 3-axis models)

void setup() {

// initialize the serial communications:

Serial.begin(9600);

// Provide ground and power by using the analog inputs as normal digital pins.

// This makes it possible to directly connect the breakout board to the

// Arduino. If you use the normal 5V and GND pins on the Arduino,

// you can remove these lines.

pinMode(groundpin, OUTPUT);

pinMode(powerpin, OUTPUT);

digitalWrite(groundpin, LOW);

digitalWrite(powerpin, HIGH);

}

void loop() {

// print the sensor values:

Serial.print(analogRead(xpin));

// print a tab between values:

Serial.print("¥t");

Serial.print(analogRead(ypin));

// print a tab between values:

Serial.print("¥t");

Serial.print(analogRead(zpin));

Serial.println();

// delay before next reading:

Page 24: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

delay(100);

}

(18)Sensors

/*

Ping))) Sensor

This sketch reads a PING))) ultrasonic rangefinder and returns the distance

to the closest object in range. To do this, it sends a pulse to the sensor to

initiate a reading, then listens for a pulse to return. The length of the

returning pulse is proportional to the distance of the object from the sensor.

The circuit:

- +V connection of the PING))) attached to +5V

- GND connection of the PING))) attached to ground

- SIG connection of the PING))) attached to digital pin 7

created 3 Nov 2008

by David A. Mellis

modified 30 Aug 2011

by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Ping

*/

// this constant won't change. It's the pin number of the sensor's output:

const int pingPin = 7;

void setup() {

// initialize serial communication:

Serial.begin(9600);

}

void loop() {

// establish variables for duration of the ping, and the distance result

Page 25: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

// in inches and centimeters:

long duration, inches, cm;

// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.

// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:

pinMode(pingPin, OUTPUT);

digitalWrite(pingPin, LOW);

delayMicroseconds(2);

digitalWrite(pingPin, HIGH);

delayMicroseconds(5);

digitalWrite(pingPin, LOW);

// The same pin is used to read the signal from the PING))): a HIGH pulse

// whose duration is the time (in microseconds) from the sending of the ping

// to the reception of its echo off of an object.

pinMode(pingPin, INPUT);

duration = pulseIn(pingPin, HIGH);

// convert the time into a distance

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) {

// According to Parallax's datasheet for the PING))), there are 73.746

// microseconds per inch (i.e. sound travels at 1130 feet per second).

// This gives the distance travelled by the ping, outbound and return,

// so we divide by 2 to get the distance of the obstacle.

Page 26: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

// See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf

return microseconds / 74 / 2;

}

long microsecondsToCentimeters(long microseconds) {

// The speed of sound is 340 m/s or 29 microseconds per centimeter.

// The ping travels out and back, so to find the distance of the object we

// take half of the distance travelled.

return microseconds / 29 / 2;

}

(19)Sensors Knock

/*

Knock Sensor

This sketch reads a piezo element to detect a knocking sound.

It reads an analog pin and compares the result to a set threshold.

If the result is greater than the threshold, it writes "knock" to the serial

port, and toggles the LED on pin 13.

The circuit:

- positive connection of the piezo attached to analog in 0

- negative connection of the piezo attached to ground

- 1 megohm resistor attached from analog in 0 to ground

created 25 Mar 2007

by David Cuartielles <http://www.0j0.org>

modified 30 Aug 2011

by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Knock

*/

// these constants won't change:

Page 27: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

const int ledPin = 13; // LED connected to digital pin 13

const int knockSensor = A0; // the piezo is connected to analog pin 0

const int threshold = 100; // threshold value to decide when the detected sound is a

knock or not

// these variables will change:

int sensorReading = 0; // variable to store the value read from the sensor pin

int ledState = LOW; // variable used to store the last LED status, to toggle the

light

void setup() {

pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT

Serial.begin(9600); // use the serial port

}

void loop() {

// read the sensor and store it in the variable sensorReading:

sensorReading = analogRead(knockSensor);

// if the sensor reading is greater than the threshold:

if (sensorReading >= threshold) {

// toggle the status of the ledPin:

ledState = !ledState;

// update the LED pin itself:

digitalWrite(ledPin, ledState);

// send the string "Knock!" back to the computer, followed by newline

Serial.println("Knock!");

}

delay(100); // delay to avoid overloading the serial port buffer

}

(20)Sensors Memsic2125

/*

Memsic2125

Read the Memsic 2125 two-axis accelerometer. Converts the pulses output by the

Page 28: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

2125 into milli-g's (1/1000 of Earth's gravity) and prints them over the

serial connection to the computer.

The circuit:

- X output of accelerometer to digital pin 2

- Y output of accelerometer to digital pin 3

- +V of accelerometer to +5V

- GND of accelerometer to ground

created 6 Nov 2008

by David A. Mellis

modified 30 Aug 2011

by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Memsic2125

*/

// these constants won't change:

const int xPin = 2; // X output of the accelerometer

const int yPin = 3; // Y output of the accelerometer

void setup() {

// initialize serial communications:

Serial.begin(9600);

// initialize the pins connected to the accelerometer as inputs:

pinMode(xPin, INPUT);

pinMode(yPin, INPUT);

}

void loop() {

// variables to read the pulse widths:

int pulseX, pulseY;

// variables to contain the resulting accelerations

int accelerationX, accelerationY;

Page 29: Arduino Sketch sample (1)Basics AnalogReadSerialyyhome/Arduino/Arduino_Sketch_sample.pdf · Arduino_Sketch_sample (1)Basics AnalogReadSerial /* AnalogReadSerial Reads an analog input

// read pulse from x- and y-axes:

pulseX = pulseIn(xPin, HIGH);

pulseY = pulseIn(yPin, HIGH);

// convert the pulse width into acceleration

// accelerationX and accelerationY are in milli-g's:

// Earth's gravity is 1000 milli-g's, or 1 g.

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

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

// print the acceleration

Serial.print(accelerationX);

// print a tab character:

Serial.print("¥t");

Serial.print(accelerationY);

Serial.println();

delay(100);

}