Initial commit

parents
Showing with 4325 additions and 0 deletions
## Example files for the title:
# Arduino Cookbook 2nd Edition, by Michael Margolis
[![Arduino Cookbook 2nd Edition, by Michael Margolis](http://akamaicovers.oreilly.com/images/9781449313876/cat.gif)](https://www.safaribooksonline.com/library/view/title/9781449321185//)
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.
const int ledPin = 13; // LED connected to digital pin 13
void setup()
{
pinMode(ledPin, OUTPUT);
}
void loop()
{
digitalWrite(ledPin, HIGH); // set the LED on
delay(2000); // wait for two seconds
digitalWrite(ledPin, LOW); // set the LED off
delay(2000); // wait for two seconds
}
const int ledPin = 13; // LED connected to digital pin 13
const int sensorPin = 0; // connect sensor to analog input 0
void setup()
{
pinMode(ledPin, OUTPUT); // enable output on the led pin
}
void loop()
{
int rate = analogRead(sensorPin); // read the analog input
digitalWrite(ledPin, HIGH); // set the LED on
delay(rate); // wait duration dependent on light level
digitalWrite(ledPin, LOW); // set the LED off
delay(rate);
}
const int ledPin = 13; // LED connected to digital pin 13
const int sensorPin = 0; // connect sensor to analog input 0
// the next two lines set the min and max delay between blinks
const int minDuration = 100; // minimum wait between blinks
const int maxDuration = 1000; // maximum wait between blinks
void setup()
{
pinMode(ledPin, OUTPUT); // enable output on the led pin
}
void loop()
{
int rate = analogRead(sensorPin); // read the analog input
// the next line scales the blink rate between the min and max values
rate = map(rate, 200,800,minDuration, maxDuration); // convert to blink rate
rate = constrain(rate, minDuration,maxDuration); // constrain the value
digitalWrite(ledPin, HIGH); // set the LED on
delay(rate); // wait duration dependent on light level
digitalWrite(ledPin, LOW); // set the LED off
delay(rate);
}
\ No newline at end of file
const int ledPin = 13; // LED connected to digital pin 13
const int sensorPin = 0; // connect sensor to analog input 0
// the next two lines set the min and max delay between blinks
const int minDuration = 100; // minimum wait between blinks
const int maxDuration = 1000; // maximum wait between blinks
void setup()
{
pinMode(ledPin, OUTPUT); // enable output on the led pin
Serial.begin(9600); // initialize Serial
}
void loop()
{
int rate = analogRead(sensorPin); // read the analog input
// the next line scales the blink rate between the min and max values
rate = map(rate, 200,800,minDuration, maxDuration); // convert to blink rate
rate = constrain(rate, minDuration,maxDuration); // constrain the value
Serial.println(rate); // print rate to serial monitor
digitalWrite(ledPin, HIGH); // set the LED on
delay(rate); // wait duration dependent on light level
digitalWrite(ledPin, LOW); // set the LED off
delay(rate);
}
const int outputPin = 9; // Speaker connected to digital pin 9
const int sensorPin = 0; // connect sensor to analog input 0
const int minDuration = 1; // 1ms on, 1ms off (500 Hz)
const int maxDuration = 10; // 10ms on, 10ms off (50 hz)
void setup()
{
pinMode(outputPin, OUTPUT); // enable output on the led pin
}
void loop()
{
int sensorReading = analogRead(sensorPin); // read the analog input
int rate = map(sensorReading, 200,800,minDuration, maxDuration);
rate = constrain(rate, minDuration,maxDuration); // constrain the value
digitalWrite(outputPin, HIGH); // set the LED on
delay(rate); // wait duration dependent on light level
digitalWrite(outputPin, LOW); // set the LED off
delay(rate);
}
\ No newline at end of file
const int ledPin = 13; // LED connected to digital pin 13
// The setup() method runs once, when the sketch starts
void setup()
{
pinMode(ledPin, OUTPUT); // initialize the digital pin as an output
}
// the loop() method runs over and over again,
void loop()
{
digitalWrite(ledPin, HIGH); // turn the LED on
delay(1000); // wait a second
digitalWrite(ledPin, LOW); // turn the LED off
delay(1000); // wait a second
}
/*
blink3 sketch
demonstrates calling a function with a parameter and returning a value
uses the same wiring as the pull-up sketch from Recipe 5.2
The LED flashes when the program starts
and stops when a switch connected to pin 2 is pressed
the program prints the number of times the LED flashes.
*/
const int ledPin = 13; // output pin for the LED
const int inputPin = 2; // input pin for the switch
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(inputPin, INPUT);
digitalWrite(inputPin,HIGH); // use internal pull-up resistor (Recipe 5.2)
Serial.begin(9600);
}
void loop(){
Serial.println("Press and hold the switch to stop blinking");
int count = blink3(250); // blink the LED 250ms on and 250ms off
Serial.print("The number of times the switch blinked was ");
Serial.println(count);
}
// blink an LED using the given delay period
// return the number of times the LED flashed
int blink3(int period)
{
int result = 0;
int switchVal = HIGH; //with pull-ups, this will be high when switch is up
while(switchVal == HIGH) // repeat this loop until switch is pressed
// (it will go low when pressed)
{
digitalWrite(ledPin,HIGH);
delay(period);
digitalWrite(ledPin,LOW);
delay(period);
result = result + 1; // increment the count
switchVal = digitalRead(inputPin); // read input value
}
// here when switchVal is no longer HIGH because the switch is pressed
return result; // this value will be returned
}
/*
swap sketch
demonstrates changing two values using global variables
*/
int x; // x and y are global variables
int y;
void setup() {
Serial.begin(9600);
}
void loop(){
x = random(10); // pick some random numbers
y = random(10);
Serial.print("The value of x and y before swapping are: ");
Serial.print(x); Serial.print(","); Serial.println(y);
swap();
Serial.print("The value of x and y after swapping are: ");
Serial.print(x); Serial.print(","); Serial.println(y);Serial.println();
delay(1000);
}
// swap the two global values
void swap()
{
int temp;
temp = x;
x = y;
y = temp;
}
/*
functionReferences sketch
demonstrates returning more than one value by passing references
*/
void setup() {
Serial.begin(9600);
}
void loop(){
int x = random(10); // pick some random numbers
int y = random(10);
Serial.print("The value of x and y before swapping are: ");
Serial.print(x); Serial.print(","); Serial.println(y);
swap(x,y);
Serial.print("The value of x and y after swapping are: ");
Serial.print(x); Serial.print(","); Serial.println(y);Serial.println();
delay(1000);
}
// swap the two given values
void swap(int &value1, int &value2)
{
int temp;
temp = value1;
value1 = value2;
value2 = temp;
}
\ No newline at end of file
/*
Pushbutton sketch
a switch connected to pin 2 lights the LED on pin 13
*/
const int ledPin = 13; // choose the pin for the LED
const int inputPin = 2; // choose the input pin (for a pushbutton)
void setup() {
pinMode(ledPin, OUTPUT); // declare LED pin as output
pinMode(inputPin, INPUT); // declare pushbutton pin as input
}
void loop(){
int val = digitalRead(inputPin); // read input value
if (val == HIGH) // check if the input is HIGH
{
digitalWrite(ledPin, HIGH); // turn LED on if switch is pressed
}
}
/*
Pushbutton sketch
a switch connected to pin 2 lights the LED on pin 13
*/
const int ledPin = 13; // choose the pin for the LED
const int inputPin = 2; // choose the input pin (for a pushbutton)
void setup() {
pinMode(ledPin, OUTPUT); // declare LED pin as output
pinMode(inputPin, INPUT); // declare pushbutton pin as input
}
void loop(){
int val = digitalRead(inputPin); // read input value
if (val == HIGH) // check if the input is HIGH
{
// do this if val is HIGH
digitalWrite(ledPin, HIGH); // turn LED on if switch is pressed
}
else
{
// else do this if val is not HIGH
digitalWrite(ledPin, LOW); // turn LED off
}
}
/*
* Repeat
* blinks while a condition is true
*/
const int ledPin = 13; // digital pin the LED is connected to
const int sensorPin = 0; // analog input 0
void setup()
{
Serial.begin(9600);
pinMode(ledPin,OUTPUT); // enable LED pin as output
}
void loop()
{
while(analogRead(sensorPin) > 100)
{
blink(); // call a function to turn an LED on and off
Serial.print(".");
}
Serial.println(analogRead(sensorPin)); // this is not executed until after
// the while loop finishes!!!
}
void blink()
{
digitalWrite(ledPin, HIGH);
delay(100);
digitalWrite(ledPin, LOW);
delay(100);
}
/*
ForLoop sketch
demonstrates for loop
*/
void setup() {
Serial.begin(9600);}
void loop(){
Serial.println("for(int i=0; i < 4; i++)");
for(int i=0; i < 4; i++)
{
Serial.println(i);
}
}
/*
* SwitchCase sketch
* example showing switch statement by switching on chars from the serial port
*
* sending the character 1 blinks the LED once, sending 2 blinks twice
* sending + turns the LED on, sending - turns it off
* any other character prints a message to the Serial Monitor
*/
const int ledPin = 13; // the pin the LED is connected to
void setup()
{
Serial.begin(9600); // Initialize serial port to send and
// receive at 9600 baud
pinMode(ledPin, OUTPUT);
}
void loop()
{
if ( Serial.available()) // Check to see if at least one
// character is available
{
char ch = Serial.read();
switch(ch)
{
case '1':
blink();
break;
case '2':
blink();
blink();
break;
case '+':
digitalWrite(ledPin,HIGH);
break;
case '-':
digitalWrite(ledPin,LOW);
break;
default :
Serial.print(ch);
Serial.println(" was received but not expected");
break;
}
}
}
void blink()
{
digitalWrite(ledPin,HIGH);
delay(500);
digitalWrite(ledPin,LOW);
delay(500);
}
\ No newline at end of file
/*
* RelationalExpressions sketch
* demonstrates comparing values
*/
int i = 1; // some values to start with
int j = 2;
void setup() {
Serial.begin(9600);
}
void loop(){
Serial.print("i = ");
Serial.print(i);
Serial.print(" and j = ");
Serial.println(j);
if(i < j)
Serial.println(" i is less than j");
if(i <= j)
Serial.println(" i is less than or equal to j");
if(i != j)
Serial.println(" i is not equal to j");
if(i == j)
Serial.println(" i is equal to j");
if(i >= j)
Serial.println(" i is greater than or equal to j");
if(i > j)
Serial.println(" i is greater than j");
Serial.println();
i = i + 1;
if(i > j + 1)
delay(10000); // long delay after i is no longer close to j
}
/*
* bits sketch
* demonstrates bitwise operators
*/
void setup() {
Serial.begin(9600);
}
void loop(){
Serial.print("3 & 1 equals "); // bitwise And 3 and 1
Serial.print(3 & 1); // print the result
Serial.print(" decimal, or in binary: ");
Serial.println(3 & 1 , BIN); // print the binary
// representation of the result
Serial.print("3 | 1 equals "); // bitwise Or 3 and 1
Serial.print(3 | 1 );
Serial.print(" decimal, or in binary: ");
Serial.println(3 | 1 , BIN); // print the binary
// representation of the result
Serial.print("3 ^ 1 equals "); // bitwise exclusive or 3 and 1
Serial.print(3 ^ 1);
Serial.print(" decimal, or in binary: ");
Serial.println(3 ^ 1 , BIN); // print the binary
// representation of the result
byte byteVal = 1;
int intVal = 1;
byteVal = ~byteVal; // do the bitwise negate
intVal = ~intVal;
Serial.print("~byteVal (1) equals "); // bitwise negate an 8 bit value
Serial.println(byteVal, BIN); // print the binary
// representation of the result
Serial.print("~intVal (1) equals "); // bitwise negate a 16 bit value
Serial.println(intVal, BIN); // print the binary
// representation of the result
delay(10000);
}
/*
* Floating-point example
* This sketch initialized a float value to 1.1
* It repeatedly reduces the value by 0.1 until the value is 0
*/
float value = 1.1;
void setup()
{
Serial.begin(9600);
}
void loop()
{
value = value - 0.1; // reduce value by 0.1 each time through the loop
if( value == 0)
Serial.println("The value is exactly zero");
else if(almostEqual(value, 0))
{
Serial.print("The value ");
Serial.print(value,7); // print to 7 decimal places
Serial.println(" is almost equal to zero");
}
else
Serial.println(value);
delay(100);
}
// returns true if the difference between a and b is small
// set value of DELTA to the maximum difference considered to be equal
boolean almostEqual(float a, float b)
{
const float DELTA = .00001; // max difference to be almost equal
if (a == 0) return fabs(b) <= DELTA;
if (b == 0) return fabs(a) <= DELTA;
return fabs((a - b) / max(fabs(a), fabs(b))) <= DELTA ;
}
/*
array sketch
an array of switches controls an array of LEDs
see Chapter 5 for more on using switches
see Chapter 7 for information on LEDs
*/
int inputPins[] = {2,3,4,5}; // create an array of pins for switch inputs
int ledPins[] = {10,11,12,13}; // create array of output pins for LEDs
void setup()
{
for(int index = 0; index < 4; index++)
{
pinMode(ledPins[index], OUTPUT); // declare LED as output
pinMode(inputPins[index], INPUT); // declare pushbutton as input
digitalWrite(inputPins[index],HIGH); // enable pull-up resistors
//(see Recipe 5.2)
}
}
void loop(){
for(int index = 0; index < 4; index++)
{
int val = digitalRead(inputPins[index]); // read input value
if (val == LOW) // check if the switch is pressed
{
digitalWrite(ledPins[index], HIGH); // turn LED on if switch is pressed
}
else
{
digitalWrite(ledPins[index], LOW); // turn LED off
}
}
}
/*
Basic_Strings sketch
*/
String text1 = "This string";
String text2 = " has more text";
String text3; // to be assigned within the sketch
void setup()
{
Serial.begin(9600);
Serial.print( text1);
Serial.print(" is ");
Serial.print(text1.length());
Serial.println(" characters long.");
Serial.print("text2 is ");
Serial.print(text2.length());
Serial.println(" characters long.");
text1.concat(text2);
Serial.println("text1 now contains: ");
Serial.println(text1);
}
void loop()
{
}
/*
* SplitSplit sketch
* split a comma-separated string
*/
String text = "Peter,Paul,Mary"; // an example string
String message = text; // holds text not yet split
int commaPosition; // the position of the next comma in the string
void setup()
{
Serial.begin(9600);
Serial.println(message); // show the source string
do
{
commaPosition = message.indexOf(',');
if(commaPosition != -1)
{
Serial.println( message.substring(0,commaPosition));
message = message.substring(commaPosition+1, message.length());
}
else
{ // here after the last comma is found
if(message.length() > 0)
Serial.println(message); // if there is text after the last comma,
// print it
}
}
while(commaPosition >=0);
}
void loop()
{
}
\ No newline at end of file
/*
* SplitSplit sketch
* split a comma-separated string
*/
const int MAX_STRING_LEN = 20; // set this to the largest string
// you'll process
char stringList[] = "Peter,Paul,Mary"; // an example string
char stringBuffer[MAX_STRING_LEN+1]; // static buffer for computation & output
void setup()
{
Serial.begin(9600);
}
void loop()
{
char *str;
char *p;
strncpy(stringBuffer, stringList, MAX_STRING_LEN); // copy source string
Serial.println(stringBuffer); // show the source string
for( str = strtok_r(stringBuffer, ",", &p); // split using comma
str; // loop while str is
// not null
str = strtok_r(NULL, ",", &p) // get subsequent tokens
)
{
Serial.println(str);
if(strcmp(str, "Paul") == 0)
Serial.println("found Paul");
}
delay(5000);
}
/*
* NumberToString
* Creates a string from a given number
*/
void setup()
{
Serial.begin(9600);
}
char buffer[12]; // long data type has 11 characters (including the
// minus sign) and a terminating null
void loop()
{
long value = 12345;
ltoa(value, buffer, 10);
Serial.print( value);
Serial.print(" has ");
Serial.print(strlen(buffer));
Serial.println(" digits");
value = 123456789;
ltoa(value, buffer, 10);
Serial.print( value);
Serial.print(" has ");
Serial.print(strlen(buffer));
Serial.println(" digits");
delay(1000);
}
/*
* StringToNumber
* Creates a number from a string
*/
const int ledPin = 13; // pin the LED is connected to
int blinkDelay; // blink rate determined by this variable
char strValue[6]; // must be big enough to hold all the digits and the
// 0 that terminates the string
int index = 0; // the index into the array storing the received digits
void setup()
{
Serial.begin(9600);
pinMode(ledPin,OUTPUT); // enable LED pin as output
}
void loop()
{
if( Serial.available())
{
char ch = Serial.read();
if(index < 5 && isDigit(ch) ){
strValue[index++] = ch; // add the ASCII character to the string;
}
else
{
// here when buffer full or on the first non digit
strValue[index] = 0; // terminate the string with a 0
blinkDelay = atoi(strValue); // use atoi to convert the string to an int
index = 0;
}
}
blink();
}
void blink()
{
digitalWrite(ledPin, HIGH);
delay(blinkDelay/2); // wait for half the blink period
digitalWrite(ledPin, LOW);
delay(blinkDelay/2); // wait for the other half
}
\ No newline at end of file
// Random
// demonstrates generating random numbers
int randNumber;
void setup()
{
Serial.begin(9600);
// Print random numbers with no seed value
Serial.println("Print 20 random numbers between 0 and 9");
for(int i=0; i < 20; i++)
{
randNumber = random(10);
Serial.print(randNumber);
Serial.print(" ");
}
Serial.println();
Serial.println("Print 20 random numbers between 2 and 9");
for(int i=0; i < 20; i++)
{
randNumber = random(2,10);
Serial.print(randNumber);
Serial.print(" ");
}
// Print random numbers with the same seed value each time
randomSeed(1234);
Serial.println();
Serial.println(
"Print 20 random numbers between 0 and 9 after constant seed ");
for(int i=0; i < 20; i++)
{
randNumber = random(10);
Serial.print(randNumber);
Serial.print(" ");
}
// Print random numbers with a different seed value each time
randomSeed(analogRead(0)); // read from an analog port
// with nothing connected
Serial.println();
Serial.println(
"Print 20 random numbers between 0 and 9 after floating seed ");
for(int i=0; i < 20; i++)
{
randNumber = random(10);
Serial.print(randNumber);
Serial.print(" ");
}
Serial.println();
Serial.println();
}
void loop()
{
}
// bitFunctions
// demonstrates using the bit functions
byte flags = 0; // these examples set, clear or read bits in a variable called flags.
// bitSet example
void setFlag( int flagNumber)
{
bitSet(flags, flagNumber);
}
// bitClear example
void clearFlag( int flagNumber)
{
bitClear(flags, flagNumber);
}
// bitPosition example
int getFlag( int flagNumber)
{
return bitRead(flags, flagNumber);
}
void setup()
{
Serial.begin(9600);
}
void loop()
{
showFlags();
setFlag(2); // set some flags;
setFlag(5);