Examples: mass code format. See example_formatter.conf

This commit is contained in:
Federico Fissore 2015-07-06 15:18:33 +02:00
parent 1af21b2233
commit 5e98cd8528
136 changed files with 1357 additions and 1447 deletions

View File

@ -40,8 +40,7 @@ void setup() {
pinMode(ledPin, OUTPUT); pinMode(ledPin, OUTPUT);
} }
void loop() void loop() {
{
// here is where you'd put code that needs to be running all the time. // here is where you'd put code that needs to be running all the time.
// check to see if it's time to blink the LED; that is, if the // check to see if it's time to blink the LED; that is, if the
@ -50,15 +49,16 @@ void loop()
// blink the LED. // blink the LED.
unsigned long currentMillis = millis(); unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval) { if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED // save the last time you blinked the LED
previousMillis = currentMillis; previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa: // if the LED is off turn it on and vice-versa:
if (ledState == LOW) if (ledState == LOW) {
ledState = HIGH; ledState = HIGH;
else } else {
ledState = LOW; ledState = LOW;
}
// set the LED with the ledState of the variable: // set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState); digitalWrite(ledPin, ledState);

View File

@ -48,8 +48,7 @@ void loop() {
if (buttonState == HIGH) { if (buttonState == HIGH) {
// turn LED on: // turn LED on:
digitalWrite(ledPin, HIGH); digitalWrite(ledPin, HIGH);
} } else {
else {
// turn LED off: // turn LED off:
digitalWrite(ledPin, LOW); digitalWrite(ledPin, LOW);
} }

View File

@ -42,8 +42,7 @@ void loop() {
// button's pressed, and off when it's not: // button's pressed, and off when it's not:
if (sensorVal == HIGH) { if (sensorVal == HIGH) {
digitalWrite(13, LOW); digitalWrite(13, LOW);
} } else {
else {
digitalWrite(13, HIGH); digitalWrite(13, HIGH);
} }
} }

View File

@ -58,8 +58,7 @@ void loop() {
Serial.println("on"); Serial.println("on");
Serial.print("number of button pushes: "); Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter); Serial.println(buttonPushCounter);
} } else {
else {
// if the current state is LOW then the button // if the current state is LOW then the button
// wend from on to off: // wend from on to off:
Serial.println("off"); Serial.println("off");

View File

@ -41,7 +41,7 @@ void loop() {
analogWrite(analogOutPin, outputValue); analogWrite(analogOutPin, outputValue);
// print the results to the serial monitor: // print the results to the serial monitor:
Serial.print("sensor = " ); Serial.print("sensor = ");
Serial.print(sensorValue); Serial.print(sensorValue);
Serial.print("\t output = "); Serial.print("\t output = ");
Serial.println(outputValue); Serial.println(outputValue);

View File

@ -34,13 +34,13 @@ int average = 0; // the average
int inputPin = A0; int inputPin = A0;
void setup() void setup() {
{
// initialize serial communication with computer: // initialize serial communication with computer:
Serial.begin(9600); Serial.begin(9600);
// initialize all the readings to 0: // initialize all the readings to 0:
for (int thisReading = 0; thisReading < numReadings; thisReading++) for (int thisReading = 0; thisReading < numReadings; thisReading++) {
readings[thisReading] = 0; readings[thisReading] = 0;
}
} }
void loop() { void loop() {
@ -54,9 +54,10 @@ void loop() {
readIndex = readIndex + 1; readIndex = readIndex + 1;
// if we're at the end of the array... // if we're at the end of the array...
if (readIndex >= numReadings) if (readIndex >= numReadings) {
// ...wrap around to the beginning: // ...wrap around to the beginning:
readIndex = 0; readIndex = 0;
}
// calculate the average: // calculate the average:
average = total / numReadings; average = total / numReadings;

View File

@ -23,8 +23,7 @@
const int ledPin = 9; // the pin that the LED is attached to const int ledPin = 9; // the pin that the LED is attached to
void setup() void setup() {
{
// initialize the serial communication: // initialize the serial communication:
Serial.begin(9600); Serial.begin(9600);
// initialize the ledPin as an output: // initialize the ledPin as an output:

View File

@ -29,8 +29,7 @@ int secondSensor = 0; // second analog sensor
int thirdSensor = 0; // digital sensor int thirdSensor = 0; // digital sensor
int inByte = 0; // incoming serial byte int inByte = 0; // incoming serial byte
void setup() void setup() {
{
// start serial port at 9600 bps: // start serial port at 9600 bps:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -41,8 +40,7 @@ void setup()
establishContact(); // send a byte to establish contact until receiver responds establishContact(); // send a byte to establish contact until receiver responds
} }
void loop() void loop() {
{
// if we get a valid byte, read analog ins: // if we get a valid byte, read analog ins:
if (Serial.available() > 0) { if (Serial.available() > 0) {
// get incoming byte: // get incoming byte:

View File

@ -33,8 +33,7 @@ int secondSensor = 0; // second analog sensor
int thirdSensor = 0; // digital sensor int thirdSensor = 0; // digital sensor
int inByte = 0; // incoming serial byte int inByte = 0; // incoming serial byte
void setup() void setup() {
{
// start serial port at 9600 bps and wait for port to open: // start serial port at 9600 bps and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -46,8 +45,7 @@ void setup()
establishContact(); // send a byte to establish contact until receiver responds establishContact(); // send a byte to establish contact until receiver responds
} }
void loop() void loop() {
{
// if we get a valid byte, read analog ins: // if we get a valid byte, read analog ins:
if (Serial.available() > 0) { if (Serial.available() > 0) {
// get incoming byte: // get incoming byte:

View File

@ -20,13 +20,11 @@ const int redPin = A0; // sensor to control red color
const int greenPin = A1; // sensor to control green color const int greenPin = A1; // sensor to control green color
const int bluePin = A2; // sensor to control blue color const int bluePin = A2; // sensor to control blue color
void setup() void setup() {
{
Serial.begin(9600); Serial.begin(9600);
} }
void loop() void loop() {
{
Serial.print(analogRead(redPin)); Serial.print(analogRead(redPin));
Serial.print(","); Serial.print(",");
Serial.print(analogRead(greenPin)); Serial.print(analogRead(greenPin));

View File

@ -44,8 +44,7 @@ void loop() {
// if the analog value is high enough, turn on the LED: // if the analog value is high enough, turn on the LED:
if (analogValue > threshold) { if (analogValue > threshold) {
digitalWrite(ledPin, HIGH); digitalWrite(ledPin, HIGH);
} } else {
else {
digitalWrite(ledPin, LOW); digitalWrite(ledPin, LOW);
} }

View File

@ -43,8 +43,8 @@ int sensorValue = 0; // the sensor value
void setup() { void setup() {
// set the LED pins as outputs and the switch pin as input: // set the LED pins as outputs and the switch pin as input:
pinMode(indicatorLedPin, OUTPUT); pinMode(indicatorLedPin, OUTPUT);
pinMode (ledPin, OUTPUT); pinMode(ledPin, OUTPUT);
pinMode (buttonPin, INPUT); pinMode(buttonPin, INPUT);
} }
void loop() { void loop() {

View File

@ -33,8 +33,7 @@ const int xpin = A3; // x-axis of the accelerometer
const int ypin = A2; // y-axis const int ypin = A2; // y-axis
const int zpin = A1; // z-axis (only on 3-axis models) const int zpin = A1; // z-axis (only on 3-axis models)
void setup() void setup() {
{
// initialize the serial communications: // initialize the serial communications:
Serial.begin(9600); Serial.begin(9600);
@ -48,8 +47,7 @@ void setup()
digitalWrite(powerpin, HIGH); digitalWrite(powerpin, HIGH);
} }
void loop() void loop() {
{
// print the sensor values: // print the sensor values:
Serial.print(analogRead(xpin)); Serial.print(analogRead(xpin));
// print a tab between values: // print a tab between values:

View File

@ -31,8 +31,7 @@ void setup() {
Serial.begin(9600); Serial.begin(9600);
} }
void loop() void loop() {
{
// establish variables for duration of the ping, // establish variables for duration of the ping,
// and the distance result in inches and centimeters: // and the distance result in inches and centimeters:
long duration, inches, cm; long duration, inches, cm;
@ -65,8 +64,7 @@ void loop()
delay(100); delay(100);
} }
long microsecondsToInches(long microseconds) long microsecondsToInches(long microseconds) {
{
// According to Parallax's datasheet for the PING))), there are // According to Parallax's datasheet for the PING))), there are
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
// second). This gives the distance travelled by the ping, outbound // second). This gives the distance travelled by the ping, outbound
@ -75,8 +73,7 @@ long microsecondsToInches(long microseconds)
return microseconds / 74 / 2; return microseconds / 74 / 2;
} }
long microsecondsToCentimeters(long microseconds) long microsecondsToCentimeters(long microseconds) {
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter. // 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 // The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled. // object we take half of the distance travelled.

View File

@ -25,7 +25,7 @@ void setup() {
stringOne = String("stringThree = "); stringOne = String("stringThree = ");
stringTwo = String("this string"); stringTwo = String("this string");
stringThree = String (); stringThree = String();
// send an intro: // send an intro:
Serial.println("\n\nAdding strings together (concatenation):"); Serial.println("\n\nAdding strings together (concatenation):");
Serial.println(); Serial.println();

View File

@ -49,16 +49,14 @@ void loop() {
// you can also use equals() to see if two strings are the same: // you can also use equals() to see if two strings are the same:
if (stringOne.equals(stringTwo)) { if (stringOne.equals(stringTwo)) {
Serial.println(stringOne + " equals " + stringTwo); Serial.println(stringOne + " equals " + stringTwo);
} } else {
else {
Serial.println(stringOne + " does not equal " + stringTwo); Serial.println(stringOne + " does not equal " + stringTwo);
} }
// or perhaps you want to ignore case: // or perhaps you want to ignore case:
if (stringOne.equalsIgnoreCase(stringTwo)) { if (stringOne.equalsIgnoreCase(stringTwo)) {
Serial.println(stringOne + " equals (ignoring case) " + stringTwo); Serial.println(stringOne + " equals (ignoring case) " + stringTwo);
} } else {
else {
Serial.println(stringOne + " does not equal (ignoring case) " + stringTwo); Serial.println(stringOne + " does not equal (ignoring case) " + stringTwo);
} }
@ -103,10 +101,9 @@ void loop() {
// comes first in alphanumeric order, then compareTo() is greater than 0: // comes first in alphanumeric order, then compareTo() is greater than 0:
stringOne = "Cucumber"; stringOne = "Cucumber";
stringTwo = "Cucuracha"; stringTwo = "Cucuracha";
if (stringOne.compareTo(stringTwo) < 0 ) { if (stringOne.compareTo(stringTwo) < 0) {
Serial.println(stringOne + " comes before " + stringTwo); Serial.println(stringOne + " comes before " + stringTwo);
} } else {
else {
Serial.println(stringOne + " comes after " + stringTwo); Serial.println(stringOne + " comes after " + stringTwo);
} }
@ -121,10 +118,9 @@ void loop() {
stringOne += analogRead(A0); stringOne += analogRead(A0);
stringTwo += analogRead(A5); stringTwo += analogRead(A5);
if (stringOne.compareTo(stringTwo) < 0 ) { if (stringOne.compareTo(stringTwo) < 0) {
Serial.println(stringOne + " comes before " + stringTwo); Serial.println(stringOne + " comes before " + stringTwo);
} } else {
else {
Serial.println(stringOne + " comes after " + stringTwo); Serial.println(stringOne + " comes after " + stringTwo);
} }

View File

@ -33,7 +33,7 @@ void loop() {
stringOne = "<HTML><HEAD><BODY>"; stringOne = "<HTML><HEAD><BODY>";
int secondOpeningBracket = firstClosingBracket + 1; int secondOpeningBracket = firstClosingBracket + 1;
int secondClosingBracket = stringOne.indexOf('>', secondOpeningBracket ); int secondClosingBracket = stringOne.indexOf('>', secondOpeningBracket);
Serial.println("The index of the second > in the string " + stringOne + " is " + secondClosingBracket); Serial.println("The index of the second > in the string " + stringOne + " is " + secondClosingBracket);
// you can also use indexOf() to search for Strings: // you can also use indexOf() to search for Strings:
@ -43,7 +43,7 @@ void loop() {
stringOne = "<UL><LI>item<LI>item<LI>item</UL>"; stringOne = "<UL><LI>item<LI>item<LI>item</UL>";
int firstListItem = stringOne.indexOf("<LI>"); int firstListItem = stringOne.indexOf("<LI>");
int secondListItem = stringOne.indexOf("item", firstListItem + 1 ); int secondListItem = stringOne.indexOf("item", firstListItem + 1);
Serial.println("The index of the second list item in the string " + stringOne + " is " + secondClosingBracket); Serial.println("The index of the second list item in the string " + stringOne + " is " + secondClosingBracket);
// lastIndexOf() gives you the last occurrence of a character or string: // lastIndexOf() gives you the last occurrence of a character or string:

View File

@ -41,8 +41,7 @@ void loop() {
// if the String's longer than 140 characters, complain: // if the String's longer than 140 characters, complain:
if (txtMsg.length() < 140) { if (txtMsg.length() < 140) {
Serial.println("That's a perfectly acceptable text message"); Serial.println("That's a perfectly acceptable text message");
} } else {
else {
Serial.println("That's too long for a text message."); Serial.println("That's too long for a text message.");
} }
// note the length for next time through the loop: // note the length for next time through the loop:

View File

@ -41,11 +41,10 @@ void loop() {
// endsWith() checks to see if a String ends with a particular character: // endsWith() checks to see if a String ends with a particular character:
String sensorReading = "sensor = "; String sensorReading = "sensor = ";
sensorReading += analogRead(A0); sensorReading += analogRead(A0);
Serial.print (sensorReading); Serial.print(sensorReading);
if (sensorReading.endsWith("0")) { if (sensorReading.endsWith("0")) {
Serial.println(". This reading is divisible by ten"); Serial.println(". This reading is divisible by ten");
} } else {
else {
Serial.println(". This reading is not divisible by ten"); Serial.println(". This reading is not divisible by ten");
} }

View File

@ -40,20 +40,16 @@ void loop() {
if (keyVal == 1023) { if (keyVal == 1023) {
// play the first frequency in the array on pin 8 // play the first frequency in the array on pin 8
tone(8, notes[0]); tone(8, notes[0]);
} } else if (keyVal >= 990 && keyVal <= 1010) {
else if (keyVal >= 990 && keyVal <= 1010) {
// play the second frequency in the array on pin 8 // play the second frequency in the array on pin 8
tone(8, notes[1]); tone(8, notes[1]);
} } else if (keyVal >= 505 && keyVal <= 515) {
else if (keyVal >= 505 && keyVal <= 515) {
// play the third frequency in the array on pin 8 // play the third frequency in the array on pin 8
tone(8, notes[2]); tone(8, notes[2]);
} } else if (keyVal >= 5 && keyVal <= 10) {
else if (keyVal >= 5 && keyVal <= 10) {
// play the fourth frequency in the array on pin 8 // play the fourth frequency in the array on pin 8
tone(8, notes[3]); tone(8, notes[3]);
} } else {
else {
// if the value is out of range, play no tone // if the value is out of range, play no tone
noTone(8); noTone(8);
} }

View File

@ -42,8 +42,7 @@ void loop() {
if (switchState == HIGH) { if (switchState == HIGH) {
// turn motor on: // turn motor on:
digitalWrite(motorPin, HIGH); digitalWrite(motorPin, HIGH);
} } else {
else {
// turn motor off: // turn motor off:
digitalWrite(motorPin, LOW); digitalWrite(motorPin, LOW);
} }

View File

@ -84,8 +84,7 @@ void loop() {
if (motorDirection == 1) { if (motorDirection == 1) {
digitalWrite(controlPin1, HIGH); digitalWrite(controlPin1, HIGH);
digitalWrite(controlPin2, LOW); digitalWrite(controlPin2, LOW);
} } else {
else {
digitalWrite(controlPin1, LOW); digitalWrite(controlPin1, LOW);
digitalWrite(controlPin2, HIGH); digitalWrite(controlPin2, HIGH);
} }
@ -94,8 +93,7 @@ void loop() {
if (motorEnabled == 1) { if (motorEnabled == 1) {
// PWM the enable pin to vary the speed // PWM the enable pin to vary the speed
analogWrite(enablePin, motorSpeed); analogWrite(enablePin, motorSpeed);
} } else { // if the motor is not supposed to be on
else { // if the motor is not supposed to be on
//turn the motor off //turn the motor off
analogWrite(enablePin, 0); analogWrite(enablePin, 0);
} }

View File

@ -100,7 +100,7 @@ void loop() {
Serial.println("the box is locked!"); Serial.println("the box is locked!");
// wait for the servo to move into position // wait for the servo to move into position
delay (1000); delay(1000);
} }
} }

View File

@ -105,8 +105,12 @@ parameter param;
uint8_t hbval = 128; uint8_t hbval = 128;
int8_t hbdelta = 8; int8_t hbdelta = 8;
void heartbeat() { void heartbeat() {
if (hbval > 192) hbdelta = -hbdelta; if (hbval > 192) {
if (hbval < 32) hbdelta = -hbdelta; hbdelta = -hbdelta;
}
if (hbval < 32) {
hbdelta = -hbdelta;
}
hbval += hbdelta; hbval += hbdelta;
analogWrite(LED_HB, hbval); analogWrite(LED_HB, hbval);
delay(20); delay(20);
@ -115,11 +119,17 @@ void heartbeat() {
void loop(void) { void loop(void) {
// is pmode active? // is pmode active?
if (pmode) digitalWrite(LED_PMODE, HIGH); if (pmode) {
else digitalWrite(LED_PMODE, LOW); digitalWrite(LED_PMODE, HIGH);
} else {
digitalWrite(LED_PMODE, LOW);
}
// is there an error? // is there an error?
if (error) digitalWrite(LED_ERR, HIGH); if (error) {
else digitalWrite(LED_ERR, LOW); digitalWrite(LED_ERR, HIGH);
} else {
digitalWrite(LED_ERR, LOW);
}
// light the heartbeat LED // light the heartbeat LED
heartbeat(); heartbeat();
@ -145,13 +155,13 @@ void pulse(int pin, int times) {
delay(PTIME); delay(PTIME);
digitalWrite(pin, LOW); digitalWrite(pin, LOW);
delay(PTIME); delay(PTIME);
} } while (times--);
while (times--);
} }
void prog_lamp(int state) { void prog_lamp(int state) {
if (PROG_FLICKER) if (PROG_FLICKER) {
digitalWrite(LED_PMODE, state); digitalWrite(LED_PMODE, state);
}
} }
void spi_init() { void spi_init() {
@ -163,8 +173,7 @@ void spi_init() {
void spi_wait() { void spi_wait() {
do { do {
} } while (!(SPSR & (1 << SPIF)));
while (!(SPSR & (1 << SPIF)));
} }
uint8_t spi_send(uint8_t b) { uint8_t spi_send(uint8_t b) {
@ -188,8 +197,7 @@ void empty_reply() {
if (CRC_EOP == getch()) { if (CRC_EOP == getch()) {
Serial.print((char)STK_INSYNC); Serial.print((char)STK_INSYNC);
Serial.print((char)STK_OK); Serial.print((char)STK_OK);
} } else {
else {
error++; error++;
Serial.print((char)STK_NOSYNC); Serial.print((char)STK_NOSYNC);
} }
@ -200,8 +208,7 @@ void breply(uint8_t b) {
Serial.print((char)STK_INSYNC); Serial.print((char)STK_INSYNC);
Serial.print((char)b); Serial.print((char)b);
Serial.print((char)STK_OK); Serial.print((char)STK_OK);
} } else {
else {
error++; error++;
Serial.print((char)STK_NOSYNC); Serial.print((char)STK_NOSYNC);
} }
@ -291,7 +298,9 @@ void flash(uint8_t hilo, int addr, uint8_t data) {
data); data);
} }
void commit(int addr) { void commit(int addr) {
if (PROG_FLICKER) prog_lamp(LOW); if (PROG_FLICKER) {
prog_lamp(LOW);
}
spi_transaction(0x4C, (addr >> 8) & 0xFF, addr & 0xFF, 0); spi_transaction(0x4C, (addr >> 8) & 0xFF, addr & 0xFF, 0);
if (PROG_FLICKER) { if (PROG_FLICKER) {
delay(PTIME); delay(PTIME);
@ -301,10 +310,18 @@ void commit(int addr) {
//#define _current_page(x) (here & 0xFFFFE0) //#define _current_page(x) (here & 0xFFFFE0)
int current_page(int addr) { int current_page(int addr) {
if (param.pagesize == 32) return here & 0xFFFFFFF0; if (param.pagesize == 32) {
if (param.pagesize == 64) return here & 0xFFFFFFE0; return here & 0xFFFFFFF0;
if (param.pagesize == 128) return here & 0xFFFFFFC0; }
if (param.pagesize == 256) return here & 0xFFFFFF80; if (param.pagesize == 64) {
return here & 0xFFFFFFE0;
}
if (param.pagesize == 128) {
return here & 0xFFFFFFC0;
}
if (param.pagesize == 256) {
return here & 0xFFFFFF80;
}
return here; return here;
} }
@ -314,8 +331,7 @@ void write_flash(int length) {
if (CRC_EOP == getch()) { if (CRC_EOP == getch()) {
Serial.print((char) STK_INSYNC); Serial.print((char) STK_INSYNC);
Serial.print((char) write_flash_pages(length)); Serial.print((char) write_flash_pages(length));
} } else {
else {
error++; error++;
Serial.print((char) STK_NOSYNC); Serial.print((char) STK_NOSYNC);
} }
@ -386,8 +402,7 @@ void program_page() {
if (CRC_EOP == getch()) { if (CRC_EOP == getch()) {
Serial.print((char) STK_INSYNC); Serial.print((char) STK_INSYNC);
Serial.print(result); Serial.print(result);
} } else {
else {
error++; error++;
Serial.print((char) STK_NOSYNC); Serial.print((char) STK_NOSYNC);
} }
@ -437,8 +452,12 @@ void read_page() {
return; return;
} }
Serial.print((char) STK_INSYNC); Serial.print((char) STK_INSYNC);
if (memtype == 'F') result = flash_read_page(length); if (memtype == 'F') {
if (memtype == 'E') result = eeprom_read_page(length); result = flash_read_page(length);
}
if (memtype == 'E') {
result = eeprom_read_page(length);
}
Serial.print(result); Serial.print(result);
return; return;
} }
@ -543,11 +562,12 @@ int avrisp() {
// anything else we will return STK_UNKNOWN // anything else we will return STK_UNKNOWN
default: default:
error++; error++;
if (CRC_EOP == getch()) if (CRC_EOP == getch()) {
Serial.print((char)STK_UNKNOWN); Serial.print((char)STK_UNKNOWN);
else } else {
Serial.print((char)STK_NOSYNC); Serial.print((char)STK_NOSYNC);
} }
}
} }

44
examples_formatter.conf Normal file
View File

@ -0,0 +1,44 @@
# This configuration file contains a selection of the available options provided by the formatting tool "Artistic Style"
# http://astyle.sourceforge.net/astyle.html
#
# If you wish to change them, don't edit this file.
# Instead, copy it in the same folder of file "preferences.txt" and modify the copy. This way, you won't lose your custom formatter settings when upgrading the IDE
# If you don't know where file preferences.txt is stored, open the IDE, File -> Preferences and you'll find a link
mode=c
# 2 spaces indentation
indent=spaces=2
# also indent macros
indent-preprocessor
# indent classes, switches (and cases), comments starting at column 1
indent-classes
indent-switches
indent-cases
indent-col1-comments
# put a space around operators
pad-oper
# put a space after if/for/while
pad-header
# if you like one-liners, keep them
keep-one-line-statements
style=java
xn
xc
xl
xk
indent-modifiers
N
L
xW
w
xw
U
j

View File

@ -1,2 +1,2 @@
# you need to have astyle installed before running this # you need to have astyle installed before running this
find libraries/ hardware/ -name '*.ino' -exec astyle --options=build/shared/lib/formatter.conf {} \; find -name '*.ino' -exec /home/federico/materiale/works_Arduino/astyle/astyle-code/AStyle/build/gcc/bin/astyle --options=examples_formatter.conf {} \;

View File

@ -10,8 +10,7 @@
#include <EEPROM.h> #include <EEPROM.h>
void setup() void setup() {
{
/*** /***
Iterate through each byte of the EEPROM storage. Iterate through each byte of the EEPROM storage.
@ -25,11 +24,14 @@ void setup()
This will make your code portable to all AVR processors. This will make your code portable to all AVR processors.
***/ ***/
for ( int i = 0 ; i < EEPROM.length() ; i++ ) for (int i = 0 ; i < EEPROM.length() ; i++) {
EEPROM.write(i, 0); EEPROM.write(i, 0);
}
// turn the LED on when we're done // turn the LED on when we're done
digitalWrite(13, HIGH); digitalWrite(13, HIGH);
} }
void loop(){ /** Empty loop. **/ } void loop() {
/** Empty loop. **/
}

View File

@ -10,7 +10,7 @@
#include <Arduino.h> #include <Arduino.h>
#include <EEPROM.h> #include <EEPROM.h>
void setup(){ void setup() {
//Start serial //Start serial
Serial.begin(9600); Serial.begin(9600);
@ -19,18 +19,20 @@ void setup(){
} }
//Print length of data to run CRC on. //Print length of data to run CRC on.
Serial.print( "EEPROM length: " ); Serial.print("EEPROM length: ");
Serial.println( EEPROM.length() ); Serial.println(EEPROM.length());
//Print the result of calling eeprom_crc() //Print the result of calling eeprom_crc()
Serial.print( "CRC32 of EEPROM data: 0x" ); Serial.print("CRC32 of EEPROM data: 0x");
Serial.println( eeprom_crc(), HEX ); Serial.println(eeprom_crc(), HEX);
Serial.print( "\n\nDone!" ); Serial.print("\n\nDone!");
} }
void loop(){ /* Empty loop */ } void loop() {
/* Empty loop */
}
unsigned long eeprom_crc( void ){ unsigned long eeprom_crc(void) {
const unsigned long crc_table[16] = { const unsigned long crc_table[16] = {
0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac,
@ -41,9 +43,9 @@ unsigned long eeprom_crc( void ){
unsigned long crc = ~0L; unsigned long crc = ~0L;
for( int index = 0 ; index < EEPROM.length() ; ++index ){ for (int index = 0 ; index < EEPROM.length() ; ++index) {
crc = crc_table[( crc ^ EEPROM[index] ) & 0x0f] ^ (crc >> 4); crc = crc_table[(crc ^ EEPROM[index]) & 0x0f] ^ (crc >> 4);
crc = crc_table[( crc ^ ( EEPROM[index] >> 4 )) & 0x0f] ^ (crc >> 4); crc = crc_table[(crc ^ (EEPROM[index] >> 4)) & 0x0f] ^ (crc >> 4);
crc = ~crc; crc = ~crc;
} }
return crc; return crc;

View File

@ -17,20 +17,20 @@
#include <EEPROM.h> #include <EEPROM.h>
void setup(){ void setup() {
float f = 0.00f; //Variable to store data read from EEPROM. float f = 0.00f; //Variable to store data read from EEPROM.
int eeAddress = 0; //EEPROM address to start reading from int eeAddress = 0; //EEPROM address to start reading from
Serial.begin( 9600 ); Serial.begin(9600);
while (!Serial) { while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only ; // wait for serial port to connect. Needed for Leonardo only
} }
Serial.print( "Read float from EEPROM: " ); Serial.print("Read float from EEPROM: ");
//Get the float data from the EEPROM at position 'eeAddress' //Get the float data from the EEPROM at position 'eeAddress'
EEPROM.get( eeAddress, f ); EEPROM.get(eeAddress, f);
Serial.println( f, 3 ); //This may print 'ovf, nan' if the data inside the EEPROM is not a valid float. Serial.println(f, 3); //This may print 'ovf, nan' if the data inside the EEPROM is not a valid float.
/*** /***
As get also returns a reference to 'f', you can use it inline. As get also returns a reference to 'f', you can use it inline.
@ -45,22 +45,24 @@ void setup(){
secondTest(); //Run the next test. secondTest(); //Run the next test.
} }
struct MyObject{ struct MyObject {
float field1; float field1;
byte field2; byte field2;
char name[10]; char name[10];
}; };
void secondTest(){ void secondTest() {
int eeAddress = sizeof(float); //Move address to the next byte after float 'f'. int eeAddress = sizeof(float); //Move address to the next byte after float 'f'.
MyObject customVar; //Variable to store custom object read from EEPROM. MyObject customVar; //Variable to store custom object read from EEPROM.
EEPROM.get( eeAddress, customVar ); EEPROM.get(eeAddress, customVar);
Serial.println( "Read custom object from EEPROM: " ); Serial.println("Read custom object from EEPROM: ");
Serial.println( customVar.field1 ); Serial.println(customVar.field1);
Serial.println( customVar.field2 ); Serial.println(customVar.field2);
Serial.println( customVar.name ); Serial.println(customVar.name);
} }
void loop(){ /* Empty loop */ } void loop() {
/* Empty loop */
}

View File

@ -19,7 +19,7 @@ void setup() {
Iterate the EEPROM using a for loop. Iterate the EEPROM using a for loop.
***/ ***/
for( int index = 0 ; index < EEPROM.length() ; index++ ){ for (int index = 0 ; index < EEPROM.length() ; index++) {
//Add one to each cell in the EEPROM //Add one to each cell in the EEPROM
EEPROM[ index ] += 1; EEPROM[ index ] += 1;
@ -31,7 +31,7 @@ void setup() {
int index = 0; int index = 0;
while( index < EEPROM.length() ){ while (index < EEPROM.length()) {
//Add one to each cell in the EEPROM //Add one to each cell in the EEPROM
EEPROM[ index ] += 1; EEPROM[ index ] += 1;
@ -44,14 +44,14 @@ void setup() {
int idx = 0; //Used 'idx' to avoid name conflict with 'index' above. int idx = 0; //Used 'idx' to avoid name conflict with 'index' above.
do{ do {
//Add one to each cell in the EEPROM //Add one to each cell in the EEPROM
EEPROM[ idx ] += 1; EEPROM[ idx ] += 1;
idx++; idx++;
}while( idx < EEPROM.length() ); } while (idx < EEPROM.length());
} //End of setup function. } //End of setup function.
void loop(){} void loop() {}

View File

@ -16,13 +16,13 @@
#include <EEPROM.h> #include <EEPROM.h>
struct MyObject{ struct MyObject {
float field1; float field1;
byte field2; byte field2;
char name[10]; char name[10];
}; };
void setup(){ void setup() {
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -34,7 +34,7 @@ void setup(){
//One simple call, with the address first and the object second. //One simple call, with the address first and the object second.
EEPROM.put( eeAddress, f ); EEPROM.put(eeAddress, f);
Serial.println("Written float data type!"); Serial.println("Written float data type!");
@ -49,8 +49,10 @@ void setup(){
eeAddress += sizeof(float); //Move address to the next byte after float 'f'. eeAddress += sizeof(float); //Move address to the next byte after float 'f'.
EEPROM.put( eeAddress, customVar ); EEPROM.put(eeAddress, customVar);
Serial.print( "Written custom data type! \n\nView the example sketch eeprom_get to see how you can retrieve the values!" ); Serial.print("Written custom data type! \n\nView the example sketch eeprom_get to see how you can retrieve the values!");
} }
void loop(){ /* Empty loop */ } void loop() {
/* Empty loop */
}

View File

@ -12,8 +12,7 @@
int address = 0; int address = 0;
byte value; byte value;
void setup() void setup() {
{
// initialize serial and wait for port to open: // initialize serial and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -21,8 +20,7 @@ void setup()
} }
} }
void loop() void loop() {
{
// read a byte from the current address of the EEPROM // read a byte from the current address of the EEPROM
value = EEPROM.read(address); value = EEPROM.read(address);
@ -43,8 +41,9 @@ void loop()
This will make your code portable to all AVR processors. This will make your code portable to all AVR processors.
***/ ***/
address = address + 1; address = address + 1;
if(address == EEPROM.length()) if (address == EEPROM.length()) {
address = 0; address = 0;
}
/*** /***
As the EEPROM sizes are powers of two, wrapping (preventing overflow) of an As the EEPROM sizes are powers of two, wrapping (preventing overflow) of an

View File

@ -16,10 +16,11 @@
/** the current address in the EEPROM (i.e. which byte we're going to write to next) **/ /** the current address in the EEPROM (i.e. which byte we're going to write to next) **/
int address = 0; int address = 0;
void setup(){ /** EMpty setup **/ } void setup() {
/** EMpty setup **/
}
void loop() void loop() {
{
/*** /***
need to divide by 4 because analog inputs range from need to divide by 4 because analog inputs range from
0 to 1023 and each byte of the EEPROM can only hold a 0 to 1023 and each byte of the EEPROM can only hold a
@ -55,8 +56,9 @@ void loop()
This will make your code portable to all AVR processors. This will make your code portable to all AVR processors.
***/ ***/
address = address + 1; address = address + 1;
if(address == EEPROM.length()) if (address == EEPROM.length()) {
address = 0; address = 0;
}
/*** /***
As the EEPROM sizes are powers of two, wrapping (preventing overflow) of an As the EEPROM sizes are powers of two, wrapping (preventing overflow) of an

View File

@ -11,10 +11,11 @@
/** the current address in the EEPROM (i.e. which byte we're going to write to next) **/ /** the current address in the EEPROM (i.e. which byte we're going to write to next) **/
int addr = 0; int addr = 0;
void setup(){ /** Empty setup. **/} void setup() {
/** Empty setup. **/
}
void loop() void loop() {
{
/*** /***
Need to divide by 4 because analog inputs range from Need to divide by 4 because analog inputs range from
0 to 1023 and each byte of the EEPROM can only hold a 0 to 1023 and each byte of the EEPROM can only hold a
@ -43,8 +44,9 @@ void loop()
This will make your code portable to all AVR processors. This will make your code portable to all AVR processors.
***/ ***/
addr = addr + 1; addr = addr + 1;
if(addr == EEPROM.length()) if (addr == EEPROM.length()) {
addr = 0; addr = 0;
}
/*** /***
As the EEPROM sizes are powers of two, wrapping (preventing overflow) of an As the EEPROM sizes are powers of two, wrapping (preventing overflow) of an

View File

@ -85,7 +85,7 @@ void loop() {
} }
//Read from or write to register from the SCP1000: //Read from or write to register from the SCP1000:
unsigned int readRegister(byte thisRegister, int bytesToRead ) { unsigned int readRegister(byte thisRegister, int bytesToRead) {
byte inByte = 0; // incoming byte from the SPI byte inByte = 0; // incoming byte from the SPI
unsigned int result = 0; // result to return unsigned int result = 0; // result to return
Serial.print(thisRegister, BIN); Serial.print(thisRegister, BIN);
@ -117,7 +117,7 @@ unsigned int readRegister(byte thisRegister, int bytesToRead ) {
// take the chip select high to de-select: // take the chip select high to de-select:
digitalWrite(chipSelectPin, HIGH); digitalWrite(chipSelectPin, HIGH);
// return the result: // return the result:
return(result); return (result);
} }

View File

@ -36,7 +36,7 @@ const int slaveSelectPin = 10;
void setup() { void setup() {
// set the slaveSelectPin as an output: // set the slaveSelectPin as an output:
pinMode (slaveSelectPin, OUTPUT); pinMode(slaveSelectPin, OUTPUT);
// initialize SPI: // initialize SPI:
SPI.begin(); SPI.begin();
} }

View File

@ -29,8 +29,7 @@
SoftwareSerial mySerial(10, 11); // RX, TX SoftwareSerial mySerial(10, 11); // RX, TX
void setup() void setup() {
{
// Open serial communications and wait for port to open: // Open serial communications and wait for port to open:
Serial.begin(57600); Serial.begin(57600);
while (!Serial) { while (!Serial) {
@ -45,11 +44,12 @@ void setup()
mySerial.println("Hello, world?"); mySerial.println("Hello, world?");
} }
void loop() // run over and over void loop() { // run over and over
{ if (mySerial.available()) {
if (mySerial.available())
Serial.write(mySerial.read()); Serial.write(mySerial.read());
if (Serial.available()) }
if (Serial.available()) {
mySerial.write(Serial.read()); mySerial.write(Serial.read());
}
} }

View File

@ -42,8 +42,7 @@ SoftwareSerial portOne(10, 11);
// on the Mega, use other pins instead, since 8 and 9 don't work on the Mega // on the Mega, use other pins instead, since 8 and 9 don't work on the Mega
SoftwareSerial portTwo(8, 9); SoftwareSerial portTwo(8, 9);
void setup() void setup() {
{
// Open serial communications and wait for port to open: // Open serial communications and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -56,8 +55,7 @@ void setup()
portTwo.begin(9600); portTwo.begin(9600);
} }
void loop() void loop() {
{
// By default, the last intialized port is listening. // By default, the last intialized port is listening.
// when you want to listen on a port, explicitly select it: // when you want to listen on a port, explicitly select it:
portOne.listen(); portOne.listen();

View File

@ -12,16 +12,14 @@
#include <Wire.h> #include <Wire.h>
void setup() void setup() {
{
Wire.begin(); // join i2c bus (address optional for master) Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial communication at 9600bps Serial.begin(9600); // start serial communication at 9600bps
} }
int reading = 0; int reading = 0;
void loop() void loop() {
{
// step 1: instruct sensor to read echoes // step 1: instruct sensor to read echoes
Wire.beginTransmission(112); // transmit to device #112 (0x70) Wire.beginTransmission(112); // transmit to device #112 (0x70)
// the address specified in the datasheet is 224 (0xE0) // the address specified in the datasheet is 224 (0xE0)
@ -44,8 +42,7 @@ void loop()
Wire.requestFrom(112, 2); // request 2 bytes from slave device #112 Wire.requestFrom(112, 2); // request 2 bytes from slave device #112
// step 5: receive reading from sensor // step 5: receive reading from sensor
if (2 <= Wire.available()) // if two bytes were received if (2 <= Wire.available()) { // if two bytes were received
{
reading = Wire.read(); // receive high byte (overwrites previous reading) reading = Wire.read(); // receive high byte (overwrites previous reading)
reading = reading << 8; // shift high byte to be high 8 bits reading = reading << 8; // shift high byte to be high 8 bits
reading |= Wire.read(); // receive low byte as lower 8 bits reading |= Wire.read(); // receive low byte as lower 8 bits

View File

@ -14,15 +14,13 @@
#include <Wire.h> #include <Wire.h>
void setup() void setup() {
{
Wire.begin(); // join i2c bus (address optional for master) Wire.begin(); // join i2c bus (address optional for master)
} }
byte val = 0; byte val = 0;
void loop() void loop() {
{
Wire.beginTransmission(44); // transmit to device #44 (0x2c) Wire.beginTransmission(44); // transmit to device #44 (0x2c)
// device address is specified in datasheet // device address is specified in datasheet
Wire.write(byte(0x00)); // sends instruction byte Wire.write(byte(0x00)); // sends instruction byte
@ -30,8 +28,7 @@ void loop()
Wire.endTransmission(); // stop transmitting Wire.endTransmission(); // stop transmitting
val++; // increment value val++; // increment value
if (val == 64) // if reached 64th position (max) if (val == 64) { // if reached 64th position (max)
{
val = 0; // start over from lowest value val = 0; // start over from lowest value
} }
delay(500); delay(500);

View File

@ -12,18 +12,15 @@
#include <Wire.h> #include <Wire.h>
void setup() void setup() {
{
Wire.begin(); // join i2c bus (address optional for master) Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output Serial.begin(9600); // start serial for output
} }
void loop() void loop() {
{
Wire.requestFrom(8, 6); // request 6 bytes from slave device #8 Wire.requestFrom(8, 6); // request 6 bytes from slave device #8
while (Wire.available()) // slave may send less than requested while (Wire.available()) { // slave may send less than requested
{
char c = Wire.read(); // receive a byte as character char c = Wire.read(); // receive a byte as character
Serial.print(c); // print the character Serial.print(c); // print the character
} }

View File

@ -12,15 +12,13 @@
#include <Wire.h> #include <Wire.h>
void setup() void setup() {
{
Wire.begin(); // join i2c bus (address optional for master) Wire.begin(); // join i2c bus (address optional for master)
} }
byte x = 0; byte x = 0;
void loop() void loop() {
{
Wire.beginTransmission(8); // transmit to device #8 Wire.beginTransmission(8); // transmit to device #8
Wire.write("x is "); // sends five bytes Wire.write("x is "); // sends five bytes
Wire.write(x); // sends one byte Wire.write(x); // sends one byte

View File

@ -12,24 +12,20 @@
#include <Wire.h> #include <Wire.h>
void setup() void setup() {
{
Wire.begin(8); // join i2c bus with address #8 Wire.begin(8); // join i2c bus with address #8
Wire.onReceive(receiveEvent); // register event Wire.onReceive(receiveEvent); // register event
Serial.begin(9600); // start serial for output Serial.begin(9600); // start serial for output
} }
void loop() void loop() {
{
delay(100); delay(100);
} }
// function that executes whenever data is received from master // function that executes whenever data is received from master
// this function is registered as an event, see setup() // this function is registered as an event, see setup()
void receiveEvent(int howMany) void receiveEvent(int howMany) {
{ while (1 < Wire.available()) { // loop through all but the last
while (1 < Wire.available()) // loop through all but the last
{
char c = Wire.read(); // receive byte as a character char c = Wire.read(); // receive byte as a character
Serial.print(c); // print the character Serial.print(c); // print the character
} }

View File

@ -12,21 +12,18 @@
#include <Wire.h> #include <Wire.h>
void setup() void setup() {
{
Wire.begin(8); // join i2c bus with address #8 Wire.begin(8); // join i2c bus with address #8
Wire.onRequest(requestEvent); // register event Wire.onRequest(requestEvent); // register event
} }
void loop() void loop() {
{
delay(100); delay(100);
} }
// function that executes whenever data is requested by master // function that executes whenever data is requested by master
// this function is registered as an event, see setup() // this function is registered as an event, see setup()
void requestEvent() void requestEvent() {
{
Wire.write("hello "); // respond with message of 6 bytes Wire.write("hello "); // respond with message of 6 bytes
// as expected by master // as expected by master
} }

View File

@ -85,7 +85,7 @@ void loop() {
} }
//Read from or write to register from the SCP1000: //Read from or write to register from the SCP1000:
unsigned int readRegister(byte thisRegister, int bytesToRead ) { unsigned int readRegister(byte thisRegister, int bytesToRead) {
byte inByte = 0; // incoming byte from the SPI byte inByte = 0; // incoming byte from the SPI
unsigned int result = 0; // result to return unsigned int result = 0; // result to return
Serial.print(thisRegister, BIN); Serial.print(thisRegister, BIN);
@ -117,7 +117,7 @@ unsigned int readRegister(byte thisRegister, int bytesToRead ) {
// take the chip select high to de-select: // take the chip select high to de-select:
digitalWrite(chipSelectPin, HIGH); digitalWrite(chipSelectPin, HIGH);
// return the result: // return the result:
return(result); return (result);
} }

View File

@ -36,7 +36,7 @@ const int slaveSelectPin = 10;
void setup() { void setup() {
// set the slaveSelectPin as an output: // set the slaveSelectPin as an output:
pinMode (slaveSelectPin, OUTPUT); pinMode(slaveSelectPin, OUTPUT);
// initialize SPI: // initialize SPI:
SPI.begin(); SPI.begin();
} }

View File

@ -22,8 +22,7 @@
#include <SPI.h> #include <SPI.h>
#include <Audio.h> #include <Audio.h>
void setup() void setup() {
{
// debug output at 9600 baud // debug output at 9600 baud
Serial.begin(9600); Serial.begin(9600);
@ -42,8 +41,7 @@ void setup()
Audio.begin(88200, 100); Audio.begin(88200, 100);
} }
void loop() void loop() {
{
int count = 0; int count = 0;
// open wave file from sdcard // open wave file from sdcard

View File

@ -9,18 +9,18 @@
Possible commands created in this shetch: Possible commands created in this shetch:
* "/arduino/digital/13" -> digitalRead(13) "/arduino/digital/13" -> digitalRead(13)
* "/arduino/digital/13/1" -> digitalWrite(13, HIGH) "/arduino/digital/13/1" -> digitalWrite(13, HIGH)
* "/arduino/analog/2/123" -> analogWrite(2, 123) "/arduino/analog/2/123" -> analogWrite(2, 123)
* "/arduino/analog/2" -> analogRead(2) "/arduino/analog/2" -> analogRead(2)
* "/arduino/mode/13/input" -> pinMode(13, INPUT) "/arduino/mode/13/input" -> pinMode(13, INPUT)
* "/arduino/mode/13/output" -> pinMode(13, OUTPUT) "/arduino/mode/13/output" -> pinMode(13, OUTPUT)
This example code is part of the public domain This example code is part of the public domain
http://www.arduino.cc/en/Tutorial/Bridge http://www.arduino.cc/en/Tutorial/Bridge
*/ */
#include <Bridge.h> #include <Bridge.h>
#include <BridgeServer.h> #include <BridgeServer.h>
@ -90,8 +90,7 @@ void digitalCommand(BridgeClient client) {
if (client.read() == '/') { if (client.read() == '/') {
value = client.parseInt(); value = client.parseInt();
digitalWrite(pin, value); digitalWrite(pin, value);
} } else {
else {
value = digitalRead(pin); value = digitalRead(pin);
} }
@ -130,8 +129,7 @@ void analogCommand(BridgeClient client) {
String key = "D"; String key = "D";
key += pin; key += pin;
Bridge.put(key, String(value)); Bridge.put(key, String(value));
} } else {
else {
// Read analog pin // Read analog pin
value = analogRead(pin); value = analogRead(pin);

View File

@ -49,8 +49,7 @@ void loop() {
// Ask again for name and clear the old name // Ask again for name and clear the old name
Console.println("Hi, what's your name?"); Console.println("Hi, what's your name?");
name = ""; // clear the name string name = ""; // clear the name string
} } else { // if the buffer is empty Cosole.read() returns -1
else { // if the buffer is empty Cosole.read() returns -1
name += c; // append the read char from Console to the name string name += c; // append the read char from Console to the name string
} }
} else { } else {

View File

@ -43,7 +43,7 @@ void setup() {
} }
void loop () { void loop() {
// make a string that start with a timestamp for assembling the data to log: // make a string that start with a timestamp for assembling the data to log:
String dataString; String dataString;
dataString += getTimeStamp(); dataString += getTimeStamp();
@ -93,9 +93,10 @@ String getTimeStamp() {
// read the output of the command // read the output of the command
while (time.available() > 0) { while (time.available() > 0) {
char c = time.read(); char c = time.read();
if (c != '\n') if (c != '\n') {
result += c; result += c;
} }
}
return result; return result;
} }

View File

@ -43,11 +43,9 @@ void loop() {
String message; String message;
// if there is a message in the Mailbox // if there is a message in the Mailbox
if (Mailbox.messageAvailable()) if (Mailbox.messageAvailable()) {
{
// read all the messages present in the queue // read all the messages present in the queue
while (Mailbox.messageAvailable()) while (Mailbox.messageAvailable()) {
{
Mailbox.readMessage(message); Mailbox.readMessage(message);
Serial.println(message); Serial.println(message);
} }

View File

@ -40,7 +40,9 @@ void setup() {
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while (!Serial) { ; } while (!Serial) {
;
}
// start-up the bridge // start-up the bridge
Bridge.begin(); Bridge.begin();
@ -76,10 +78,10 @@ void loop() {
sb.monitor(); sb.monitor();
// connected to spacebrew then send a string every 2 seconds // connected to spacebrew then send a string every 2 seconds
if ( sb.connected() ) { if (sb.connected()) {
// check if it is time to send a new message // check if it is time to send a new message
if ( (millis() - last) > interval ) { if ((millis() - last) > interval) {
String test_str_msg = "testing, testing, "; String test_str_msg = "testing, testing, ";
test_str_msg += counter; test_str_msg += counter;
counter ++; counter ++;
@ -98,21 +100,21 @@ void loop() {
// define handler methods, all standard data type handlers take two appropriate arguments // define handler methods, all standard data type handlers take two appropriate arguments
void handleRange (String route, int value) { void handleRange(String route, int value) {
Serial.print("Range msg "); Serial.print("Range msg ");
Serial.print(route); Serial.print(route);
Serial.print(", value "); Serial.print(", value ");
Serial.println(value); Serial.println(value);
} }
void handleString (String route, String value) { void handleString(String route, String value) {
Serial.print("String msg "); Serial.print("String msg ");
Serial.print(route); Serial.print(route);
Serial.print(", value "); Serial.print(", value ");
Serial.println(value); Serial.println(value);
} }
void handleBoolean (String route, boolean value) { void handleBoolean(String route, boolean value) {
Serial.print("Boolen msg "); Serial.print("Boolen msg ");
Serial.print(route); Serial.print(route);
Serial.print(", value "); Serial.print(", value ");
@ -121,7 +123,7 @@ void handleBoolean (String route, boolean value) {
// custom data type handlers takes three String arguments // custom data type handlers takes three String arguments
void handleCustom (String route, String value, String type) { void handleCustom(String route, String value, String type) {
Serial.print("Custom msg "); Serial.print("Custom msg ");
Serial.print(route); Serial.print(route);
Serial.print(" of type "); Serial.print(" of type ");

View File

@ -40,7 +40,9 @@ void setup() {
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while (!Serial) { ; } while (!Serial) {
;
}
// start-up the bridge // start-up the bridge
Bridge.begin(); Bridge.begin();
@ -68,18 +70,21 @@ void loop() {
sb.monitor(); sb.monitor();
// connected to spacebrew then send a new value whenever the pot value changes // connected to spacebrew then send a new value whenever the pot value changes
if ( sb.connected() ) { if (sb.connected()) {
int cur_value = digitalRead(3); int cur_value = digitalRead(3);
if ( last_value != cur_value ) { if (last_value != cur_value) {
if (cur_value == HIGH) sb.send("physical button", false); if (cur_value == HIGH) {
else sb.send("physical button", true); sb.send("physical button", false);
} else {
sb.send("physical button", true);
}
last_value = cur_value; last_value = cur_value;
} }
} }
} }
// handler method that is called whenever a new string message is received // handler method that is called whenever a new string message is received
void handleBoolean (String route, boolean value) { void handleBoolean(String route, boolean value) {
// print the message that was received // print the message that was received
Serial.print("From "); Serial.print("From ");
Serial.print(route); Serial.print(route);

View File

@ -41,7 +41,9 @@ void setup() {
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while (!Serial) { ; } while (!Serial) {
;
}
// start-up the bridge // start-up the bridge
Bridge.begin(); Bridge.begin();
@ -66,9 +68,9 @@ void loop() {
sb.monitor(); sb.monitor();
// connected to spacebrew then send a new value whenever the pot value changes // connected to spacebrew then send a new value whenever the pot value changes
if ( sb.connected() ) { if (sb.connected()) {
int cur_value = analogRead(A0); int cur_value = analogRead(A0);
if ( last_value != cur_value ) { if (last_value != cur_value) {
sb.send("physical pot", cur_value); sb.send("physical pot", cur_value);
last_value = cur_value; last_value = cur_value;
} }
@ -76,7 +78,7 @@ void loop() {
} }
// handler method that is called whenever a new string message is received // handler method that is called whenever a new string message is received
void handleRange (String route, int value) { void handleRange(String route, int value) {
// print the message that was received // print the message that was received
Serial.print("From "); Serial.print("From ");
Serial.print(route); Serial.print(route);

View File

@ -38,7 +38,9 @@ void setup() {
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while (!Serial) { ; } while (!Serial) {
;
}
// start-up the bridge // start-up the bridge
Bridge.begin(); Bridge.begin();
@ -63,10 +65,10 @@ void loop() {
sb.monitor(); sb.monitor();
// connected to spacebrew then send a string every 2 seconds // connected to spacebrew then send a string every 2 seconds
if ( sb.connected() ) { if (sb.connected()) {
// check if it is time to send a new message // check if it is time to send a new message
if ( (millis() - last_time) > interval ) { if ((millis() - last_time) > interval) {
sb.send("speak", "is anybody out there?"); sb.send("speak", "is anybody out there?");
last_time = millis(); last_time = millis();
} }
@ -74,7 +76,7 @@ void loop() {
} }
// handler method that is called whenever a new string message is received // handler method that is called whenever a new string message is received
void handleString (String route, String value) { void handleString(String route, String value) {
// print the message that was received // print the message that was received
Serial.print("From "); Serial.print("From ");
Serial.print(route); Serial.print(route);

View File

@ -20,7 +20,7 @@
#include <Bridge.h> #include <Bridge.h>
#include <Temboo.h> #include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information #include "TembooAccount.h" // contains Temboo account information
// as described in the footer comment below // as described in the footer comment below
// the address for which a weather forecast will be retrieved // the address for which a weather forecast will be retrieved
@ -35,13 +35,12 @@ void setup() {
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while(!Serial); while (!Serial);
Bridge.begin(); Bridge.begin();
} }
void loop() void loop() {
{
// while we haven't reached the max number of runs... // while we haven't reached the max number of runs...
if (numRuns <= maxRuns) { if (numRuns <= maxRuns) {
@ -79,7 +78,7 @@ void loop()
GetWeatherByAddressChoreo.run(); GetWeatherByAddressChoreo.run();
// when the choreo results are available, print them to the serial monitor // when the choreo results are available, print them to the serial monitor
while(GetWeatherByAddressChoreo.available()) { while (GetWeatherByAddressChoreo.available()) {
char c = GetWeatherByAddressChoreo.read(); char c = GetWeatherByAddressChoreo.read();
Serial.print(c); Serial.print(c);

View File

@ -27,7 +27,7 @@
#include <Bridge.h> #include <Bridge.h>
#include <Temboo.h> #include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information #include "TembooAccount.h" // contains Temboo account information
// as described in the footer comment below // as described in the footer comment below
/*** SUBSTITUTE YOUR VALUES BELOW: ***/ /*** SUBSTITUTE YOUR VALUES BELOW: ***/
@ -46,11 +46,10 @@ void setup() {
// For debugging, wait until a serial console is connected. // For debugging, wait until a serial console is connected.
delay(4000); delay(4000);
while(!Serial); while (!Serial);
Bridge.begin(); Bridge.begin();
} }
void loop() void loop() {
{
// while we haven't reached the max number of runs... // while we haven't reached the max number of runs...
if (numRuns <= maxRuns) { if (numRuns <= maxRuns) {
Serial.println("Running ReadATweet - Run #" + String(numRuns++)); Serial.println("Running ReadATweet - Run #" + String(numRuns++));
@ -99,7 +98,7 @@ void loop()
unsigned int returnCode = HomeTimelineChoreo.run(); unsigned int returnCode = HomeTimelineChoreo.run();
// a response code of 0 means success; print the API response // a response code of 0 means success; print the API response
if(returnCode == 0) { if (returnCode == 0) {
String author; // a String to hold the tweet author's name String author; // a String to hold the tweet author's name
String tweet; // a String to hold the text of the tweet String tweet; // a String to hold the text of the tweet
@ -115,7 +114,7 @@ void loop()
// see the examples at http://www.temboo.com/arduino for more details // see the examples at http://www.temboo.com/arduino for more details
// we can read this format into separate variables, as follows: // we can read this format into separate variables, as follows:
while(HomeTimelineChoreo.available()) { while (HomeTimelineChoreo.available()) {
// read the name of the output item // read the name of the output item
String name = HomeTimelineChoreo.readStringUntil('\x1F'); String name = HomeTimelineChoreo.readStringUntil('\x1F');
name.trim(); name.trim();
@ -137,7 +136,7 @@ void loop()
} else { } else {
// there was an error // there was an error
// print the raw output from the choreo // print the raw output from the choreo
while(HomeTimelineChoreo.available()) { while (HomeTimelineChoreo.available()) {
char c = HomeTimelineChoreo.read(); char c = HomeTimelineChoreo.read();
Serial.print(c); Serial.print(c);
} }

View File

@ -28,7 +28,7 @@
#include <Bridge.h> #include <Bridge.h>
#include <Temboo.h> #include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information #include "TembooAccount.h" // contains Temboo account information
// as described in the footer comment below // as described in the footer comment below
/*** SUBSTITUTE YOUR VALUES BELOW: ***/ /*** SUBSTITUTE YOUR VALUES BELOW: ***/
@ -48,13 +48,12 @@ void setup() {
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while(!Serial); while (!Serial);
Bridge.begin(); Bridge.begin();
} }
void loop() void loop() {
{
// only try to send the tweet if we haven't already sent it successfully // only try to send the tweet if we haven't already sent it successfully
if (numRuns <= maxRuns) { if (numRuns <= maxRuns) {

View File

@ -53,7 +53,7 @@
#include <Bridge.h> #include <Bridge.h>
#include <Temboo.h> #include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information #include "TembooAccount.h" // contains Temboo account information
// as described in the footer comment below // as described in the footer comment below
/*** SUBSTITUTE YOUR VALUES BELOW: ***/ /*** SUBSTITUTE YOUR VALUES BELOW: ***/
@ -77,13 +77,12 @@ void setup() {
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while(!Serial); while (!Serial);
Bridge.begin(); Bridge.begin();
} }
void loop() void loop() {
{
// only try to send the email if we haven't already tried // only try to send the email if we haven't already tried
if (!attempted) { if (!attempted) {

View File

@ -33,7 +33,7 @@
#include <Bridge.h> #include <Bridge.h>
#include <Temboo.h> #include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information #include "TembooAccount.h" // contains Temboo account information
// as described in the footer comment below // as described in the footer comment below
@ -62,13 +62,12 @@ void setup() {
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while(!Serial); while (!Serial);
Bridge.begin(); Bridge.begin();
} }
void loop() void loop() {
{
// only try to send the SMS if we haven't already sent it successfully // only try to send the SMS if we haven't already sent it successfully
if (!attempted) { if (!attempted) {
@ -128,7 +127,7 @@ void loop()
SendSMSChoreo.close(); SendSMSChoreo.close();
// set the flag indicatine we've tried once. // set the flag indicatine we've tried once.
attempted=true; attempted = true;
} }
} }

View File

@ -56,7 +56,7 @@
#include <Bridge.h> #include <Bridge.h>
#include <Temboo.h> #include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information, #include "TembooAccount.h" // contains Temboo account information,
// as described in the footer comment below // as described in the footer comment below
/*** SUBSTITUTE YOUR VALUES BELOW: ***/ /*** SUBSTITUTE YOUR VALUES BELOW: ***/
@ -84,22 +84,21 @@ const unsigned long RUN_INTERVAL_MILLIS = 60000; // how often to run the Choreo
// the last time we ran the Choreo // the last time we ran the Choreo
// (initialized to 60 seconds ago so the // (initialized to 60 seconds ago so the
// Choreo is run immediately when we start up) // Choreo is run immediately when we start up)
unsigned long lastRun = (unsigned long)-60000; unsigned long lastRun = (unsigned long) - 60000;
void setup() { void setup() {
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
Serial.begin(9600); Serial.begin(9600);
delay(4000); delay(4000);
while(!Serial); while (!Serial);
Serial.print("Initializing the bridge..."); Serial.print("Initializing the bridge...");
Bridge.begin(); Bridge.begin();
Serial.println("Done"); Serial.println("Done");
} }
void loop() void loop() {
{
// get the number of milliseconds this sketch has been running // get the number of milliseconds this sketch has been running
unsigned long now = millis(); unsigned long now = millis();

View File

@ -22,7 +22,7 @@
#include <Bridge.h> #include <Bridge.h>
#include <Temboo.h> #include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information #include "TembooAccount.h" // contains Temboo account information
// as described in the footer comment below // as described in the footer comment below
// the zip code to search for toxin-emitting facilities // the zip code to search for toxin-emitting facilities
String US_ZIP_CODE = "11215"; String US_ZIP_CODE = "11215";
@ -35,12 +35,11 @@ void setup() {
// for debugging, wait until a serial console is connected // for debugging, wait until a serial console is connected
delay(4000); delay(4000);
while(!Serial); while (!Serial);
Bridge.begin(); Bridge.begin();
} }
void loop() void loop() {
{
// while we haven't reached the max number of runs... // while we haven't reached the max number of runs...
if (numRuns <= maxRuns) { if (numRuns <= maxRuns) {
@ -83,7 +82,7 @@ void loop()
// the output filters we specified will return comma delimited // the output filters we specified will return comma delimited
// lists containing the name and street address of the facilities // lists containing the name and street address of the facilities
// located in the specified zip code. // located in the specified zip code.
while(FacilitiesSearchByZipChoreo.available()) { while (FacilitiesSearchByZipChoreo.available()) {
String name = FacilitiesSearchByZipChoreo.readStringUntil('\x1F'); String name = FacilitiesSearchByZipChoreo.readStringUntil('\x1F');
name.trim(); name.trim();
@ -123,7 +122,7 @@ void loop()
printResult(facility, address); printResult(facility, address);
} }
}while (i >= 0); } while (i >= 0);
facility = facilities.substring(facilityStart); facility = facilities.substring(facilityStart);
address = addresses.substring(addressStart); address = addresses.substring(addressStart);
printResult(facility, address); printResult(facility, address);
@ -131,7 +130,7 @@ void loop()
Serial.println("No facilities found in zip code " + US_ZIP_CODE); Serial.println("No facilities found in zip code " + US_ZIP_CODE);
} }
} else { } else {
while(FacilitiesSearchByZipChoreo.available()) { while (FacilitiesSearchByZipChoreo.available()) {
char c = FacilitiesSearchByZipChoreo.read(); char c = FacilitiesSearchByZipChoreo.read();
Serial.print(c); Serial.print(c);
} }

View File

@ -27,7 +27,7 @@
#include <Bridge.h> #include <Bridge.h>
#include <Temboo.h> #include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information, #include "TembooAccount.h" // contains Temboo account information,
// as described in the footer comment below // as described in the footer comment below
/*** SUBSTITUTE YOUR VALUES BELOW: ***/ /*** SUBSTITUTE YOUR VALUES BELOW: ***/
@ -46,7 +46,7 @@ void setup() {
// For debugging, wait until a serial console is connected. // For debugging, wait until a serial console is connected.
delay(4000); delay(4000);
while(!Serial); while (!Serial);
Bridge.begin(); Bridge.begin();
} }
@ -96,7 +96,7 @@ void loop() {
// note that in this case, we're just printing the raw response from Facebook. // note that in this case, we're just printing the raw response from Facebook.
// see the examples on using Temboo SDK output filters at http://www.temboo.com/arduino // see the examples on using Temboo SDK output filters at http://www.temboo.com/arduino
// for information on how to filter this data // for information on how to filter this data
while(SetStatusChoreo.available()) { while (SetStatusChoreo.available()) {
char c = SetStatusChoreo.read(); char c = SetStatusChoreo.read();
Serial.print(c); Serial.print(c);
} }

View File

@ -32,7 +32,7 @@
#include <Bridge.h> #include <Bridge.h>
#include <Temboo.h> #include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information #include "TembooAccount.h" // contains Temboo account information
// as described in the footer comment below // as described in the footer comment below
/*** SUBSTITUTE YOUR VALUES BELOW: ***/ /*** SUBSTITUTE YOUR VALUES BELOW: ***/
@ -60,12 +60,11 @@ void setup() {
// For debugging, wait until a serial console is connected. // For debugging, wait until a serial console is connected.
delay(4000); delay(4000);
while(!Serial); while (!Serial);
Bridge.begin(); Bridge.begin();
} }
void loop() void loop() {
{
// only try to upload the file if we haven't already done so // only try to upload the file if we haven't already done so
if (!success) { if (!success) {
@ -103,7 +102,7 @@ void loop()
// next, the root folder on Dropbox relative to which the file path is specified. // next, the root folder on Dropbox relative to which the file path is specified.
// to work with the Dropbox app you created earlier, this should be left as "sandbox" // to work with the Dropbox app you created earlier, this should be left as "sandbox"
// if your Dropbox app has full access to your files, specify "dropbox" // if your Dropbox app has full access to your files, specify "dropbox"
UploadFileChoreo.addInput("Root","sandbox"); UploadFileChoreo.addInput("Root", "sandbox");
// next, the Base64 encoded file data to upload // next, the Base64 encoded file data to upload
UploadFileChoreo.addInput("FileContents", base64EncodedData); UploadFileChoreo.addInput("FileContents", base64EncodedData);
@ -171,7 +170,7 @@ String base64Encode(String toEncode) {
// read in the choreo results, and return the "Base64EncodedText" output value. // read in the choreo results, and return the "Base64EncodedText" output value.
// see http://www.temboo.com/arduino for more details on using choreo outputs. // see http://www.temboo.com/arduino for more details on using choreo outputs.
while(Base64EncodeChoreo.available()) { while (Base64EncodeChoreo.available()) {
// read the name of the output item // read the name of the output item
String name = Base64EncodeChoreo.readStringUntil('\x1F'); String name = Base64EncodeChoreo.readStringUntil('\x1F');
name.trim(); name.trim();
@ -180,7 +179,7 @@ String base64Encode(String toEncode) {
String data = Base64EncodeChoreo.readStringUntil('\x1E'); String data = Base64EncodeChoreo.readStringUntil('\x1E');
data.trim(); data.trim();
if(name == "Base64EncodedText") { if (name == "Base64EncodedText") {
return data; return data;
} }
} }

View File

@ -41,13 +41,19 @@ void loop() {
if (lastSecond != seconds) { // if a second has passed if (lastSecond != seconds) { // if a second has passed
// print the time: // print the time:
if (hours <= 9) Serial.print("0"); // adjust for 0-9 if (hours <= 9) {
Serial.print("0"); // adjust for 0-9
}
Serial.print(hours); Serial.print(hours);
Serial.print(":"); Serial.print(":");
if (minutes <= 9) Serial.print("0"); // adjust for 0-9 if (minutes <= 9) {
Serial.print("0"); // adjust for 0-9
}
Serial.print(minutes); Serial.print(minutes);
Serial.print(":"); Serial.print(":");
if (seconds <= 9) Serial.print("0"); // adjust for 0-9 if (seconds <= 9) {
Serial.print("0"); // adjust for 0-9
}
Serial.println(seconds); Serial.println(seconds);
// restart the date process: // restart the date process:

View File

@ -19,7 +19,7 @@
obtain the console. obtain the console.
The circuit: The circuit:
* Arduino Yún Arduino Yún
created March 2013 created March 2013
by Massimo Banzi by Massimo Banzi
@ -29,7 +29,7 @@
http://www.arduino.cc/en/Tutorial/YunSerialTerminal http://www.arduino.cc/en/Tutorial/YunSerialTerminal
*/ */
long linuxBaud = 250000; long linuxBaud = 250000;
@ -65,8 +65,7 @@ void loop() {
Serial1.begin(500000); // set speed to 500000 Serial1.begin(500000); // set speed to 500000
Serial.println("Speed set to 500000"); Serial.println("Speed set to 500000");
} else if (c == '~') { // '~` key pressed? } else if (c == '~') { // '~` key pressed?
// send "bridge shutdown" command Serial1.write((uint8_t *)"\xff\0\0\x05XXXXX\x7f\xf9", 11); // send "bridge shutdown" command
Serial1.write((uint8_t *)"\xff\0\0\x05XXXXX\x7f\xf9", 11);
Serial.println("Sending bridge's shutdown command"); Serial.println("Sending bridge's shutdown command");
} else { // any other key pressed? } else { // any other key pressed?
Serial1.write('~'); // write '~' to UART Serial1.write('~'); // write '~' to UART

View File

@ -14,13 +14,11 @@
#include <Esplora.h> #include <Esplora.h>
void setup() void setup() {
{
Serial.begin(9600); // initialize serial communications with your computer Serial.begin(9600); // initialize serial communications with your computer
} }
void loop() void loop() {
{
int xAxis = Esplora.readAccelerometer(X_AXIS); // read the X axis int xAxis = Esplora.readAccelerometer(X_AXIS); // read the X axis
int yAxis = Esplora.readAccelerometer(Y_AXIS); // read the Y axis int yAxis = Esplora.readAccelerometer(Y_AXIS); // read the Y axis
int zAxis = Esplora.readAccelerometer(Z_AXIS); // read the Z axis int zAxis = Esplora.readAccelerometer(Z_AXIS); // read the Z axis

View File

@ -27,14 +27,12 @@
#include <Esplora.h> #include <Esplora.h>
void setup() void setup() {
{
Serial.begin(9600); // initialize serial communication with your computer Serial.begin(9600); // initialize serial communication with your computer
Mouse.begin(); // take control of the mouse Mouse.begin(); // take control of the mouse
} }
void loop() void loop() {
{
int xValue = Esplora.readJoystickX(); // read the joystick's X position int xValue = Esplora.readJoystickX(); // read the joystick's X position
int yValue = Esplora.readJoystickY(); // read the joystick's Y position int yValue = Esplora.readJoystickY(); // read the joystick's Y position
int button = Esplora.readJoystickSwitch(); // read the joystick pushbutton int button = Esplora.readJoystickSwitch(); // read the joystick pushbutton

View File

@ -45,8 +45,7 @@ void loop() {
byte thisNote = map(slider, 0, 1023, 0, 13); byte thisNote = map(slider, 0, 1023, 0, 13);
// play the note corresponding to the slider's position: // play the note corresponding to the slider's position:
Esplora.tone(note[thisNote]); Esplora.tone(note[thisNote]);
} } else {
else {
// if the button isn't pressed, turn the note off: // if the button isn't pressed, turn the note off:
Esplora.noTone(); Esplora.noTone();
} }

View File

@ -11,13 +11,11 @@
*/ */
#include <Esplora.h> #include <Esplora.h>
void setup() void setup() {
{
Serial.begin(9600); // initialize serial communications with your computer Serial.begin(9600); // initialize serial communications with your computer
} }
void loop() void loop() {
{
// read the temperature sensor in Celsius, then Fahrenheit: // read the temperature sensor in Celsius, then Fahrenheit:
int celsius = Esplora.readTemperature(DEGREES_C); int celsius = Esplora.readTemperature(DEGREES_C);
int fahrenheit = Esplora.readTemperature(DEGREES_F); int fahrenheit = Esplora.readTemperature(DEGREES_F);

View File

@ -103,8 +103,7 @@ void loop() {
*/ */
if (newState == PRESSED) { if (newState == PRESSED) {
Keyboard.press(keystrokes[thisButton]); Keyboard.press(keystrokes[thisButton]);
} } else if (newState == RELEASED) {
else if (newState == RELEASED) {
Keyboard.release(keystrokes[thisButton]); Keyboard.release(keystrokes[thisButton]);
} }
} }

View File

@ -37,8 +37,9 @@ void setup() {
} }
void loop() { void loop() {
if (Serial.available()) if (Serial.available()) {
parseCommand(); parseCommand();
}
} }
/* /*

View File

@ -114,17 +114,19 @@ void loop() {
// let the RGB led blink green once per second, for 200ms. // let the RGB led blink green once per second, for 200ms.
unsigned int ms = millis() % 1000; unsigned int ms = millis() % 1000;
if (ms < 200) if (ms < 200) {
Esplora.writeGreen(50); Esplora.writeGreen(50);
else } else {
Esplora.writeGreen(0); Esplora.writeGreen(0);
}
Esplora.writeBlue(0); Esplora.writeBlue(0);
} } else
else
// while not active, keep a reassuring blue color coming // while not active, keep a reassuring blue color coming
// from the Esplora... // from the Esplora...
{
Esplora.writeBlue(20); Esplora.writeBlue(20);
}
} }
@ -203,9 +205,10 @@ void checkSwitchPress() {
if (startBtn != lastStartBtn) { if (startBtn != lastStartBtn) {
if (startBtn == HIGH) { // button released if (startBtn == HIGH) { // button released
active = !active; active = !active;
if (active) if (active) {
justActivated = true; justActivated = true;
} }
}
lastStartBtn = startBtn; lastStartBtn = startBtn;
} }

View File

@ -27,9 +27,10 @@
// The IP address will be dependent on your local network. // The IP address will be dependent on your local network.
// gateway and subnet are optional: // gateway and subnet are optional:
byte mac[] = { byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
IPAddress ip(192,168,1, 177); };
IPAddress gateway(192,168,1, 1); IPAddress ip(192, 168, 1, 177);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 0, 0); IPAddress subnet(255, 255, 0, 0);
@ -62,9 +63,9 @@ void loop() {
if (client) { if (client) {
boolean newClient = true; boolean newClient = true;
for (byte i=0;i<4;i++) { for (byte i = 0; i < 4; i++) {
//check whether this client refers to the same socket as one of the existing instances: //check whether this client refers to the same socket as one of the existing instances:
if (clients[i]==client) { if (clients[i] == client) {
newClient = false; newClient = false;
break; break;
} }
@ -72,8 +73,8 @@ void loop() {
if (newClient) { if (newClient) {
//check which of the existing clients can be overridden: //check which of the existing clients can be overridden:
for (byte i=0;i<4;i++) { for (byte i = 0; i < 4; i++) {
if (!clients[i] && clients[i]!=client) { if (!clients[i] && clients[i] != client) {
clients[i] = client; clients[i] = client;
// clead out the input buffer: // clead out the input buffer:
client.flush(); client.flush();
@ -90,8 +91,8 @@ void loop() {
// read the bytes incoming from the client: // read the bytes incoming from the client:
char thisChar = client.read(); char thisChar = client.read();
// echo the bytes back to all other connected clients: // echo the bytes back to all other connected clients:
for (byte i=0;i<4;i++) { for (byte i = 0; i < 4; i++) {
if (clients[i] && (clients[i]!=client)) { if (clients[i] && (clients[i] != client)) {
clients[i].write(thisChar); clients[i].write(thisChar);
} }
} }
@ -99,7 +100,7 @@ void loop() {
Serial.write(thisChar); Serial.write(thisChar);
} }
} }
for (byte i=0;i<4;i++) { for (byte i = 0; i < 4; i++) {
if (!(clients[i].connected())) { if (!(clients[i].connected())) {
// client.stop() invalidates the internal socket-descriptor, so next use of == will allways return false; // client.stop() invalidates the internal socket-descriptor, so next use of == will allways return false;
clients[i].stop(); clients[i].stop();

View File

@ -156,8 +156,7 @@ void listenForEthernetClients() {
if (c == '\n') { if (c == '\n') {
// you're starting a new line // you're starting a new line
currentLineIsBlank = true; currentLineIsBlank = true;
} } else if (c != '\r') {
else if (c != '\r') {
// you've gotten a character on the current line // you've gotten a character on the current line
currentLineIsBlank = false; currentLineIsBlank = false;
} }
@ -219,5 +218,5 @@ unsigned int readRegister(byte registerName, int numBytes) {
// take the chip select high to de-select: // take the chip select high to de-select:
digitalWrite(chipSelectPin, HIGH); digitalWrite(chipSelectPin, HIGH);
// return the result: // return the result:
return(result); return (result);
} }

View File

@ -54,15 +54,13 @@ void setup() {
// if you get a connection, report back via serial: // if you get a connection, report back via serial:
if (client.connect(server, 10002)) { if (client.connect(server, 10002)) {
Serial.println("connected"); Serial.println("connected");
} } else {
else {
// if you didn't get a connection to the server: // if you didn't get a connection to the server:
Serial.println("connection failed"); Serial.println("connection failed");
} }
} }
void loop() void loop() {
{
// if there are incoming bytes available // if there are incoming bytes available
// from the server, read them and print them: // from the server, read them and print them:
if (client.available()) { if (client.available()) {

View File

@ -45,17 +45,14 @@ void setup() {
void loop() { void loop() {
// if there's data available, read a packet // if there's data available, read a packet
int packetSize = Udp.parsePacket(); int packetSize = Udp.parsePacket();
if (packetSize) if (packetSize) {
{
Serial.print("Received packet of size "); Serial.print("Received packet of size ");
Serial.println(packetSize); Serial.println(packetSize);
Serial.print("From "); Serial.print("From ");
IPAddress remote = Udp.remoteIP(); IPAddress remote = Udp.remoteIP();
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++) {
{
Serial.print(remote[i], DEC); Serial.print(remote[i], DEC);
if (i < 3) if (i < 3) {
{
Serial.print("."); Serial.print(".");
} }
} }

View File

@ -37,8 +37,7 @@ byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing pack
// A UDP instance to let us send and receive packets over UDP // A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp; EthernetUDP Udp;
void setup() void setup() {
{
// Open serial communications and wait for port to open: // Open serial communications and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -56,13 +55,12 @@ void setup()
Udp.begin(localPort); Udp.begin(localPort);
} }
void loop() void loop() {
{
sendNTPpacket(timeServer); // send an NTP packet to a time server sendNTPpacket(timeServer); // send an NTP packet to a time server
// wait to see if a reply is available // wait to see if a reply is available
delay(1000); delay(1000);
if ( Udp.parsePacket() ) { if (Udp.parsePacket()) {
// We've received a packet, read the data from it // We've received a packet, read the data from it
Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
@ -74,7 +72,7 @@ void loop()
// combine the four bytes (two words) into a long integer // combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900): // this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord; unsigned long secsSince1900 = highWord << 16 | lowWord;
Serial.print("Seconds since Jan 1 1900 = " ); Serial.print("Seconds since Jan 1 1900 = ");
Serial.println(secsSince1900); Serial.println(secsSince1900);
// now convert NTP time into everyday time: // now convert NTP time into everyday time:
@ -91,13 +89,13 @@ void loop()
Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
Serial.print(':'); Serial.print(':');
if ( ((epoch % 3600) / 60) < 10 ) { if (((epoch % 3600) / 60) < 10) {
// In the first 10 minutes of each hour, we'll want a leading '0' // In the first 10 minutes of each hour, we'll want a leading '0'
Serial.print('0'); Serial.print('0');
} }
Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
Serial.print(':'); Serial.print(':');
if ( (epoch % 60) < 10 ) { if ((epoch % 60) < 10) {
// In the first 10 seconds of each minute, we'll want a leading '0' // In the first 10 seconds of each minute, we'll want a leading '0'
Serial.print('0'); Serial.print('0');
} }
@ -108,8 +106,7 @@ void loop()
} }
// send an NTP request to the time server at the given address // send an NTP request to the time server at the given address
unsigned long sendNTPpacket(char* address) unsigned long sendNTPpacket(char* address) {
{
// set all bytes in the buffer to 0 // set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE); memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request // Initialize values needed to form NTP request

View File

@ -59,15 +59,13 @@ void setup() {
client.println("Host: www.google.com"); client.println("Host: www.google.com");
client.println("Connection: close"); client.println("Connection: close");
client.println(); client.println();
} } else {
else {
// kf you didn't get a connection to the server: // kf you didn't get a connection to the server:
Serial.println("connection failed"); Serial.println("connection failed");
} }
} }
void loop() void loop() {
{
// if there are incoming bytes available // if there are incoming bytes available
// from the server, read them and print them: // from the server, read them and print them:
if (client.available()) { if (client.available()) {

View File

@ -98,8 +98,7 @@ void httpRequest() {
// note the time that the connection was made: // note the time that the connection was made:
lastConnectionTime = millis(); lastConnectionTime = millis();
} } else {
else {
// if you couldn't make a connection: // if you couldn't make a connection:
Serial.println("connection failed"); Serial.println("connection failed");
} }

View File

@ -84,8 +84,7 @@ void loop() {
if (c == '\n') { if (c == '\n') {
// you're starting a new line // you're starting a new line
currentLineIsBlank = true; currentLineIsBlank = true;
} } else if (c != '\r') {
else if (c != '\r') {
// you've gotten a character on the current line // you've gotten a character on the current line
currentLineIsBlank = false; currentLineIsBlank = false;
} }

View File

@ -37,8 +37,7 @@ char server[] = "arduino.cc";
char path[] = "/asciilogo.txt"; char path[] = "/asciilogo.txt";
int port = 80; // port 80 is the default for HTTP int port = 80; // port 80 is the default for HTTP
void setup() void setup() {
{
// initialize serial communications and wait for port to open: // initialize serial communications and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -51,13 +50,11 @@ void setup()
// After starting the modem with GSM.begin() // After starting the modem with GSM.begin()
// attach the shield to the GPRS network with the APN, login and password // attach the shield to the GPRS network with the APN, login and password
while (notConnected) while (notConnected) {
{
if ((gsmAccess.begin(PINNUMBER) == GSM_READY) & if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &
(gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) {
notConnected = false; notConnected = false;
else } else {
{
Serial.println("Not connected"); Serial.println("Not connected");
delay(1000); delay(1000);
} }
@ -66,8 +63,7 @@ void setup()
Serial.println("connecting..."); Serial.println("connecting...");
// if you get a connection, report back via serial: // if you get a connection, report back via serial:
if (client.connect(server, port)) if (client.connect(server, port)) {
{
Serial.println("connected"); Serial.println("connected");
// Make a HTTP request: // Make a HTTP request:
client.print("GET "); client.print("GET ");
@ -77,27 +73,22 @@ void setup()
client.println(server); client.println(server);
client.println("Connection: close"); client.println("Connection: close");
client.println(); client.println();
} } else {
else
{
// if you didn't get a connection to the server: // if you didn't get a connection to the server:
Serial.println("connection failed"); Serial.println("connection failed");
} }
} }
void loop() void loop() {
{
// if there are incoming bytes available // if there are incoming bytes available
// from the server, read them and print them: // from the server, read them and print them:
if (client.available()) if (client.available()) {
{
char c = client.read(); char c = client.read();
Serial.print(c); Serial.print(c);
} }
// if the server's disconnected, stop the client: // if the server's disconnected, stop the client:
if (!client.available() && !client.connected()) if (!client.available() && !client.connected()) {
{
Serial.println(); Serial.println();
Serial.println("disconnecting."); Serial.println("disconnecting.");
client.stop(); client.stop();

View File

@ -32,8 +32,7 @@ GSMServer server(80); // port 80 (http default)
// timeout // timeout
const unsigned long __TIMEOUT__ = 10 * 1000; const unsigned long __TIMEOUT__ = 10 * 1000;
void setup() void setup() {
{
// initialize serial communications and wait for port to open: // initialize serial communications and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -45,13 +44,11 @@ void setup()
// Start GSM shield // Start GSM shield
// If your SIM has PIN, pass it as a parameter of begin() in quotes // If your SIM has PIN, pass it as a parameter of begin() in quotes
while (notConnected) while (notConnected) {
{
if ((gsmAccess.begin(PINNUMBER) == GSM_READY) & if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &
(gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) {
notConnected = false; notConnected = false;
else } else {
{
Serial.println("Not connected"); Serial.println("Not connected");
delay(1000); delay(1000);
} }
@ -76,22 +73,20 @@ void loop() {
if (client) if (client) {
{ while (client.connected()) {
while (client.connected()) if (client.available()) {
{
if (client.available())
{
Serial.println("Receiving request!"); Serial.println("Receiving request!");
bool sendResponse = false; bool sendResponse = false;
while (char c = client.read()) { while (char c = client.read()) {
if (c == '\n') sendResponse = true; if (c == '\n') {
sendResponse = true;
}
} }
// if you've gotten to the end of the line (received a newline // if you've gotten to the end of the line (received a newline
// character) // character)
if (sendResponse) if (sendResponse) {
{
// send a standard http response header // send a standard http response header
client.println("HTTP/1.1 200 OK"); client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html"); client.println("Content-Type: text/html");

View File

@ -32,8 +32,7 @@ GSMVoiceCall vcs;
String remoteNumber = ""; // the number you will call String remoteNumber = ""; // the number you will call
char charbuffer[20]; char charbuffer[20];
void setup() void setup() {
{
// initialize serial communications and wait for port to open: // initialize serial communications and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
@ -48,12 +47,10 @@ void setup()
// Start GSM shield // Start GSM shield
// If your SIM has PIN, pass it as a parameter of begin() in quotes // If your SIM has PIN, pass it as a parameter of begin() in quotes
while (notConnected) while (notConnected) {
{ if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
if (gsmAccess.begin(PINNUMBER) == GSM_READY)
notConnected = false; notConnected = false;
else } else {
{
Serial.println("Not connected"); Serial.println("Not connected");
delay(1000); delay(1000);
} }
@ -64,19 +61,15 @@ void setup()
} }
void loop() void loop() {
{
// add any incoming characters to the String: // add any incoming characters to the String:
while (Serial.available() > 0) while (Serial.available() > 0) {
{
char inChar = Serial.read(); char inChar = Serial.read();
// if it's a newline, that means you should make the call: // if it's a newline, that means you should make the call:
if (inChar == '\n') if (inChar == '\n') {
{
// make sure the phone number is not too long: // make sure the phone number is not too long:
if (remoteNumber.length() < 20) if (remoteNumber.length() < 20) {
{
// let the user know you're calling: // let the user know you're calling:
Serial.print("Calling to : "); Serial.print("Calling to : ");
Serial.println(remoteNumber); Serial.println(remoteNumber);
@ -87,8 +80,7 @@ void loop()
// Check if the receiving end has picked up the call // Check if the receiving end has picked up the call
if (vcs.voiceCall(charbuffer)) if (vcs.voiceCall(charbuffer)) {
{
Serial.println("Call Established. Enter line to end"); Serial.println("Call Established. Enter line to end");
// Wait for some input from the line // Wait for some input from the line
while (Serial.read() != '\n' && (vcs.getvoiceCallStatus() == TALKING)); while (Serial.read() != '\n' && (vcs.getvoiceCallStatus() == TALKING));
@ -98,19 +90,16 @@ void loop()
Serial.println("Call Finished"); Serial.println("Call Finished");
remoteNumber = ""; remoteNumber = "";
Serial.println("Enter phone number to call."); Serial.println("Enter phone number to call.");
} } else {
else
{
Serial.println("That's too long for a phone number. I'm forgetting it"); Serial.println("That's too long for a phone number. I'm forgetting it");
remoteNumber = ""; remoteNumber = "";
} }
} } else {
else
{
// add the latest character to the message to send: // add the latest character to the message to send:
if (inChar != '\r') if (inChar != '\r') {
remoteNumber += inChar; remoteNumber += inChar;
} }
} }
}
} }

View File

@ -30,8 +30,7 @@ GSM_SMS sms;
// Array to hold the number a SMS is retreived from // Array to hold the number a SMS is retreived from
char senderNumber[20]; char senderNumber[20];
void setup() void setup() {
{
// initialize serial communications and wait for port to open: // initialize serial communications and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -44,12 +43,10 @@ void setup()
boolean notConnected = true; boolean notConnected = true;
// Start GSM connection // Start GSM connection
while (notConnected) while (notConnected) {
{ if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
if (gsmAccess.begin(PINNUMBER) == GSM_READY)
notConnected = false; notConnected = false;
else } else {
{
Serial.println("Not connected"); Serial.println("Not connected");
delay(1000); delay(1000);
} }
@ -59,13 +56,11 @@ void setup()
Serial.println("Waiting for messages"); Serial.println("Waiting for messages");
} }
void loop() void loop() {
{
char c; char c;
// If there are any SMSs available() // If there are any SMSs available()
if (sms.available()) if (sms.available()) {
{
Serial.println("Message received from:"); Serial.println("Message received from:");
// Get remote number // Get remote number
@ -74,15 +69,15 @@ void loop()
// An example of message disposal // An example of message disposal
// Any messages starting with # should be discarded // Any messages starting with # should be discarded
if (sms.peek() == '#') if (sms.peek() == '#') {
{
Serial.println("Discarded SMS"); Serial.println("Discarded SMS");
sms.flush(); sms.flush();
} }
// Read message bytes and print them // Read message bytes and print them
while (c = sms.read()) while (c = sms.read()) {
Serial.print(c); Serial.print(c);
}
Serial.println("\nEND OF MESSAGE"); Serial.println("\nEND OF MESSAGE");

View File

@ -34,8 +34,7 @@ GSMVoiceCall vcs;
// Array to hold the number for the incoming call // Array to hold the number for the incoming call
char numtel[20]; char numtel[20];
void setup() void setup() {
{
// initialize serial communications and wait for port to open: // initialize serial communications and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -49,12 +48,10 @@ void setup()
// Start GSM shield // Start GSM shield
// If your SIM has PIN, pass it as a parameter of begin() in quotes // If your SIM has PIN, pass it as a parameter of begin() in quotes
while (notConnected) while (notConnected) {
{ if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
if (gsmAccess.begin(PINNUMBER) == GSM_READY)
notConnected = false; notConnected = false;
else } else {
{
Serial.println("Not connected"); Serial.println("Not connected");
delay(1000); delay(1000);
} }
@ -66,11 +63,9 @@ void setup()
Serial.println("Waiting for a call"); Serial.println("Waiting for a call");
} }
void loop() void loop() {
{
// Check the status of the voice call // Check the status of the voice call
switch (vcs.getvoiceCallStatus()) switch (vcs.getvoiceCallStatus()) {
{
case IDLE_CALL: // Nothing is happening case IDLE_CALL: // Nothing is happening
break; break;
@ -93,8 +88,9 @@ void loop()
case TALKING: // In this case the call would be established case TALKING: // In this case the call would be established
Serial.println("TALKING. Press enter to hang up."); Serial.println("TALKING. Press enter to hang up.");
while (Serial.read() != '\n') while (Serial.read() != '\n') {
delay(100); delay(100);
}
vcs.hangCall(); vcs.hangCall();
Serial.println("Hanging up and waiting for the next call."); Serial.println("Hanging up and waiting for the next call.");
break; break;

View File

@ -30,8 +30,7 @@
GSM gsmAccess; GSM gsmAccess;
GSM_SMS sms; GSM_SMS sms;
void setup() void setup() {
{
// initialize serial communications and wait for port to open: // initialize serial communications and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -45,12 +44,10 @@ void setup()
// Start GSM shield // Start GSM shield
// If your SIM has PIN, pass it as a parameter of begin() in quotes // If your SIM has PIN, pass it as a parameter of begin() in quotes
while (notConnected) while (notConnected) {
{ if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
if (gsmAccess.begin(PINNUMBER) == GSM_READY)
notConnected = false; notConnected = false;
else } else {
{
Serial.println("Not connected"); Serial.println("Not connected");
delay(1000); delay(1000);
} }
@ -59,8 +56,7 @@ void setup()
Serial.println("GSM initialized"); Serial.println("GSM initialized");
} }
void loop() void loop() {
{
Serial.print("Enter a mobile number: "); Serial.print("Enter a mobile number: ");
char remoteNum[20]; // telephone number to send sms char remoteNum[20]; // telephone number to send sms
@ -86,22 +82,17 @@ void loop()
/* /*
Read input serial Read input serial
*/ */
int readSerial(char result[]) int readSerial(char result[]) {
{
int i = 0; int i = 0;
while (1) while (1) {
{ while (Serial.available() > 0) {
while (Serial.available() > 0)
{
char inChar = Serial.read(); char inChar = Serial.read();
if (inChar == '\n') if (inChar == '\n') {
{
result[i] = '\0'; result[i] = '\0';
Serial.flush(); Serial.flush();
return 0; return 0;
} }
if (inChar != '\r') if (inChar != '\r') {
{
result[i] = inChar; result[i] = inChar;
i++; i++;
} }

View File

@ -28,8 +28,7 @@
// initialize the library instance // initialize the library instance
GSMBand band; GSMBand band;
void setup() void setup() {
{
// initialize serial communications and wait for port to open: // initialize serial communications and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -44,8 +43,7 @@ void setup()
}; };
void loop() void loop() {
{
// Get current band // Get current band
String bandName = band.getBand(); // Get and print band name String bandName = band.getBand(); // Get and print band name
Serial.print("Current band:"); Serial.print("Current band:");
@ -60,17 +58,13 @@ void loop()
boolean operationSuccess; boolean operationSuccess;
operationSuccess = band.setBand(newBandName); operationSuccess = band.setBand(newBandName);
// Tell the user if the operation was OK // Tell the user if the operation was OK
if (operationSuccess) if (operationSuccess) {
{
Serial.println("Success"); Serial.println("Success");
} } else {
else
{
Serial.println("Error while changing band"); Serial.println("Error while changing band");
} }
if (operationSuccess) if (operationSuccess) {
{
while (true); while (true);
} }
} }
@ -78,8 +72,7 @@ void loop()
// This function offers the user different options // This function offers the user different options
// through the Serial interface // through the Serial interface
// The user selects one // The user selects one
String askUser() String askUser() {
{
String newBand; String newBand;
Serial.println("Select band:"); Serial.println("Select band:");
// Print the different options // Print the different options
@ -91,26 +84,28 @@ String askUser()
Serial.println("6 : GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)"); Serial.println("6 : GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)");
// Empty the incoming buffer // Empty the incoming buffer
while (Serial.available()) while (Serial.available()) {
Serial.read(); Serial.read();
}
// Wait for an answer, just look at the first character // Wait for an answer, just look at the first character
while (!Serial.available()); while (!Serial.available());
char c = Serial.read(); char c = Serial.read();
if (c == '1') if (c == '1') {
newBand = GSM_MODE_EGSM; newBand = GSM_MODE_EGSM;
else if (c == '2') } else if (c == '2') {
newBand = GSM_MODE_DCS; newBand = GSM_MODE_DCS;
else if (c == '3') } else if (c == '3') {
newBand = GSM_MODE_PCS; newBand = GSM_MODE_PCS;
else if (c == '4') } else if (c == '4') {
newBand = GSM_MODE_EGSM_DCS; newBand = GSM_MODE_EGSM_DCS;
else if (c == '5') } else if (c == '5') {
newBand = GSM_MODE_GSM850_PCS; newBand = GSM_MODE_GSM850_PCS;
else if (c == '6') } else if (c == '6') {
newBand = GSM_MODE_GSM850_EGSM_DCS_PCS; newBand = GSM_MODE_GSM850_EGSM_DCS_PCS;
else } else {
newBand = "GSM_MODE_UNDEFINED"; newBand = "GSM_MODE_UNDEFINED";
}
return newBand; return newBand;
} }

View File

@ -38,8 +38,7 @@ String IMEI = "";
// serial monitor result messages // serial monitor result messages
String errortext = "ERROR"; String errortext = "ERROR";
void setup() void setup() {
{
// initialize serial communications and wait for port to open: // initialize serial communications and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -54,12 +53,10 @@ void setup()
// Start GSM shield // Start GSM shield
// If your SIM has PIN, pass it as a parameter of begin() in quotes // If your SIM has PIN, pass it as a parameter of begin() in quotes
while (notConnected) while (notConnected) {
{ if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
if (gsmAccess.begin(PINNUMBER) == GSM_READY)
notConnected = false; notConnected = false;
else } else {
{
Serial.println("Not connected"); Serial.println("Not connected");
delay(1000); delay(1000);
} }
@ -70,12 +67,12 @@ void setup()
Serial.print("Modem IMEI: "); Serial.print("Modem IMEI: ");
IMEI = modemTest.getIMEI(); IMEI = modemTest.getIMEI();
IMEI.replace("\n", ""); IMEI.replace("\n", "");
if (IMEI != NULL) if (IMEI != NULL) {
Serial.println(IMEI); Serial.println(IMEI);
}
} }
void loop() void loop() {
{
// scan for existing networks, displays a list of networks // scan for existing networks, displays a list of networks
Serial.println("Scanning available networks. May take some seconds."); Serial.println("Scanning available networks. May take some seconds.");
Serial.println(scannerNetworks.readNetworks()); Serial.println(scannerNetworks.readNetworks());

View File

@ -32,8 +32,7 @@ boolean auth = false;
String oktext = "OK"; String oktext = "OK";
String errortext = "ERROR"; String errortext = "ERROR";
void setup() void setup() {
{
// initialize serial communications and wait for port to open: // initialize serial communications and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -46,52 +45,39 @@ void setup()
// check if the SIM have pin lock // check if the SIM have pin lock
while (!auth) { while (!auth) {
int pin_query = PINManager.isPIN(); int pin_query = PINManager.isPIN();
if (pin_query == 1) if (pin_query == 1) {
{
// if SIM is locked, enter PIN code // if SIM is locked, enter PIN code
Serial.print("Enter PIN code: "); Serial.print("Enter PIN code: ");
user_input = readSerial(); user_input = readSerial();
// check PIN code // check PIN code
if (PINManager.checkPIN(user_input) == 0) if (PINManager.checkPIN(user_input) == 0) {
{
auth = true; auth = true;
PINManager.setPINUsed(true); PINManager.setPINUsed(true);
Serial.println(oktext); Serial.println(oktext);
} } else {
else
{
// if PIN code was incorrected // if PIN code was incorrected
Serial.println("Incorrect PIN. Remember that you have 3 opportunities."); Serial.println("Incorrect PIN. Remember that you have 3 opportunities.");
} }
} } else if (pin_query == -1) {
else if (pin_query == -1)
{
// PIN code is locked, user must enter PUK code // PIN code is locked, user must enter PUK code
Serial.println("PIN locked. Enter PUK code: "); Serial.println("PIN locked. Enter PUK code: ");
String puk = readSerial(); String puk = readSerial();
Serial.print("Now, enter a new PIN code: "); Serial.print("Now, enter a new PIN code: ");
user_input = readSerial(); user_input = readSerial();
// check PUK code // check PUK code
if (PINManager.checkPUK(puk, user_input) == 0) if (PINManager.checkPUK(puk, user_input) == 0) {
{
auth = true; auth = true;
PINManager.setPINUsed(true); PINManager.setPINUsed(true);
Serial.println(oktext); Serial.println(oktext);
} } else {
else
{
// if PUK o the new PIN are incorrect // if PUK o the new PIN are incorrect
Serial.println("Incorrect PUK or invalid new PIN. Try again!."); Serial.println("Incorrect PUK or invalid new PIN. Try again!.");
} }
} } else if (pin_query == -2) {
else if (pin_query == -2)
{
// the worst case, PIN and PUK are locked // the worst case, PIN and PUK are locked
Serial.println("PIN & PUK locked. Use PIN2/PUK2 in a mobile phone."); Serial.println("PIN & PUK locked. Use PIN2/PUK2 in a mobile phone.");
while (true); while (true);
} } else {
else
{
// SIM does not requires authetication // SIM does not requires authetication
Serial.println("No pin necessary."); Serial.println("No pin necessary.");
auth = true; auth = true;
@ -100,47 +86,42 @@ void setup()
// start GSM shield // start GSM shield
Serial.print("Checking register in GSM network..."); Serial.print("Checking register in GSM network...");
if (PINManager.checkReg() == 0) if (PINManager.checkReg() == 0) {
Serial.println(oktext); Serial.println(oktext);
}
// if you are connect by roaming // if you are connect by roaming
else if (PINManager.checkReg() == 1) else if (PINManager.checkReg() == 1) {
Serial.println("ROAMING " + oktext); Serial.println("ROAMING " + oktext);
else } else {
{
// error connection // error connection
Serial.println(errortext); Serial.println(errortext);
while (true); while (true);
} }
} }
void loop() void loop() {
{
// Function loop implements pin management user menu // Function loop implements pin management user menu
// Only if you SIM use pin lock, you can change PIN code // Only if you SIM use pin lock, you can change PIN code
// user_op variables save user option // user_op variables save user option
Serial.println("Choose an option:\n1 - On/Off PIN."); Serial.println("Choose an option:\n1 - On/Off PIN.");
if (PINManager.getPINUsed()) if (PINManager.getPINUsed()) {
Serial.println("2 - Change PIN."); Serial.println("2 - Change PIN.");
}
String user_op = readSerial(); String user_op = readSerial();
if (user_op == "1") if (user_op == "1") {
{
Serial.println("Enter your PIN code:"); Serial.println("Enter your PIN code:");
user_input = readSerial(); user_input = readSerial();
// activate/deactivate PIN lock // activate/deactivate PIN lock
PINManager.switchPIN(user_input); PINManager.switchPIN(user_input);
} } else if (user_op == "2" & PINManager.getPINUsed()) {
else if (user_op == "2" & PINManager.getPINUsed())
{
Serial.println("Enter your actual PIN code:"); Serial.println("Enter your actual PIN code:");
String oldPIN = readSerial(); String oldPIN = readSerial();
Serial.println("Now, enter your new PIN code:"); Serial.println("Now, enter your new PIN code:");
String newPIN = readSerial(); String newPIN = readSerial();
// change PIN // change PIN
PINManager.changePIN(oldPIN, newPIN); PINManager.changePIN(oldPIN, newPIN);
} } else {
else
{
Serial.println("Incorrect option. Try again!."); Serial.println("Incorrect option. Try again!.");
} }
delay(1000); delay(1000);
@ -149,20 +130,17 @@ void loop()
/* /*
Read input serial Read input serial
*/ */
String readSerial() String readSerial() {
{
String text = ""; String text = "";
while (1) while (1) {
{ while (Serial.available() > 0) {
while (Serial.available() > 0)
{
char inChar = Serial.read(); char inChar = Serial.read();
if (inChar == '\n') if (inChar == '\n') {
{
return text; return text;
} }
if (inChar != '\r') if (inChar != '\r') {
text += inChar; text += inChar;
} }
} }
}
} }

View File

@ -43,8 +43,7 @@ String response = "";
// use a proxy // use a proxy
boolean use_proxy = false; boolean use_proxy = false;
void setup() void setup() {
{
// initialize serial communications and wait for port to open: // initialize serial communications and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -52,15 +51,13 @@ void setup()
} }
} }
void loop() void loop() {
{
use_proxy = false; use_proxy = false;
// start GSM shield // start GSM shield
// if your SIM has PIN, pass it as a parameter of begin() in quotes // if your SIM has PIN, pass it as a parameter of begin() in quotes
Serial.print("Connecting GSM network..."); Serial.print("Connecting GSM network...");
if (gsmAccess.begin(PINNUMBER) != GSM_READY) if (gsmAccess.begin(PINNUMBER) != GSM_READY) {
{
Serial.println(errortext); Serial.println(errortext);
while (true); while (true);
} }
@ -85,11 +82,9 @@ void loop()
// attach GPRS // attach GPRS
Serial.println("Attaching to GPRS with your APN..."); Serial.println("Attaching to GPRS with your APN...");
if (gprsAccess.attachGPRS(apn, login, password) != GPRS_READY) if (gprsAccess.attachGPRS(apn, login, password) != GPRS_READY) {
{
Serial.println(errortext); Serial.println(errortext);
} } else {
else {
Serial.println(oktext); Serial.println(oktext);
@ -117,40 +112,37 @@ void loop()
int res_connect; int res_connect;
// if use a proxy, connect with it // if use a proxy, connect with it
if (use_proxy) if (use_proxy) {
res_connect = client.connect(proxy, pport); res_connect = client.connect(proxy, pport);
else } else {
res_connect = client.connect(url, 80); res_connect = client.connect(url, 80);
}
if (res_connect) if (res_connect) {
{
// make a HTTP 1.0 GET request (client sends the request) // make a HTTP 1.0 GET request (client sends the request)
client.print("GET "); client.print("GET ");
// if use a proxy, the path is arduino.cc URL // if use a proxy, the path is arduino.cc URL
if (use_proxy) if (use_proxy) {
client.print(urlproxy); client.print(urlproxy);
else } else {
client.print(path); client.print(path);
}
client.println(" HTTP/1.0"); client.println(" HTTP/1.0");
client.println(); client.println();
Serial.println(oktext); Serial.println(oktext);
} } else {
else
{
// if you didn't get a connection to the server // if you didn't get a connection to the server
Serial.println(errortext); Serial.println(errortext);
} }
Serial.print("Receiving response..."); Serial.print("Receiving response...");
boolean test = true; boolean test = true;
while (test) while (test) {
{
// if there are incoming bytes available // if there are incoming bytes available
// from the server, read and check them // from the server, read and check them
if (client.available()) if (client.available()) {
{
char c = client.read(); char c = client.read();
response += c; response += c;
@ -167,8 +159,7 @@ void loop()
} }
// if the server's disconnected, stop the client: // if the server's disconnected, stop the client:
if (!client.connected()) if (!client.connected()) {
{
Serial.println(); Serial.println();
Serial.println("disconnecting."); Serial.println("disconnecting.");
client.stop(); client.stop();
@ -181,21 +172,16 @@ void loop()
/* /*
Read input serial Read input serial
*/ */
int readSerial(char result[]) int readSerial(char result[]) {
{
int i = 0; int i = 0;
while (1) while (1) {
{ while (Serial.available() > 0) {
while (Serial.available() > 0)
{
char inChar = Serial.read(); char inChar = Serial.read();
if (inChar == '\n') if (inChar == '\n') {
{
result[i] = '\0'; result[i] = '\0';
return 0; return 0;
} }
if (inChar != '\r') if (inChar != '\r') {
{
result[i] = inChar; result[i] = inChar;
i++; i++;
} }

View File

@ -27,8 +27,7 @@ GSMModem modem;
// IMEI variable // IMEI variable
String IMEI = ""; String IMEI = "";
void setup() void setup() {
{
// initialize serial communications and wait for port to open: // initialize serial communications and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -37,38 +36,32 @@ void setup()
// start modem test (reset and check response) // start modem test (reset and check response)
Serial.print("Starting modem test..."); Serial.print("Starting modem test...");
if (modem.begin()) if (modem.begin()) {
Serial.println("modem.begin() succeeded"); Serial.println("modem.begin() succeeded");
else } else {
Serial.println("ERROR, no modem answer."); Serial.println("ERROR, no modem answer.");
}
} }
void loop() void loop() {
{
// get modem IMEI // get modem IMEI
Serial.print("Checking IMEI..."); Serial.print("Checking IMEI...");
IMEI = modem.getIMEI(); IMEI = modem.getIMEI();
// check IMEI response // check IMEI response
if (IMEI != NULL) if (IMEI != NULL) {
{
// show IMEI in serial monitor // show IMEI in serial monitor
Serial.println("Modem's IMEI: " + IMEI); Serial.println("Modem's IMEI: " + IMEI);
// reset modem to check booting: // reset modem to check booting:
Serial.print("Resetting modem..."); Serial.print("Resetting modem...");
modem.begin(); modem.begin();
// get and check IMEI one more time // get and check IMEI one more time
if (modem.getIMEI() != NULL) if (modem.getIMEI() != NULL) {
{
Serial.println("Modem is functoning properly"); Serial.println("Modem is functoning properly");
} } else {
else
{
Serial.println("Error: getIMEI() failed after modem.begin()"); Serial.println("Error: getIMEI() failed after modem.begin()");
} }
} } else {
else
{
Serial.println("Error: Could not get IMEI"); Serial.println("Error: Could not get IMEI");
} }
// do nothing: // do nothing:

View File

@ -35,8 +35,7 @@ GSMServer server(80); // port 80 (http default)
// timeout // timeout
const unsigned long __TIMEOUT__ = 10 * 1000; const unsigned long __TIMEOUT__ = 10 * 1000;
void setup() void setup() {
{
// initialize serial communications and wait for port to open: // initialize serial communications and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {
@ -49,13 +48,11 @@ void setup()
// Start GSM shield // Start GSM shield
// If your SIM has PIN, pass it as a parameter of begin() in quotes // If your SIM has PIN, pass it as a parameter of begin() in quotes
while (!connected) while (!connected) {
{
if ((gsmAccess.begin(PINNUMBER) == GSM_READY) & if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &
(gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) {
connected = true; connected = true;
else } else {
{
Serial.println("Not connected"); Serial.println("Not connected");
delay(1000); delay(1000);
} }

View File

@ -48,8 +48,7 @@ void setup() {
Serial.begin(9600); Serial.begin(9600);
} }
void loop() void loop() {
{
// when characters arrive over the serial port... // when characters arrive over the serial port...
if (Serial.available()) { if (Serial.available()) {
// wait a bit for the entire message to arrive // wait a bit for the entire message to arrive

View File

@ -56,8 +56,9 @@ void loop() {
// empty the commands array // empty the commands array
void iniCommands() { void iniCommands() {
for (int i = 0; i < 20; i++) for (int i = 0; i < 20; i++) {
commands[i] = -1; commands[i] = -1;
}
} }
// add commands to the array // add commands to the array

View File

@ -99,17 +99,19 @@ void runScript() {
// get the next 2 commands (direction and duration) // get the next 2 commands (direction and duration)
parseCommand(danceScript[currentScript], danceScript[currentScript + 1]); parseCommand(danceScript[currentScript], danceScript[currentScript + 1]);
currentScript += 2; currentScript += 2;
if (danceScript[currentScript] == '\0') // at the end of the array if (danceScript[currentScript] == '\0') { // at the end of the array
currentScript = 0; // start again at the beginning currentScript = 0; // start again at the beginning
} }
}
} }
// instead of delay, use this timer // instead of delay, use this timer
boolean waiting() { boolean waiting() {
if (millis() - waitFrom >= waitTime) if (millis() - waitFrom >= waitTime) {
return false; return false;
else } else {
return true; return true;
}
} }
// how long to wait // how long to wait

View File

@ -45,10 +45,11 @@ void loop() {
int diff = compassValue - direc; int diff = compassValue - direc;
// modify degress // modify degress
if (diff > 180) if (diff > 180) {
diff = -360 + diff; diff = -360 + diff;
else if (diff < -180) } else if (diff < -180) {
diff = 360 + diff; diff = 360 + diff;
}
// Make the robot turn to its proper orientation // Make the robot turn to its proper orientation
diff = map(diff, -180, 180, -255, 255); diff = map(diff, -180, 180, -255, 255);

View File

@ -85,7 +85,9 @@ void keyDown(int keyCode) {
case BUTTON_LEFT: case BUTTON_LEFT:
//left button pressed, reduces tempo //left button pressed, reduces tempo
tempo -= 5; tempo -= 5;
if (tempo < 20) tempo = 20; //lowest tempo 20 if (tempo < 20) {
tempo = 20; //lowest tempo 20
}
Robot.fill(255, 190, 0); Robot.fill(255, 190, 0);
Robot.rect(53, 58, 13, 13); Robot.rect(53, 58, 13, 13);
@ -93,14 +95,18 @@ void keyDown(int keyCode) {
case BUTTON_RIGHT: case BUTTON_RIGHT:
//right button pressed, increases tempo //right button pressed, increases tempo
tempo += 5; tempo += 5;
if (tempo > 100) tempo = 100; //highest tempo 100 if (tempo > 100) {
tempo = 100; //highest tempo 100
}
Robot.fill(255, 190, 0); Robot.fill(255, 190, 0);
Robot.rect(93, 58, 13, 13); Robot.rect(93, 58, 13, 13);
break; break;
case BUTTON_UP: case BUTTON_UP:
//up button pressed, increases pitch //up button pressed, increases pitch
pitch += 120; pitch += 120;
if (pitch > 2000) pitch = 2000; if (pitch > 2000) {
pitch = 2000;
}
Robot.fill(0, 0, 255); Robot.fill(0, 0, 255);
Robot.rect(73, 38, 13, 13); Robot.rect(73, 38, 13, 13);

View File

@ -93,11 +93,15 @@ void keyboardControl() {
int keyPressed = Robot.keyboardRead(); // read the button values int keyPressed = Robot.keyboardRead(); // read the button values
switch (keyPressed) { switch (keyPressed) {
case BUTTON_LEFT: // display previous picture case BUTTON_LEFT: // display previous picture
if (--i < 1) i = NUM_PICS; if (--i < 1) {
i = NUM_PICS;
}
return; return;
case BUTTON_MIDDLE: // do nothing case BUTTON_MIDDLE: // do nothing
case BUTTON_RIGHT: // display next picture case BUTTON_RIGHT: // display next picture
if (++i > NUM_PICS) i = 1; if (++i > NUM_PICS) {
i = 1;
}
return; return;
case BUTTON_UP: // change mode case BUTTON_UP: // change mode
changeMode(-1); changeMode(-1);
@ -118,11 +122,16 @@ void compassControl(int change) {
//get the change of angle //get the change of angle
int diff = Robot.compassRead() - oldV; int diff = Robot.compassRead() - oldV;
if (diff > 180) diff -= 360; if (diff > 180) {
else if (diff < -180) diff += 360; diff -= 360;
} else if (diff < -180) {
diff += 360;
}
if (abs(diff) > change) { if (abs(diff) > change) {
if (++i > NUM_PICS) i = 1; if (++i > NUM_PICS) {
i = 1;
}
return; return;
} }
@ -146,8 +155,9 @@ void changeMode(int changeDir) {
mode += changeDir; mode += changeDir;
if (mode < 0) { if (mode < 0) {
mode = 1; mode = 1;
} else if (mode > 1) } else if (mode > 1) {
mode = 0; mode = 0;
}
// display the mode on screen // display the mode on screen
Robot.fill(255, 255, 255); Robot.fill(255, 255, 255);

View File

@ -34,8 +34,7 @@ SdFile root;
// Sparkfun SD shield: pin 8 // Sparkfun SD shield: pin 8
const int chipSelect = 4; const int chipSelect = 4;
void setup() void setup() {
{
// Open serial communications and wait for port to open: // Open serial communications and wait for port to open:
Serial.begin(9600); Serial.begin(9600);
while (!Serial) { while (!Serial) {

Some files were not shown because too many files have changed in this diff Show More