Initial commit

parents
## Example files for the title:
# Getting Started with Arduino 2nd Edition, by Massimo Banzi
[![Getting Started with Arduino 2nd Edition, by Massimo Banzi](http://akamaicovers.oreilly.com/images/9781449309879/cat.gif)](https://www.safaribooksonline.com/library/view/title/9781449316358//)
The following applies to example files from material published by O’Reilly Media, Inc. Content from other publishers may include different rules of usage. Please refer to any additional usage rights explained in the actual example files or refer to the publisher’s website.
O'Reilly books are here to help you get your job done. In general, you may use the code in O'Reilly books in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from our books does not require permission. Answering a question by citing our books and quoting example code does not require permission. On the other hand, selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Incorporating a significant amount of example code from our books into your product's documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN.
If you think your use of code examples falls outside fair use or the permission given here, feel free to contact us at <permissions@oreilly.com>.
Please note that the examples are not production code and have not been carefully testing. They are provided "as-is" and come with no warranty of any kind.
// Example 01 : Blinking LED
const int LED = 13; // LED connected to
// digital pin 13
void setup()
{
pinMode(LED, OUTPUT); // sets the digital
// pin as output
}
void loop()
{
digitalWrite(LED, HIGH); // turns the LED on
delay(1000); // waits for a second
digitalWrite(LED, LOW); // turns the LED off
delay(1000); // waits for a second
}
// Example 02: Turn on LED while the button is pressed
const int LED = 13; // the pin for the LED
const int BUTTON = 7; // the input pin where the
// pushbutton is connected
int val = 0; // val will be used to store the state
// of the input pin
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop(){
val = digitalRead(BUTTON); // read input value and store it
// check whether the input is HIGH (button pressed)
if (val == HIGH) {
digitalWrite(LED, HIGH); // turn LED ON
}
else {
digitalWrite(LED, LOW);
}
}
// Example 03A: Turn on LED when the button is pressed
// and keep it on after it is released
const int LED = 13; // the pin for the LED
const int BUTTON = 7; // the input pin where the
// pushbutton is connected
int val = 0; // val will be used to store the state
// of the input pin
int state = 0; // 0 = LED off while 1 = LED on
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop() {
val = digitalRead(BUTTON); // read input value and store it
// check if the input is HIGH (button pressed)
// and change the state
if (val == HIGH) {
state = 1 - state;
}
if (state == 1) {
digitalWrite(LED, HIGH); // turn LED ON
}
else {
digitalWrite(LED, LOW);
}
}
// Example 03B: Turn on LED when the button is pressed
// and keep it on after it is released
// Now with a new and improved formula!
const int LED = 13; // the pin for the LED
const int BUTTON = 7; // the input pin where the
// pushbutton is connected
int val = 0; // val will be used to store the state
// of the input pin
int old_val = 0; // this variable stores the previous
// value of "val"
int state = 0; // 0 = LED off and 1 = LED on
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop(){
val = digitalRead(BUTTON); // read input value and store it
// yum, fresh
// check if there was a transition
if ((val == HIGH) && (old_val == LOW)){
state = 1 - state;
}
old_val = val; // val is now old, let's store it
if (state == 1) {
digitalWrite(LED, HIGH); // turn LED ON
}
else {
digitalWrite(LED, LOW);
}
}
// Example 03C: Turn on LED when the button is pressed
// and keep it on after it is released
// including simple de-bouncing
// Now with another new and improved formula!!
const int LED = 13; // the pin for the LED
const int BUTTON = 7; // the input pin where the
// pushbutton is connected
int val = 0; // val will be used to store the state
// of the input pin
int old_val = 0; // this variable stores the previous
// value of "val"
int state = 0; // 0 = LED off and 1 = LED on
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop(){
val = digitalRead(BUTTON); // read input value and store it
// yum, fresh
// check if there was a transition
if ((val == HIGH) && (old_val == LOW)){
state = 1 - state;
delay(10);
}
old_val = val; // val is now old, let's store it
if (state == 1) {
digitalWrite(LED, HIGH); // turn LED ON
}
else {
digitalWrite(LED, LOW);
}
}
// Example 04: Fade an LED in and out like on
// a sleeping Apple computer
const int LED = 9; // the pin for the LED
int i = 0; // We’ll use this to count up and down
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
}
void loop(){
for (i = 0; i < 255; i++) { // loop from 0 to 254 (fade in)
analogWrite(LED, i); // set the LED brightness
delay(10); // Wait 10ms because analogWrite
// is instantaneous and we would
// not see any change
}
for (i = 255; i > 0; i--) { // loop from 255 to 1 (fade out)
analogWrite(LED, i); // set the LED brightness
delay(10); // Wait 10ms
}
}
// Example 05: Turn on LED when the button is pressed
// and keep it on after it is released
// including simple de-bouncing.
// If the button is held, brightness changes.
const int LED = 9; // the pin for the LED
const int BUTTON = 7; // input pin of the pushbutton
int val = 0; // stores the state of the input pin
int old_val = 0; // stores the previous value of "val"
int state = 0; // 0 = LED off while 1 = LED on
int brightness = 128; // Stores the brightness value
unsigned long startTime = 0; // when did we begin pressing?
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop() {
val = digitalRead(BUTTON); // read input value and store it
// yum, fresh
// check if there was a transition
if ((val == HIGH) && (old_val == LOW)) {
state = 1 - state; // change the state from off to on
// or vice-versa
startTime = millis(); // millis() is the Arduino clock
// it returns how many milliseconds
// have passed since the board has
// been reset.
// (this line remembers when the button
// was last pressed)
delay(10);
}
// check whether the button is being held down
if ((val == HIGH) && (old_val == HIGH)) {
// If the button is held for more than 500ms.
if (state == 1 && (millis() - startTime) > 500) {
brightness++; // increment brightness by 1
delay(10); // delay to avoid brightness going
// up too fast
if (brightness > 255) { // 255 is the max brightness
brightness = 0; // if we go over 255
// let’s go back to 0
}
}
}
old_val = val; // val is now old, let’s store it
if (state == 1) {
analogWrite(LED, brightness); // turn LED ON at the
// current brightness level
}
else {
analogWrite(LED, 0); // turn LED OFF
}
}
// Example 06A: Blink LED at a rate specified by the
// value of the analogue input
const int LED = 13; // the pin for the LED
int val = 0; // variable used to store the value
// coming from the sensor
void setup() {
pinMode(LED, OUTPUT); // LED is as an OUTPUT
// Note: Analogue pins are
// automatically set as inputs
}
void loop() {
val = analogRead(0); // read the value from
// the sensor
digitalWrite(LED, HIGH); // turn the LED on
delay(val); // stop the program for
// some time
digitalWrite(LED, LOW); // turn the LED off
delay(val); // stop the program for
// some time
}
// Example 06B: Set the brightness of LED to
// a brightness specified by the
// value of the analogue input
const int LED = 9; // the pin for the LED
int val = 0; // variable used to store the value
// coming from the sensor
void setup() {
pinMode(LED, OUTPUT); // LED is as an OUTPUT
// Note: Analogue pins are
// automatically set as inputs
}
void loop() {
val = analogRead(0); // read the value from
// the sensor
analogWrite(LED, val/4); // turn the LED on at
// the brightness set
// by the sensor
delay(10); // stop the program for
// some time
}
// Example 07: Send to the computer the values read from
// analogue input 0
// Make sure you click on "Serial Monitor"
// after you upload
const int SENSOR = 0; // select the input pin for the
// sensor resistor
int val = 0; // variable to store the value coming
// from the sensor
void setup() {
Serial.begin(9600); // open the serial port to send
// data back to the computer at
// 9600 bits per second
}
void loop() {
val = analogRead(SENSOR); // read the value from
// the sensor
Serial.println(val); // print the value to
// the serial port
delay(100); // wait 100ms between
// each send
}
// Example 08A: Arduino networked lamp
// parts of the code are inspired
// by a blog post by Tod E. Kurt (todbot.com)
import processing.serial.*;
String feed = "http://blog.makezine.com/index.xml";
int interval = 10; // retrieve feed every 60 seconds;
int lastTime; // the last time we fetched the content
int love = 0;
int peace = 0;
int arduino = 0;
int light = 0; // light level measured by the lamp
Serial port;
color c;
String cs;
String buffer = ""; // Accumulates characters coming from Arduino
PFont font;
void setup() {
size(640, 480);
frameRate(10); // we don't need fast updates
font = loadFont("HelveticaNeue-Bold-32.vlw");
fill(255);
textFont(font, 32);
// IMPORTANT NOTE:
// The first serial port retrieved by Serial.list()
// should be your Arduino. If not, uncomment the next
// line by deleting the // before it, and re-run the
// sketch to see a list of serial ports. Then, change
// the 0 in between [ and ] to the number of the port
// that your Arduino is connected to.
//println(Serial.list());
String arduinoPort = Serial.list()[0];
port = new Serial(this, arduinoPort, 9600); // connect to Arduino
lastTime = 0;
fetchData();
}
void draw() {
background( c );
int n = (interval - ((millis()-lastTime)/1000));
// Build a colour based on the 3 values
c = color(peace, love, arduino);
cs = "#" + hex(c, 6); // Prepare a string to be sent to Arduino
text("Arduino Networked Lamp", 10, 40);
text("Reading feed:", 10, 100);
text(feed, 10, 140);
text("Next update in "+ n + " seconds", 10, 450);
text("peace", 10, 200);
text(" " + peace, 130, 200);
rect(200, 172, peace, 28);
text("love ", 10, 240);
text(" " + love, 130, 240);
rect(200, 212, love, 28);
text("arduino ", 10, 280);
text(" " + arduino, 130, 280);
rect(200, 252, arduino, 28);
// write the colour string to the screen
text("sending", 10, 340);
text(cs, 200, 340);
text("light level", 10, 380);
rect(200, 352, light/10.23, 28); // this turns 1023 into 100
if (n <= 0) {
fetchData();
lastTime = millis();
}
port.write(cs); // send data to Arduino
if (port.available() > 0) { // check if there is data waiting
int inByte = port.read(); // read one byte
if (inByte != 10) { // if byte is not newline
buffer = buffer + char(inByte); // just add it to the buffer
}
else {
// newline reached, let's process the data
if (buffer.length() > 1) { // make sure there is enough data
// chop off the last character, it's a carriage return
// (a carriage return is the character at the end of a
// line of text)
buffer = buffer.substring(0, buffer.length() -1);
// turn the buffer from string into an integer number
light = int(buffer);
// clean the buffer for the next read cycle
buffer = "";
// We're likely falling behind in taking readings
// from Arduino. So let's clear the backlog of
// incoming sensor readings so the next reading is
// up-to-date.
port.clear();
}
}
}
}
void fetchData() {
// we use these strings to parse the feed
String data;
String chunk;
// zero the counters
love = 0;
peace = 0;
arduino = 0;
try {
URL url = new URL(feed); // An object to represent the URL
// prepare a connection
URLConnection conn = url.openConnection();
conn.connect(); // now connect to the Website
// this is a bit of virtual plumbing as we connect
// the data coming from the connection to a buffered
// reader that reads the data one line at a time.
BufferedReader in = new
BufferedReader(new InputStreamReader(conn.getInputStream()));
// read each line from the feed
while ( (data = in.readLine ()) != null) {
StringTokenizer st =
new StringTokenizer(data, "\"<>,.()[] ");// break it down
while (st.hasMoreTokens ()) {
// each chunk of data is made lowercase
chunk= st.nextToken().toLowerCase() ;
if (chunk.indexOf("love") >= 0 ) // found "love"?
love++; // increment love by 1
if (chunk.indexOf("peace") >= 0) // found "peace"?
peace++; // increment peace by 1
if (chunk.indexOf("arduino") >= 0) // found "arduino"?
arduino++; // increment arduino by 1
}
}
// Set 64 to be the maximum number of references we care about.
if (peace > 64) peace = 64;
if (love > 64) love = 64;
if (arduino > 64) arduino = 64;
peace = peace * 4; // multiply by 4 so that the max is 255,
love = love * 4; // which comes in handy when building a
arduino = arduino * 4; // colour that is made of 4 bytes (ARGB)
}
catch (Exception ex) { // If there was an error, stop the sketch
ex.printStackTrace();
System.out.println("ERROR: "+ex.getMessage());
}
}
// Example 08B: Arduino Networked Lamp
const int SENSOR = 0;
const int R_LED = 9;
const int G_LED = 10;
const int B_LED = 11;
const int BUTTON = 12;
int val = 0; // variable to store the value coming from the sensor
int btn = LOW;
int old_btn = LOW;
int state = 0;
char buffer[7] ;
int pointer = 0;
byte inByte = 0;
byte r = 0;
byte g = 0;
byte b = 0;
void setup() {
Serial.begin(9600); // open the serial port
pinMode(BUTTON, INPUT);
}
void loop() {
val = analogRead(SENSOR); // read the value from the sensor
Serial.println(val); // print the value to
// the serial port
if (Serial.available() >0) {
// read the incoming byte:
inByte = Serial.read();
// If the marker's found, next 6 characters are the colour
if (inByte == '#') {
while (pointer < 6) { // accumulate 6 chars
buffer[pointer] = Serial.read(); // store in the buffer
pointer++; // move the pointer forward by 1
}
// now we have the 3 numbers stored as hex numbers
// we need to decode them into 3 bytes r, g and b
r = hex2dec(buffer[1]) + hex2dec(buffer[0]) * 16;
g = hex2dec(buffer[3]) + hex2dec(buffer[2]) * 16;
b = hex2dec(buffer[5]) + hex2dec(buffer[4]) * 16;
pointer = 0; // reset the pointer so we can reuse the buffer
}
}
btn = digitalRead(BUTTON); // read input value and store it
// Check if there was a transition
if ((btn == HIGH) && (old_btn == LOW)){
state = 1 - state;
}
old_btn = btn; // val is now old, let's store it
if (state == 1) { // if the lamp is on
analogWrite(R_LED, r); // turn the leds on
analogWrite(G_LED, g); // at the colour
analogWrite(B_LED, b); // sent by the computer
}
else {
analogWrite(R_LED, 0); // otherwise turn off
analogWrite(G_LED, 0);
analogWrite(B_LED, 0);
}
delay(100); // wait 100ms between each send
}
int hex2dec(byte c) { // converts one HEX character into a number
if (c >= '0' && c <= '9') {
return c - '0';
}
else if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
}
logo.png

2.59 KB

Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment