//
// Generate a signal to trigger camera and lightning
//

// Setup
int button = 7;
int trigger = 13;
boolean running = false;
int button_state;
int last_button_state = LOW;
int high_duration = 10;
int low_duration = 190; // 5Hz
//int low_duration = 101; // 9Hz

// Arduino setup
void setup() {
  // Input-Output signals
  pinMode( button, INPUT );
  pinMode( trigger, OUTPUT );
}

// Main loop
void loop() {
  // Start / Stop button
  button_state = digitalRead( button );
  if( button_state == HIGH && last_button_state == LOW ) {
    running = !running;
    delay( 50 );
  }
  last_button_state = button_state;
  // Trigger
  if( running ) {
    // High state
    digitalWrite( trigger, HIGH );
    delay( high_duration );
    // Low state
    digitalWrite( trigger, LOW );
    delay( low_duration );
  }
}

//
// Generate a 9Hz signal to trigger camera and lightning
//

// Setup
int button = 7;
int trigger = 13;
boolean running = false;
int button_state;
int last_button_state = LOW;
int high_duration = 10;
int low_duration = 101;

// Arduino setup
void setup() {
  // Input-Output signals
  pinMode( button, INPUT );
  pinMode( trigger, OUTPUT );
}

// Main loop
void loop() {
  // Start / Stop button
  button_state = digitalRead( button );
  if( button_state == HIGH && last_button_state == LOW ) {
    running = !running;
    delay( 50 );
  }
  last_button_state = button_state;
  // Trigger
  if( running ) {
    // High state
    digitalWrite( trigger, HIGH );
    delay( high_duration );
    // Low state
    digitalWrite( trigger, LOW );
    delay( low_duration );
  }
}

Change the trigger frequency to 9Hz.

Change the trigger frequency to 9Hz.


// RFID_UART.ino

#if defined (SPARK)
#include "SeeedRFID/SeeedRFID.h"
#else
#include <SoftwareSerial.h>
#include <SeeedRFID.h>
#endif

#define RFID_RX_PIN 10
#define RFID_TX_PIN 11

// #define DEBUG
#define TEST

SeeedRFID RFID(RFID_RX_PIN, RFID_TX_PIN);
RFIDdata tag;

void setup() {
	Serial1.begin(9600);	//Done here to prevent SeeedRFID constructor system crash

	Serial.begin(57600);
	Serial.println("Hello, double bk!");
}

void loop() {
	if(RFID.isAvailable()){
		tag = RFID.data();
		Serial.print("RFID card number: ");
		Serial.println(RFID.cardNumber());
#ifdef TEST
	Serial.print("RFID raw data: ");
	for(int i=0; i<tag.dataLen; i++){
	    Serial.print(tag.raw[i], HEX);
	    Serial.print('\t');
		}
#endif
	}
}

// RFID_UART.ino

#if defined (SPARK)
#include "SeeedRFID/SeeedRFID.h"
#else
#include <SoftwareSerial.h>
#include <SeeedRFID.h>
#endif

#define RFID_RX_PIN 10
#define RFID_TX_PIN 11

// #define DEBUGRFID
#define TEST

SeeedRFID RFID(RFID_RX_PIN, RFID_TX_PIN);
RFIDdata tag;

void setup() {
	Serial1.begin(9600);	//Done here to prevent SeeedRFID constructor system crash

	Serial.begin(57600);
	Serial.println("Hello, double bk!");
}

void loop() {
	if(RFID.isAvailable()){
		tag = RFID.data();
		Serial.print("RFID card number: ");
		Serial.println(RFID.cardNumber());
#ifdef TEST
	Serial.print("RFID raw data: ");
	for(int i=0; i<tag.dataLen; i++){
	    Serial.print(tag.raw[i], HEX);
	    Serial.print('\t');
		}
#endif
	}
}

Fix DEBUG compile flag issue

Fix DEBUG compile flag issue


/**
 * Display the voltage measured at four 16-bit channels.
 *
 * Copyright (c) 2014 Circuitar
 * All rights reserved.
 *
 * This software is released under a BSD license. See the attached LICENSE file for details.
 */
#include <Wire.h>
#include <Nanoshield_ADC.h>

Nanoshield_ADC adc[4] = { 0x48, 0x49, 0x4A, 0x4B };

void setup()
{
  Serial.begin(9600);
  Serial.println("ADC Nanoshield Test - Voltage Measurement - 16 x 12-bit");
  Serial.println("");

  for (int i = 0; i < 4; i++) {
    adc[i].begin();
  }
}

void loop()
{
  for (int i = 0; i < 16; i++) {
    Serial.print("A");
    Serial.print(i%4);
    Serial.print(" (");
    Serial.print(i/4);
    Serial.print(") voltage: ");
    Serial.print(adc[i/4].readVoltage(i%4));
    Serial.println("V");
  }
  Serial.println();

  delay(1000);
}

/**
 * Display the voltage measured at four 16-bit channels.
 *
 * Copyright (c) 2014 Circuitar
 * All rights reserved.
 *
 * This software is released under a BSD license. See the attached LICENSE file for details.
 */
#include <Wire.h>
#include <Nanoshield_ADC.h>

Nanoshield_ADC adc[4] = { 0x48, 0x49, 0x4A, 0x4B };

void setup()
{
  Serial.begin(9600);
  Serial.println("ADC Nanoshield Test - Voltage Measurement - 16 x 16-bit");
  Serial.println("");

  for (int i = 0; i < 4; i++) {
    adc[i].begin();
  }
}

void loop()
{
  for (int i = 0; i < 16; i++) {
    Serial.print("A");
    Serial.print(i%4);
    Serial.print(" (");
    Serial.print(i/4);
    Serial.print(") voltage: ");
    Serial.print(adc[i/4].readVoltage(i%4));
    Serial.println("V");
  }
  Serial.println();

  delay(1000);
}

Fix text shown on serial monitor.

Fix text shown on serial monitor.


/*
 MQTT subscriber example

  - connects to an MQTT server
  - subscribes to the topic "inTopic"
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char *ssid =	"xxxxxxxx";		// cannot be longer than 32 characters!
const char *pass =	"yyyyyyyy";		//

// Update these with values suitable for your network.
IPAddress server(172, 16, 0, 2);

void callback(MQTT::Publish& pub) {
  Serial.print(pub.topic());
  Serial.print(" => ");
  Serial.print(pub.payload_string());
}

PubSubClient client(server);

void setup()
{
  // Setup console
  Serial.begin(115200);
  delay(10);
  Serial.println();
  Serial.println();

  client.set_callback(callback);

  WiFi.begin(ssid, pass);

  int retries = 0;
  while ((WiFi.status() != WL_CONNECTED) && (retries < 10)) {
    retries++;
    delay(500);
    Serial.print(".");
  }
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("");
    Serial.println("WiFi connected");
  }

  if (client.connect("arduinoClient")) {
    client.subscribe("inTopic");
  }
}

void loop()
{
  client.loop();
}

/*
 MQTT subscriber example

  - connects to an MQTT server
  - subscribes to the topic "inTopic"
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char *ssid =	"xxxxxxxx";		// cannot be longer than 32 characters!
const char *pass =	"yyyyyyyy";		//

// Update these with values suitable for your network.
IPAddress server(172, 16, 0, 2);

void callback(const MQTT::Publish& pub) {
  Serial.print(pub.topic());
  Serial.print(" => ");
  Serial.print(pub.payload_string());
}

PubSubClient client(server);

void setup()
{
  // Setup console
  Serial.begin(115200);
  delay(10);
  Serial.println();
  Serial.println();

  client.set_callback(callback);

  WiFi.begin(ssid, pass);

  int retries = 0;
  while ((WiFi.status() != WL_CONNECTED) && (retries < 10)) {
    retries++;
    delay(500);
    Serial.print(".");
  }
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("");
    Serial.println("WiFi connected");
  }

  if (client.connect("arduinoClient")) {
    client.subscribe("inTopic");
  }
}

void loop()
{
  client.loop();
}

Fix signature of callback function in subscriber example


#define HALLPIN P1_5

int revs;
int count;
unsigned long oldtime;
unsigned long average;
int rpm[5];
int hallRead;
int switched;
void magnet_detect();

void setup()
{
    Serial.begin(9600);
    //Pull down to start
    pinMode(HALLPIN,INPUT_PULLDOWN);

    //initialize variables
    switched = 0;
    revs = 0;
    oldtime = 0;
    average = 0;
    count = 0;
}

void loop()
{
    hallRead = digitalRead(HALLPIN);

    //Using moving average to calculate RPM, I don't think it is totally correct
    if(millis() - oldtime > 1000)
    {
        average -= average / 5;
        average += (revs*30) / 5;

        oldtime = millis();
        revs = 0;
        Serial.println(average,DEC);
    }

    if(hallRead == 1 && switched == 0)
    {
        Serial.print("HallPin State: HIGH\n");
       revs++;
       switched = 1;
    }else if(hallRead == 0 && switched == 1)
    {
       Serial.print("HallPin State: LOW\n");
       revs++;
       switched = 0;
    }

}

#define HALLPIN P1_5

int revs;
unsigned long oldtime;
unsigned int average;
int rpm[5];
int hallRead;
int switched;

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

    //Pull up to start
    pinMode(HALLPIN,INPUT_PULLUP);
    pinMode(P1_4,OUTPUT);
    digitalWrite(P1_4,HIGH);

    //initialize variables
    switched = 0;
    revs = 0;
    oldtime = 0;
    average = 0;
}

void loop()
{
    hallRead = digitalRead(HALLPIN);

    //Using moving average to calculate RPM, I don't think it is totally correct
    if(millis() - oldtime > 1000)
    {
        average -= average / 5;
        average += (revs*30) / 5;

        oldtime = millis();
        revs = 0;
        Serial.println(average,DEC);
    }

    if(hallRead == 1 && switched == 0)
    {
        Serial.print("HallPin State: HIGH\n");
       revs++;
       switched = 1;
    }else if(hallRead == 0 && switched == 1)
    {
       Serial.print("HallPin State: LOW\n");
       revs++;
       switched = 0;
    }
}

Update hallsensor code to reflect changes in wiring on breadboard using pullup resistor


#include <FastLED.h>
#include <Segment16.h>

Segment16 display;

void setup(){
  Serial.begin(9600);
  while (!Serial) {}  // wait for Leonardo
  Serial.println("Type any character to start");
  while (Serial.read() <= 0) {}
  delay(200);  // Catch Due reset problem
  // assume the user typed a valid character and no reset happened
}

void loop(){
  Serial.println("LOOP");
  display.show();
  delay(1000);
}

#include <FastLED.h>
#include <Segment16.h>

Segment16 display;
uint32_t incomingByte = 0, input = 0;   // for incoming serial data

void setup(){
  Serial.begin(9600);
  while (!Serial) {}  // wait for Leonard
  Serial.println("Type any character to start");
  while (Serial.read() <= 0) {}
  delay(200);  // Catch Due reset problem
  display.init();
  // assume the user typed a valid character and no reset happened
}

void loop(){
  if(Serial.available() > 0){
    input = 0;
    while(Serial.available() > 0){
      incomingByte = Serial.read();
      input = (input << 8) | incomingByte;
    }
    display.pushChar(input);
    Serial.println(input, HEX);
    //incomingByte = Serial.read();
  }
  display.show();
  delay(5);
}

Add ability to input alt characters

Add ability to input alt characters


/**
 * Read raw 20-bit integer value from a load cell using the ADS1230 IC in the LoadCell Nanoshield.
 *
 * Copyright (c) 2015 Circuitar
 * This software is released under the MIT license. See the attached LICENSE file for details.
 */
#include <SPI.h>
#include <Nanoshield_LoadCell.h>

// LoadCell Nanoshield with the following parameters:
//  - Load cell capacity: 100kg
//  - Load cell sensitivity: 3mV/V
//  - CS on pin D8 (D8 jumper closed)
//  - High gain (GAIN jumper closed)
//  - No averaging (number of samples = 1)
Nanoshield_LoadCell loadCell(100000, 3, 8, true, 1);

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

void loop() {
  if (loadCell.updated()) {
    Serial.println(loadCell.getLatestRawValue(), 0);
  }
}

/**
 * Read raw 20-bit integer value from a load cell using the ADS1230 IC in the LoadCell Nanoshield.
 *
 * Copyright (c) 2015 Circuitar
 * This software is released under the MIT license. See the attached LICENSE file for details.
 */
#include <SPI.h>
#include <Nanoshield_LoadCell.h>

// LoadCell Nanoshield with the following parameters:
//  - Load cell capacity: 100kg
//  - Load cell sensitivity: 3mV/V
//  - CS on pin D8 (D8 jumper closed)
//  - High gain (GAIN jumper closed)
//  - No averaging (number of samples = 1)
Nanoshield_LoadCell loadCell(100000, 3, 8, true, 1);

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

void loop() {
  if (loadCell.updated()) {
    Serial.println(loadCell.getLatestRawValue());
  }
}

Fix raw value output to serial terminal.


void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}

/*
  Turns on an LED for one seconds, then off for one second, repeat.

  This example is adapted from Examples > 01.Basics > Blink

 */

// On the Arduino UNO the onboard LED is attached to digital pin 13
#define LED 13

void setup() {
  // put your setup code here, to run once:

  pinMode(LED, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

  digitalWrite(LED, HIGH);     // turn the LED on
  delay(1000);
  digitalWrite(LED, LOW);      // turn the LED off
  delay(1000);
}

Add code for blinking LED on digital out 13

Signed-off-by: Gianpaolo Macario <f8885408b8c3d931b330bae3c3a28a3af912c463@gmail.com>


#include <NewPing.h>
#include <Sonar.h>
#include <Tach.h>

#define SENSOR_SONAR 14
#define SENSOR_TACH_0 2
#define SENSOR_TACH_1 3
#define MAX_DISTANCE 300
#define LED13 13
#define FREQ 20

void tach_0_dispatcher();
void tach_1_dispatcher();

Sonar sonar(SENSOR_SONAR, MAX_DISTANCE);
Tach tach_0(SENSOR_TACH_0, tach_0_dispatcher);
Tach tach_1(SENSOR_TACH_1, tach_1_dispatcher);

void setup() {
  digitalWrite(LED13,LOW);
  Serial.begin(115200);
}

void loop() {
  send("sonar", sonar.get_range());
  send("tach0", tach_0.get_rpm());
  send("tach1", tach_1.get_rpm());
  delay(1000/FREQ);
}

void send(const String& label, int value)
{
  digitalWrite(LED13,HIGH);
  Serial.print("{\"type\":");
  Serial.print(label);
  Serial.print("\", \"value\":");
  Serial.print(value);
  Serial.print("}");
  Serial.println();
  digitalWrite(LED13,LOW);
}

void tach_0_dispatcher(){
  tach_0.handler();
}

void tach_1_dispatcher(){
  tach_1.handler();
}

#include <NewPing.h>
#include <Sonar.h>
#include <Tach.h>

#define SENSOR_SONAR 14
#define SENSOR_TACH_0 2
#define SENSOR_TACH_1 3
#define MAX_DISTANCE 300
#define LED13 13
#define FREQ 20

void tach_0_dispatcher();
void tach_1_dispatcher();

Sonar sonar(SENSOR_SONAR, MAX_DISTANCE);
Tach tach_0(SENSOR_TACH_0, tach_0_dispatcher);
Tach tach_1(SENSOR_TACH_1, tach_1_dispatcher);

void setup() {
  digitalWrite(LED13,LOW);
  Serial.begin(115200);
}

void loop() {
  send("sonar", sonar.get_range());
  send("tach0", tach_0.get_rpm());
  send("tach1", tach_1.get_rpm());
  delay(1000/FREQ);
}

void send(const String& label, int value)
{
  digitalWrite(LED13,HIGH);
  Serial.print("{\"sensor\":");
  Serial.print(label);
  Serial.print("\", \"value\":");
  Serial.print(value);
  Serial.print("}");
  Serial.println();
  digitalWrite(LED13,LOW);
}

void tach_0_dispatcher(){
  tach_0.handler();
}

void tach_1_dispatcher(){
  tach_1.handler();
}

Use the sensor id as the identifier.

Use the sensor id as the identifier.


/*
  Test SD Card Shield sensor with Low Power library sleep

  This sketch specifically tests the DeadOn RTC - DS3234 Breakout board
  used on our sensor platform.

  This sketch will write a value of n + 1 to the file test.txt when
  the RocketScream wakes up.

  You should detach the RTC breakout board and GSM Shield.

  Created 1 7 2014
  Modified 1 7 2014
*/

#include <LowPower.h>

#include <UASensors_SDCard.h>

// UASensors SDCard Dependency
#include <SdFat.h>

// LED blink settings
const byte LED = 13;
const int BLINK_DELAY = 5;

// SD card settings
const byte SD_CS_PIN = 10;

// Settings
#define TEST_FILENAME "test.txt"

int wakeupCount = 0;
UASensors_SDCard sd(SD_CS_PIN);

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

void loop()
{
  // Sleep for about 8 seconds
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

  wakeupCount += 1;

  sd.begin();
  sd.writeFile(TEST_FILENAME, String(wakeupCount));
  delay(1000);
}

// Simple blink function
void blink(byte pin, int delay_ms)
{
  pinMode(pin, OUTPUT);
  digitalWrite(pin, HIGH);
  delay(delay_ms);
  digitalWrite(pin, LOW);
}

/*
  Test SD Card Shield sensor with Low Power library sleep

  This sketch specifically tests the DeadOn RTC - DS3234 Breakout board
  used on our sensor platform.

  This sketch will write a value of n + 1 to the file test.txt each time
  the RocketScream wakes up.

  You should detach the RTC breakout board and GSM Shield.

  Created 1 7 2014
  Modified 2 7 2014
*/

#include <LowPower.h>

#include <UASensors_SDCard.h>

// UASensors SDCard Dependency
#include <SdFat.h>

// SD card settings
const byte SD_CS_PIN = 10;

// Settings
#define TEST_FILENAME "test.txt"

int wakeupCount = 0;
UASensors_SDCard sd(SD_CS_PIN);

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

void loop()
{
  // Sleep for about 8 seconds
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

  wakeupCount += 1;

  sd.begin();
  sd.writeFile(TEST_FILENAME, String(wakeupCount));
  delay(1000);
}

Remove blink code since unused here

Remove blink code since unused here


#include "serLCD.h"

#define LCD_PIN 2
#define LED_PIN 13
#define BLINK_DELAY 75

/*serLCD lcd(LCD_PIN);*/

void setup() {
  delay(2000);

  Serial.begin(9600);
  Serial.println("hello world");

  for (int i = 0; i < 4; i++) {
    blink();
  }

  delay(1000);
}

String str = "";
char character;

void loop() {
  ledOff();
  Serial.print("fa;");

  // wait for FA00000000000;
  while (Serial.available() > 0) {
    character = Serial.read();

    if (character != ';') {
      str += character;
    } else {
      ledOn();

      displayFrequency(str);
      str = "";
    }
  }

  delay(1000);
}

void displayFrequency(String msg) {
  Serial.println();
  Serial.println("------------");
  Serial.println(msg);
  Serial.println("------------");
}

void ledOn() {
  led(HIGH);
}

void ledOff() {
  led(LOW);
}

void led(int state) {
  digitalWrite(LED_PIN, state);
}

void blink() {
  ledOn();
  delay(BLINK_DELAY);
  ledOff();
  delay(BLINK_DELAY);
}

#include "serLCD.h"

#define LCD_PIN 5
#define LED_PIN 13
#define BLINK_DELAY 75

serLCD lcd(LCD_PIN);

void setup() {
  delay(2000);

  Serial.begin(9600);
  Serial.println("hello world");

  for (int i = 0; i < 4; i++) {
    blink();
  }

  delay(1000);
}

String str = "";
char character;

void loop() {
  ledOff();
  Serial.print("fa;");

  // wait for FA00000000000;
  while (Serial.available() > 0) {
    character = Serial.read();

    if (character != ';') {
      str += character;
    } else {
      ledOn();

      displayFrequency(str);
      str = "";
    }
  }

  delay(1000);
}

void displayFrequency(String msg) {
  Serial.println();
  Serial.println("------------");
  Serial.println(msg);
  Serial.println("------------");
}

void ledOn() {
  led(HIGH);
}

void ledOff() {
  led(LOW);
}

void led(int state) {
  digitalWrite(LED_PIN, state);
}

void blink() {
  ledOn();
  delay(BLINK_DELAY);
  ledOff();
  delay(BLINK_DELAY);
}

Set up the LCD pin

Set up the LCD pin


/*
 Controlling a servo position using a potentiometer (variable resistor)
 by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>

 modified on 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Knob
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int potpin = 0;  // analog pin used to connect the potentiometer
int val;    // variable to read the value from the analog pin

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
  val = map(val, 0, 1023, 0, 180);     // scale it to use it with the servo (value between 0 and 180)
  myservo.write(val);                  // sets the servo position according to the scaled value
  delay(15);                           // waits for the servo to get there
}

/*
 Controlling a servo position using a potentiometer (variable resistor)
 by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>

 modified on 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Knob
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int potpin = 0;  // analog pin used to connect the potentiometer
int val;    // variable to read the value from the analog pin

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
  val = map(val, 0, 1023, 0, 180);     // scale it to use it with the servo (value between 0 and 180)
  myservo.write(val);                  // sets the servo position according to the scaled value$
  delay(15);                           // waits for the servo to get there
}

Modify pin 19's pin description for EVT board

Signed-off-by: Kevin Moloney <8d8bc1a72c6f3e47b067d54d8af800cedf125850@emutex.com>


#define LED GREEN_LED

void setupBlueLed() {
  // initialize the digital pin as an output.
  pinMode(LED, OUTPUT);
}

// the loop routine runs over and over again forever as a task.
void loopBlueLed() {
  digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);               // wait for a second
  digitalWrite(LED, LOW);    // turn the LED off by making the voltage LOW
  delay(500);               // wait for a second
}

#define LED GREEN_LED

void setupGreenLed() {
  // initialize the digital pin as an output.
  pinMode(LED, OUTPUT);
}

// the loop routine runs over and over again forever as a task.
void loopGreenLed() {
  digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);               // wait for a second
  digitalWrite(LED, LOW);    // turn the LED off by making the voltage LOW
  delay(500);               // wait for a second
}

Correct typo in setup/loop tuple

Correct typo in setup/loop tuple


const int BUTTON_PIN = 12;
const int LED_PIN = 13;

// See https://www.arduino.cc/en/Tutorial/StateChangeDetection

void setup() {
  // Initialize the button pin as a input.
  pinMode(BUTTON_PIN, INPUT);
  // initialize the LED as an output.
  pinMode(LED_PIN, OUTPUT);
  // Initialize serial communication for debugging.
  Serial.begin(9600);

}

int buttonState = 0;
int lastButtonState = 0;

void loop() {
  buttonState = digitalRead(BUTTON_PIN);

  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      // If the current state is HIGH then the button
      // went from off to on:
      Serial.println("on");

      // Light the LED.
      digitalWrite(LED_PIN, HIGH);
      delay(100);
      digitalWrite(LED_PIN, LOW);

    } else {
      Serial.println("off");
    }
    // Delay a little bit to avoid bouncing.
    delay(50);
  }
  lastButtonState = buttonState;
}

const int BUTTON_PIN = 12;
const int LED_PIN = 13;
const int PIEZO_PIN = 8;

// See https://www.arduino.cc/en/Tutorial/StateChangeDetection

void setup() {
  // Initialize the button pin as a input.
  pinMode(BUTTON_PIN, INPUT);
  // initialize the LED as an output.
  pinMode(LED_PIN, OUTPUT);
  // Initialize serial communication for debugging.
  Serial.begin(9600);
}

int buttonState = 0;
int lastButtonState = 0;

void loop() {
  buttonState = digitalRead(BUTTON_PIN);

  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      // If the current state is HIGH then the button
      // went from off to on:
      Serial.println("on");

    } else {
      Serial.println("off");
    }
  }
  lastButtonState = buttonState;

  if (buttonState == HIGH) {
    // Play a tone
    tone(PIEZO_PIN, 200, 20);
    // Light the LED.
    digitalWrite(LED_PIN, HIGH);
    // Delay a little bit to avoid bouncing.
    delay(50);
  } else {
    digitalWrite(LED_PIN, LOW);
  }
}

Add sound when button is held down

Add sound when button is held down


#include "neopixel/neopixel.h"
#include "RandomPixels.h"

#define PIN 6

Adafruit_NeoPixel snowStrip1 = Adafruit_NeoPixel(24, PIN, WS2812);
RandomPixels snowRing1 = RandomPixels();

void setup() {

    snowStrip1.begin();
    snowStrip1.show();
    randomSeed(analogRead(0));

}

void loop() {

    snowRing1.Animate(snowStrip1, snowStrip1.Color(127, 127, 127), 100);

}

#include "neopixel/neopixel.h"
#include "RandomPixels.h"

Adafruit_NeoPixel neopixelRingLarge = Adafruit_NeoPixel(24, 6, WS2812);
RandomPixels ringLarge = RandomPixels();

Adafruit_NeoPixel neopixelRingMedium = Adafruit_NeoPixel(16, 7, WS2812);
RandomPixels ringMedium = RandomPixels();

Adafruit_NeoPixel neopixelRingSmall = Adafruit_NeoPixel(12, 8, WS2812);
RandomPixels ringSmall = RandomPixels();

// This is the pixel on the top...it will be controlled differently: TODO
Adafruit_NeoPixel neopixelSingle = Adafruit_NeoPixel(1, 9, WS2812);

void setup() {

    neopixelRingLarge.begin();
    neopixelRingLarge.show();

    neopixelRingMedium.begin();
    neopixelRingMedium.show();

    neopixelRingSmall.begin();
    neopixelRingSmall.show();

    neopixelSingle.begin();
    neopixelSingle.show();

    randomSeed(analogRead(0));

}

void loop() {

    // Snow...make this into function that is callable from API: TODO
    ringSmall.Animate(neopixelRingLarge, neopixelRingLarge.Color(127, 127, 127), 100);
    ringMedium.Animate(neopixelRingLarge, neopixelRingLarge.Color(127, 127, 127), 100);
    ringLarge.Animate(neopixelRingLarge, neopixelRingLarge.Color(127, 127, 127), 100);

}

Work on snow animation for three rings of tree


#include <RunningAverage.h>
#include <HX711.h>

#define DISP_TIMER_CLK 12
#define DISP_TIMER_DIO 11
#define DISP_SCALE_CLK 3
#define DISP_SCALE_DIO 2
#define SCALE_DT       A1
#define SCALE_SCK      A2
#include "TimerDisplay.h"
#include "GramsDisplay.h"

#define FILTER_SIZE 10

#define SCALE_FACTOR 1876
#define SCALE_OFFSET 105193 - 100

TimerDisplay         timerDisplay(DISP_TIMER_CLK, DISP_TIMER_DIO);
GramsDisplay         gramsDisplay(DISP_SCALE_CLK, DISP_SCALE_DIO);
HX711                scale;
RunningAverage       filter(FILTER_SIZE);
float                weight_in_grams;

void setup() {
  // Serial comm
  Serial.begin(38400);

  // Load cell
  scale.begin(SCALE_DT, SCALE_SCK);
  scale.set_scale(SCALE_FACTOR);
  scale.set_offset(SCALE_OFFSET);

  // Filter
  filter.clear();
}

void loop() {
  filter.addValue(scale.get_units());
  weight_in_grams = filter.getAverage();
  gramsDisplay.displayGrams(weight_in_grams);

  if (weight_in_grams > 1)
    timerDisplay.start();
  else
    timerDisplay.stop();

  timerDisplay.refresh();
}

#include <RunningAverage.h>
#include <HX711.h>

#include "TimerDisplay.h"
#include "GramsDisplay.h"

#define DISP_TIMER_CLK 2
#define DISP_TIMER_DIO 3
#define DISP_SCALE_CLK 8
#define DISP_SCALE_DIO 9
#define SCALE_DT       A2
#define SCALE_SCK      A1

#define FILTER_SIZE 10

#define SCALE_FACTOR 1874
#define SCALE_OFFSET 984550

TimerDisplay         timerDisplay(DISP_TIMER_CLK, DISP_TIMER_DIO);
GramsDisplay         gramsDisplay(DISP_SCALE_CLK, DISP_SCALE_DIO);
HX711                scale;
RunningAverage       filter(FILTER_SIZE);
float                weight_in_grams;

void setup() {
  // Serial comm
  Serial.begin(38400);

  // Load cell
  scale.begin(SCALE_DT, SCALE_SCK);
  scale.set_scale(SCALE_FACTOR);
  scale.set_offset(SCALE_OFFSET);

  // Filter
  filter.clear();
}

void loop() {
  filter.addValue(scale.get_units());
  weight_in_grams = filter.getAverage();
  gramsDisplay.displayGrams(weight_in_grams);

  if (weight_in_grams > 1)
    timerDisplay.start();
  else
    timerDisplay.stop();

  timerDisplay.refresh();
}

Update pin numbers and load cell params

Update pin numbers and load cell params


#define thresh 600 // If our analogRead is less than this we will blink

void setup() {
  pinMode(13,OUTPUT); // On board LED in Arduino Micro is 13
}

void loop() {
  int sensorValue = analogRead(A0); // read the voltage from the sensor on A0
  Serial.println(sensorValue,DEC);  // print the value
  digitalWrite(13,sensorValue<500); // Light LED if sensorValue is under thresh, else dark
  delay(1000); // sleep for 1 second
}

#define thresh 600 // If our analogRead is less than this we will blink

void setup() {
  pinMode(LED_BUILTIN,OUTPUT); // On board LED in Arduino Micro is 13
}

void loop() {
  int sensorValue = analogRead(A0); // read the voltage from the sensor on A0
  Serial.println(sensorValue,DEC);  // print the value
  digitalWrite(LED_BUILTIN,sensorValue<500); // Light LED if sensorValue is under thresh, else dark
  delay(1000); // sleep for 1 second
}

Tweak to code so it will use the builtin LED on any board


#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif

#define NUM_LEDS 300
#define PIN 7
#define WHITE 255,255,255

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);

int lighting_style = 0;
int intensity = 0;
uint8_t index = 0;

void setup() {
    Serial.begin(9600);
    strip.begin();
    strip.show();
    randomSeed(analogRead(0));
}

void loop() {
    if (Serial.available() > 1) {
      lighting_style = Serial.read();
      intensity = Serial.read();

      if(intensity == 0){
        index = random(300);
      }

      strip.setPixelColor(index, strip.Color(255,255,255));
      strip.setBrightness(intensity);
      strip.show();

      Serial.print("Index: ");
      Serial.print(index);
      Serial.print("  Intensity:");
      Serial.println(intensity);

    }
}

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif

#define NUM_LEDS 300
#define PIN 7
#define WHITE 255,255,255

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);

uint8_t intensity = 0;
uint8_t index = 0;

void setup() {
    Serial.begin(9600);
    strip.begin();
    strip.show();
    randomSeed(analogRead(0));
}

void loop() {
    if (Serial.available() > 0) {
      intensity = Serial.read();

      if(intensity == 0){
        index = random(294)+3;
      }

      strip.setPixelColor(index, strip.Color(255,255,255));
      strip.setPixelColor(index+1, strip.Color(255,255,255));
      strip.setPixelColor(index+2, strip.Color(255,255,255));

      strip.setBrightness(intensity);
      strip.show();
//      Serial.println(index);
    }
}

Update arduino code to light 3 pixels at a time.


#define robot_number 1 //Define qual robô esta sendo configurado
#include <pins.h>
#include <radio.h>
#include <motor.h>
#include <encoder.h>
#include <control.h>

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

  Radio::Setup();
  Motor::Setup();
  Encoder::Setup();
  Control::acc = 0;
}

void loop(){
  Control::stand();
}

Facilitate how to define which robot is being configured, on .ino now.


void setup() {
  // put your setup code here, to run once:

  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(4, INPUT);
  pinMode(5, INPUT);
  pinMode(6, INPUT);

  pinMode(13, OUTPUT);

}

void loop() {

  int len = 500;
  int t1 = 220;
  int t2 = 246.94;
  int t3 = 277.18;
  int t4 = 293.66;
  int t5 = 329.63;

  if (digitalRead(2) == HIGH) {
    tone(13, t1);
    delay(len);
    noTone(13);

  }

  if (digitalRead(3) == HIGH) {
    tone(13, t2);
    delay(len);
    noTone(13);

  }
  if (digitalRead(4) == HIGH) {
    tone(13, t3);
    delay(len);
    noTone(13);

  }
  if (digitalRead(5) == HIGH) {
    tone(13, t4);
    delay(len);
    noTone(13);

  }
  if (digitalRead(6) == HIGH) {
    tone(13, t5);
    delay(len);
    noTone(13);

}
}

void setup() {
  // put your setup code here, to run once:

  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(4, INPUT);
  pinMode(5, INPUT);
  pinMode(6, INPUT);

  pinMode(13, OUTPUT);

}

void loop() {

  int len = 500;
  float t1 = 220;
  float t2 = 246.94;
  float t3 = 277.18;
  float t4 = 293.66;
  float t5 = 329.63;

  if (digitalRead(2) == HIGH) {
    tone(13, t1);
    delay(len);
    noTone(13);

  }

  if (digitalRead(3) == HIGH) {
    tone(13, t2);
    delay(len);
    noTone(13);

  }
  if (digitalRead(4) == HIGH) {
    tone(13, t3);
    delay(len);
    noTone(13);

  }
  if (digitalRead(5) == HIGH) {
    tone(13, t4);
    delay(len);
    noTone(13);

  }
  if (digitalRead(6) == HIGH) {
    tone(13, t5);
    delay(len);
    noTone(13);

}
}

Change t* vars from ints to floats

Change t* vars from ints to floats


// RFID_UART.ino

#if defined (SPARK)
#include "SeeedRFID/SeeedRFID.h"
#else
#include <SoftwareSerial.h>
#include <SeeedRFID.h>
#endif

#define RFID_RX_PIN 10
#define RFID_TX_PIN 11

// #define DEBUGRFID
#define TEST

SeeedRFID RFID(RFID_RX_PIN, RFID_TX_PIN);
RFIDdata tag;

void setup() {
	Serial1.begin(9600);	//Done here to prevent SeeedRFID constructor system crash

	Serial.begin(57600);
	Serial.println("Hello, double bk!");
}

void loop() {
	if(RFID.isAvailable()){
		tag = RFID.data();
		Serial.print("RFID card number: ");
		Serial.println(RFID.cardNumber());
#ifdef TEST
	Serial.print("RFID raw data: ");
	for(int i=0; i<tag.dataLen; i++){
	    Serial.print(tag.raw[i], HEX);
	    Serial.print('\t');
		}
#endif
	}
}

// RFID_UART.ino

#if defined (PLATFORM_ID)
#include "SeeedRFID/SeeedRFID.h"
#else
#include <SoftwareSerial.h>
#include <SeeedRFID.h>
#endif

#define RFID_RX_PIN 10
#define RFID_TX_PIN 11

// #define DEBUGRFID
#define TEST

SeeedRFID RFID(RFID_RX_PIN, RFID_TX_PIN);
RFIDdata tag;

void setup() {
	Serial1.begin(9600);	//Done here to prevent SeeedRFID constructor system crash

	Serial.begin(57600);
	Serial.println("Hello, double bk!");
}

void loop() {
	if(RFID.isAvailable()){
		tag = RFID.data();
		Serial.print("RFID card number: ");
		Serial.println(RFID.cardNumber());
#ifdef TEST
	Serial.print("RFID raw data: ");
	for(int i=0; i<tag.dataLen; i++){
	    Serial.print(tag.raw[i], HEX);
	    Serial.print('\t');
		}
#endif
	}
}

Change to include Redbear Duo

Change to include Redbear Duo


#include <Homie.h>

const int TEMPERATURE_INTERVAL = 300;

unsigned long lastTemperatureSent = 0;

HomieNode temperatureNode("temperature", "temperature");

void setupHandler() {
  Homie.setNodeProperty(temperatureNode, "unit", "c", true);
}

void loopHandler() {
  if (millis() - lastTemperatureSent >= TEMPERATURE_INTERVAL * 1000UL || lastTemperatureSent == 0) {
    float temperature = 22; // Fake temperature here, for the example
    Serial.print("Temperature: ");
    Serial.print(temperature);
    Serial.println(" °C");
    if (Homie.setNodeProperty(temperatureNode, "temperature", String(temperature), true)) {
      lastTemperatureSent = millis();
    } else {
      Serial.println("Sending failed");
    }
  }
}

void setup() {
  Homie.setFirmware("awesome-temperature", "1.0.0");
  Homie.registerNode(temperatureNode);
  Homie.setSetupFunction(setupHandler);
  Homie.setLoopFunction(loopHandler);
  Homie.setup();
}

void loop() {
  Homie.loop();
}

#include <Homie.h>

const int TEMPERATURE_INTERVAL = 300;

unsigned long lastTemperatureSent = 0;

HomieNode temperatureNode("temperature", "temperature");

void setupHandler() {
  Homie.setNodeProperty(temperatureNode, "unit", "c", true);
}

void loopHandler() {
  if (millis() - lastTemperatureSent >= TEMPERATURE_INTERVAL * 1000UL || lastTemperatureSent == 0) {
    float temperature = 22; // Fake temperature here, for the example
    Serial.print("Temperature: ");
    Serial.print(temperature);
    Serial.println(" °C");
    if (Homie.setNodeProperty(temperatureNode, "degrees", String(temperature), true)) {
      lastTemperatureSent = millis();
    } else {
      Serial.println("Temperature sending failed");
    }
  }
}

void setup() {
  Homie.setFirmware("awesome-temperature", "1.0.0");
  Homie.registerNode(temperatureNode);
  Homie.setSetupFunction(setupHandler);
  Homie.setLoopFunction(loopHandler);
  Homie.setup();
}

void loop() {
  Homie.loop();
}

Update temperature example with more semantic topic


#include "brotherKH930.h"

void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}

#include "brotherKH930.h"

PinSetup pins = kniticV2Pins();
BrotherKH930 brother(pins);

void setup() {
  Serial.begin(115200);
  Serial.println("Ready.");
}

void loop() {
  Direction dir = brother.direction();
  int pos = brother.position();

  Serial.print("@");
  Serial.print(pos);
  Serial.print("  ");
  if (dir == LEFT) Serial.print("<-");
  else Serial.print("->");
  Serial.println();
}

Add main to test the position logic.

Add main to test the position logic.


#include <Arduino.h>
#include "test_cpp_wrapper.h"

void
setup(
)
{
    Serial.begin(BAUD_RATE);
    runalltests_cpp_wrapper();
}

void
loop(
)
{

}

#include <Arduino.h>
#include <SPI.h>
#include <SD.h>
#include "test_cpp_wrapper.h"

void
setup(
)
{
    SPI.begin();
    SD.begin(SD_CS_PIN);
    Serial.begin(BAUD_RATE);
    runalltests_cpp_wrapper();
}

void
loop(
)
{

}

Fix missing SD begin in C++ Wrapper test


/*
  btnLed sketch
  Push a button to turn on a LED.
  Push the button again to turn the LED off.

  *******
  Do not connect more than 5 volts directly to an Arduino pin!!
  *******
*/

#define pushbuttonPIN 2
#define onoffPIN 3

volatile int flag = LOW;
unsigned long timestamp = 0;

void setup()
{
  pinMode(onoffPIN, OUTPUT);       // An LED to signal on or off state
  attachInterrupt(0, interrupt, HIGH); // Interrupt when button is pressed
}

void interrupt()
{
  // Only change the flag if more than 1000 ms has passed since previous IRQ
  // to handle debouncing-effect.
  if ( (unsigned long)(millis() - timestamp) > 1000 )
  {
    flag = !flag;
    timestamp = millis();
  }
}

void loop()
{
  digitalWrite(onoffPIN, flag);
}

/*
  btnLed sketch
  Push a button to turn on a LED.
  Push the button again to turn the LED off.

  *******
  Do not connect more than 5 volts directly to an Arduino pin!!
  *******
*/

#define pushbuttonPIN 2
#define onoffLED 3

volatile int flag = LOW;
unsigned long timestamp = 0;

void setup()
{
  pinMode(onoffLED, OUTPUT);       // An LED to signal on or off state
  attachInterrupt(0, interrupt, HIGH); // Interrupt when button is pressed
}

void interrupt()
{
  // Only change the flag if more than 1000 ms has passed since previous IRQ
  // to handle debouncing-effect.
  if ( (unsigned long)(millis() - timestamp) > 1000 )
  {
    flag = !flag;
    timestamp = millis();
  }
}

void loop()
{
  digitalWrite(onoffLED, flag);
}

Use LED iso PIN to avoid confusion

Use LED iso PIN to avoid confusion


/*
  ArcFour Entropy Seeding Demo

  created 10 Jun 2014
  by Pascal de Bruijn

 */

#include <Entropy.h>
#include <ArcFour.h>

ArcFour ArcFour;

int ledPin = 13;

void setup()
{
  Serial.begin(9600);
  while (!Serial)
  {
    ; // wait for serial port to connect. Needed for Leonardo and Due
  }

  Entropy.Initialize();

  ArcFour.initialize();

  for (int i = 0; i < ARCFOUR_MAX; i++)
  {
    if (i / 4 % 2)
      digitalWrite(ledPin, LOW);
    else
      digitalWrite(ledPin, HIGH);

    ArcFour.seed(i, Entropy.random(WDT_RETURN_BYTE));
  }

  ArcFour.finalize();

  for (int i = 0; i < ARCFOUR_MAX; i++)
  {
    ArcFour.random();
  }

  digitalWrite(ledPin, HIGH);
}

void loop()
{
  Serial.println(ArcFour.random());
  delay(1000);
}

/*
  ArcFour Entropy Seeding Demo

  created 10 Jun 2014
  by Pascal de Bruijn

 */

#include <Entropy.h>
#include <ArcFour.h>

ArcFour ArcFour;

int ledPin = 13;

void setup()
{
  Serial.begin(9600);
  while (!Serial)
  {
    ; // wait for serial port to connect. Needed for Leonardo and Due
  }

  Entropy.initialize();

  ArcFour.initialize();

  for (int i = 0; i < ARCFOUR_MAX; i++)
  {
    if (i / 4 % 2)
      digitalWrite(ledPin, LOW);
    else
      digitalWrite(ledPin, HIGH);

    ArcFour.seed(i, Entropy.random(WDT_RETURN_BYTE));
  }

  ArcFour.finalize();

  for (int i = 0; i < ARCFOUR_MAX; i++)
  {
    ArcFour.random();
  }

  digitalWrite(ledPin, HIGH);
}

void loop()
{
  Serial.println(ArcFour.random());
  delay(1000);
}

Update for new Entropy API

Update for new Entropy API


// This program allows the Spark to act as a relay
// between a terminal program on a PC and the
// Fingerprint sensor connected to RX/TX (Serial1)
// on the Spark

void setup() {
  // initialize both serial ports:
  Serial.begin(57600);
  Serial1.begin(57600);
}

void loop() {
  // read from Serial1 (Fingerprint reader), send to Serial (USB to PC)
  if (Serial1.available()) {
    int inByte = Serial1.read();
    Serial.write(inByte);
  }

  // read from Serial (USB to PC), send to Serial1 (Fingerprint reader)
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial1.write(inByte);
  }
}

// This program allows the Spark to act as a relay
// between a terminal program on a PC and the
// Fingerprint sensor connected to RX/TX (Serial1)
// on the Spark

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
  Serial1.begin(57600);

}

void loop() // run over and over
{
  while (Serial1.available())
    Serial.write(Serial1.read());

  while (Serial.available())
    Serial1.write(Serial.read());
}

Update to tested and working code

Update to tested and working code


#include "CurieImu.h"

int16_t ax, ay, az;

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

  CurieImu.initialize();

  if (!CurieImu.testConnection()) {
    Serial.println("CurieImu connection failed");
  }

  CurieImu.setFullScaleAccelRange(BMI160_ACCEL_RANGE_8G);
}

void loop() {
  CurieImu.getAcceleration(&ax, &ay, &az);
  Serial.print(ax);
  Serial.print("\t");
  Serial.print(ay);
  Serial.print("\t");
  Serial.print(az);
  Serial.println();
}

#include "CurieIMU.h"

int ax, ay, az;

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

  CurieIMU.begin();

  if (!CurieIMU.testConnection()) {
    Serial.println("CurieImu connection failed");
  }

  CurieIMU.setAccelerometerRange(8);
}

void loop() {
  CurieIMU.readAccelerometer(ax, ay, az);
  Serial.print(ax);
  Serial.print("\t");
  Serial.print(ay);
  Serial.print("\t");
  Serial.print(az);
  Serial.println();
}

Use Arduino101 CurieIMU new APIs.

Use Arduino101 CurieIMU new APIs.


#include <Arduino.h>

#include "config.h"
#include <DcMotor.h>

DcMotor xMotor(X_AXIS_PWM, X_AXIS_FWD, X_AXIS_REV),
  yMotor(Y_AXIS_PWM, Y_AXIS_FWD, Y_AXIS_REV),
  zMotor(Z_AXIS_PWM, Z_AXIS_FWD, Z_AXIS_REV);

void setup() {
  Serial.begin(BAUDRATE);
  xMotor.begin();
  yMotor.begin();
  zMotor.begin();
}

void loop() {
}

#include <Arduino.h>

#include "config.h"
#include <DcMotor.h>

DcMotor xMotor(X_AXIS_PWM, X_AXIS_FWD, X_AXIS_REV);
DcMotor yMotor(Y_AXIS_PWM, Y_AXIS_FWD, Y_AXIS_REV);
DcMotor zMotor(Z_AXIS_PWM, Z_AXIS_FWD, Z_AXIS_REV);

void setup() {
  Serial.begin(BAUDRATE);
  xMotor.begin();
  yMotor.begin();
  zMotor.begin();
}

void loop() {
}

Split motor definitions into multiple lines


// RFID_UART.ino

#if defined (SPARK)
#include "SeeedRFID/SeeedRFID.h"
#else
#include <SoftwareSerial.h>
#include <SeeedRFID.h>
#endif

#define RFID_RX_PIN 10
#define RFID_TX_PIN 11

// #define DEBUG
#define TEST

SeeedRFID RFID(RFID_RX_PIN, RFID_TX_PIN);
RFIDdata tag;

void setup() {
	Serial.begin(57600);
	Serial.println("Hello, double bk!");
}

void loop() {
	if(RFID.isAvailable()){
		tag = RFID.data();
		Serial.print("RFID card number: ");
		Serial.println(RFID.cardNumber());
#ifdef TEST
	Serial.print("RFID raw data: ");
	for(int i=0; i<tag.dataLen; i++){
	    Serial.print(tag.raw[i], HEX);
	    Serial.print('\t');
		}
#endif
	}
}

// RFID_UART.ino

#if defined (SPARK)
#include "SeeedRFID/SeeedRFID.h"
#else
#include <SoftwareSerial.h>
#include <SeeedRFID.h>
#endif

#define RFID_RX_PIN 10
#define RFID_TX_PIN 11

// #define DEBUG
#define TEST

SeeedRFID RFID(RFID_RX_PIN, RFID_TX_PIN);
RFIDdata tag;

void setup() {
	Serial1.begin(9600);	//Done here to prevent SeeedRFID constructor system crash

	Serial.begin(57600);
	Serial.println("Hello, double bk!");
}

void loop() {
	if(RFID.isAvailable()){
		tag = RFID.data();
		Serial.print("RFID card number: ");
		Serial.println(RFID.cardNumber());
#ifdef TEST
	Serial.print("RFID raw data: ");
	for(int i=0; i<tag.dataLen; i++){
	    Serial.print(tag.raw[i], HEX);
	    Serial.print('\t');
		}
#endif
	}
}

Update for Particle Core and Photon

Update for Particle Core and Photon


#include <Smartcar.h>

const int TRIGGER_PIN = 6; //D6
const int ECHO_PIN = 7; //D7
SR04 front(TRIGGER_PIN, ECHO_PIN, 10);

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

void loop() {
  Serial.println(front.getDistance());
  delay(100);
}

#include <Smartcar.h>

const int TRIGGER_PIN = 6; //D6
const int ECHO_PIN = 7; //D7
const unsigned int MAX_DISTANCE = 100;
SR04 front(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

void loop() {
  Serial.println(front.getDistance());
  delay(100);
}

Adjust max sensor distance to something more suitable


#include <SoftwareSerial.h>

// Serial speed
#define SERIAL_BAUDRATE 9600
#define LIGHTSENSOR_PIN 3

#define FETCH_INTERVAL 100
#define POST_INTERVAL 5000

const int numLedSamples = POST_INTERVAL / FETCH_INTERVAL;
int ledSamples[numLedSamples];
int ledSampleCounter = 0;

int light = 0;

// Software serial for XBee module
SoftwareSerial xbeeSerial(2, 3); // RX, TX

void setup() {
  Serial.begin(SERIAL_BAUDRATE);
  xbeeSerial.begin(SERIAL_BAUDRATE);
}

void loop() {
  readLightsensor();

  if (ledSampleCounter >= numLedSamples)
    sendLightData();

  delay(FETCH_INTERVAL);
}

void readLightsensor() {
  int sample = analogRead(LIGHTSENSOR_PIN);
  Serial.print("d:");Serial.println(sample);
  ledSamples[ledSampleCounter] = sample;
  ledSampleCounter++;
}

void sendLightData() {
  float avg = 0.0f;

  for (int i = 0; i < numLedSamples; i++)
    avg += ledSamples[i];

  avg /= numLedSamples;

  xbeeSerial.print("l=");xbeeSerial.println(avg);
  ledSampleCounter = 0;
}

#include <SoftwareSerial.h>

// Serial speed
#define SERIAL_BAUDRATE 9600
#define LIGHTSENSOR_PIN 3

#define FETCH_INTERVAL 100
#define POST_INTERVAL 5000

const int numLedSamples = POST_INTERVAL / FETCH_INTERVAL;
int ledSamples[numLedSamples];
int ledSampleCounter = 0;

int light = 0;

// Software serial for XBee module
SoftwareSerial xbeeSerial(2, 3); // RX, TX

void setup() {
  Serial.begin(SERIAL_BAUDRATE);
  xbeeSerial.begin(SERIAL_BAUDRATE);
}

void loop() {
  readLightsensor();

  if (ledSampleCounter >= numLedSamples)
    sendLightData();

  delay(FETCH_INTERVAL);
}

void readLightsensor() {
  ledSamples[ledSampleCounter] = analogRead(LIGHTSENSOR_PIN);
  ledSampleCounter++;
  ledSampleCounter %= numLedSamples;
}

void sendLightData() {
  float avg = 0.0f;

  for (int i = 0; i < numLedSamples; i++)
    avg += ledSamples[i];

  avg /= numLedSamples;

  xbeeSerial.print("l=");xbeeSerial.println(avg);
}

Implement LED data as ringbuffer.

[LedDude] Implement LED data as ringbuffer.

Signed-off-by: Juri Berlanda <5bfdca9e82c53adb0603ce7083f4ba4f2da5cacf@hotmail.com>


#include <MIDI.h>

#define PIN_KEY_IN   2
#define PIN_MIDI_OUT 3

MIDI_CREATE_DEFAULT_INSTANCE();

void setup()
{
    pinMode(PIN_KEY_IN, INPUT);
    pinMode(PIN_MIDI_OUT, OUTPUT);

    MIDI.begin();
}

void loop()
{
    // Read digital value from piano key
    int in_value = digitalRead(PIN_KEY_IN);

    // Output a tone if key was pressed
    if (in_value == HIGH) {
        MIDI.sendNoteOn(40, 127, 1);      // Note 40 (E3), velocity 127, channel 1
    }

    // TODO: Come up with a way to choose which note to play based on which key
    // is being pressed.
}

Add main MIDI controller sketch

Add main MIDI controller sketch


/******************************************************************
Example starting point sketch for ParticleIoT library

This example contains no devices.
It is provided for comparison with other example sketches.

http://www.github.com/rlisle/ParticleIoT

Written by Ron Lisle

BSD license, check LICENSE for more information.
All text above must be included in any redistribution.

Changelog:
2017-03-11: Initial creation
******************************************************************/

/****************/
/*** INCLUDES ***/
/****************/
#include <IoT.h>

/*****************/
/*** VARIABLES ***/
/*****************/
IoT *iot;

/*************/
/*** SETUP ***/
/*************/
void setup() {
    iot = IoT::getInstance();
    iot->setControllerName("lislerv");
    iot->setPublishName("RonTest");
    iot->begin();
}

/************/
/*** LOOP ***/
/************/
void loop() {
    long currentMillis = millis();
    iot->loop(currentMillis);
}

Add example with no devices

Add example with no devices


#include <G35String.h>

//#define TWO_STRINGS

#ifdef TWO_STRINGS
  #define LIGHT_COUNT 50
  #define G35_PIN1 9
  #define G35_PIN2 10
  G35String lights1(G35_PIN1, LIGHT_COUNT);
  G35String lights2(G35_PIN2, LIGHT_COUNT);
  const int middle = 0;
#else
  #define LIGHT_COUNT 49
  #define G35_PIN 9
  G35String lights(G35_PIN, LIGHT_COUNT);
  const int middle = LIGHT_COUNT/2;
#endif

// Simple function to get amount of RAM free
int freeRam () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

// Colour table for rainbow
const int COLOURS[] = {COLOR_BLUE, COLOR_RED, COLOR_ORANGE, COLOR_YELLOW, COLOR_GREEN};
const int NCOLOURS = sizeof(COLOURS)/sizeof(int);

// Counter - to insert a long pause, occasionally
int pause = 0;

// Width of half a string
const float width = (float) LIGHT_COUNT/2.0;

// 2*pi, roughly
const float twoPi = 6.283185;

// pre-compute 2*pi/(half of LIGHT_COUNT)
const float mul = 2.0*twoPi/(float) LIGHT_COUNT;

int getIntensity(const int bulb, const int centre) {
  float x = mul * (float) (bulb-centre);
  return int(G35::MAX_INTENSITY*(0.95*abs(sin(x))+0.05));
}

void setup() {
  Serial.begin (115200);
  Serial.println(freeRam());
#ifdef TWO_STRINGS
  lights1.enumerate();
  lights2.enumerate();
#else
  lights.enumerate();
#endif
}

void loop() {
  int offset = 0;
  for (int colIndex=0; colIndex<NCOLOURS; colIndex++) {
    int colour = COLOURS[colIndex];
    for (int repeat=0; repeat < 250; repeat++) {
      // Update all bulbs
      #ifdef TWO_STRINGS
      for (int bulb=0; bulb < LIGHT_COUNT; bulb++) {
      #else
      for (int bulb=0; bulb <= LIGHT_COUNT/2; bulb++) {
      #endif
        int intensity = getIntensity(bulb,middle+offset);
        #ifdef TWO_STRINGS
          lights1.set_color(bulb, intensity, colour);
          lights2.set_color(bulb, intensity, colour);
        #else
          lights.set_color(middle+bulb, intensity, colour);
          lights.set_color(middle-bulb, intensity, colour);
        #endif
      }
      delay(100);
      offset++;
    }
  }
}

Add a sort of intensity wave option

Add a sort of intensity wave option


#include "AES.h"
#include "CBC.h"

#define CHAIN_SIZE 2
#define BLOCK_SIZE 16
#define SAMPLE_SIZE (BLOCK_SIZE * CHAIN_SIZE)

byte key[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                    0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};

CBC<AES128> cbc;

byte sourcePool[SAMPLE_SIZE];

void setup()
{
  Serial.begin(115200);
  //Set B pins to input
  DDRB = B00000000;
  delay(1000);

}

void loop() {
  static byte currentByte = 0x00;
  byte pinVal = (PINB >> 3) & B00000001;
  boolean byteReady = collectBit(pinVal, &currentByte);

  if (byteReady){
    //Serial.println("ByteCollected");
    boolean poolFull = collectByte(currentByte);
    if (poolFull){
      conditionPool();
      //Serial.write(sourcePool, SAMPLE_SIZE);
    }
    currentByte = 0;
  }
}

//@return true if byte is full/complete
boolean collectBit(byte inputBit, byte *currentByte){
  static int bitCounter = 0;
  *currentByte |= inputBit << bitCounter;
   bitCounter = ++bitCounter % 8;

  if (bitCounter == 0) {
    return true;
  }
  return false;
}

//@return true if sourcePool is full
boolean collectByte(byte currentByte){
  static int byteCount = 0;
  sourcePool[byteCount] = currentByte;
  byteCount = ++byteCount % SAMPLE_SIZE;
  //Serial.println(byteCount);

  if (byteCount == 0){
    return true;
  }
  return false;
}

 //TODO: this should return encrypted pool, and mac should
 //be sent in the calling function
void conditionPool(){
  //Serial.println("Conditioning");
  static byte iv[BLOCK_SIZE] = {0};
  byte output[SAMPLE_SIZE];
  cbc.clear();
  cbc.setKey(key, 16);
  cbc.setIV(iv, 16);
  cbc.encrypt(output, sourcePool, SAMPLE_SIZE);

   //advance pointer to last block (the MAC)
  byte *outBuf = &output[SAMPLE_SIZE - BLOCK_SIZE];
  Serial.write(outBuf, BLOCK_SIZE);
}

Add v0.2.0 conditioning Arduino source

Add v0.2.0 conditioning Arduino source


#include <Wire.h>
#include <Adafruit_BMP085.h>

/***************************************************
  This is an example for the BMP085 Barometric Pressure & Temp Sensor

  Designed specifically to work with the Adafruit BMP085 Breakout
  ----> https://www.adafruit.com/products/391

  These displays use I2C to communicate, 2 pins are required to
  interface
  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ****************************************************/

// Connect VCC of the BMP085 sensor to 3.3V (NOT 5.0V!)
// Connect GND to Ground
// Connect SCL to i2c clock - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 5
// Connect SDA to i2c data - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 4
// EOC is not used, it signifies an end of conversion
// XCLR is a reset pin, also not used here

Adafruit_BMP085 bmp;

void setup() {
  Serial.begin(9600);
  if (!bmp.begin()) {
	Serial.println("Could not find a valid BMP085 sensor, check wiring!");
	while (1) {}
  }
}

void loop() {
    Serial.print("Temperature = ");
    Serial.print(bmp.readTemperature());
    Serial.println(" *C");

    Serial.print("Pressure = ");
    Serial.print(bmp.readPressure());
    Serial.println(" Pa");

    // Calculate altitude assuming 'standard' barometric
    // pressure of 1013.25 millibar = 101325 Pascal
    Serial.print("Altitude = ");
    Serial.print(bmp.readAltitude());
    Serial.println(" meters");

    Serial.print("Pressure at sealevel (calculated) = ");
    Serial.print(bmp.readSealevelPressure());
    Serial.println(" Pa");

  // you can get a more precise measurement of altitude
  // if you know the current sea level pressure which will
  // vary with weather and such. If it is 1015 millibars
  // that is equal to 101500 Pascals.
    Serial.print("Real altitude = ");
    Serial.print(bmp.readAltitude(101500));
    Serial.println(" meters");

    Serial.println();
    delay(500);
}

Add boilerplate .ino to implement the baro sensor


#include <Arduino.h>
#include <SPI.h>
#if not defined (_VARIANT_ARDUINO_DUE_X_) && not defined (_VARIANT_ARDUINO_ZERO_)
  #include <SoftwareSerial.h>
#endif

#include "Adafruit_BLE.h"
#include "Adafruit_BluefruitLE_SPI.h"
#include "Adafruit_BluefruitLE_UART.h"

#include "BluefruitConfig.h"

static const int PIN = 5;

Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);

void setup() {
  pinMode(PIN, OUTPUT);
  boolean debug = false;
  ble.begin(debug);
  ble.echo(false);
  while (!ble.isConnected()) {
    delay(500);
  }
  ble.setMode(BLUEFRUIT_MODE_DATA);
  digitalWrite(PIN, HIGH);
}

// note that Bluefruit LE client adds NL when SEND button is pressed
void loop() {
  if (ble.available()) {
    int c = ble.read();
    if (c != -1 && c != 0x0A) {
      digitalWrite(PIN, (char)c == 'a' ? HIGH : LOW);
    }
  }
}

Add sample for simple bluetooth data.

Add sample for simple bluetooth data.


#include <Servo.h>

int fricken_laser = 7;
Servo s1;
Servo s2;

// for printf
int my_putc(char c, FILE *t)
{
    Serial.write(c);
}

void setup()
{
    fdevopen(&my_putc, 0);
    Serial.begin(57600);
    Serial.setTimeout(1000);
    s2.attach(3);
    s1.attach(9);
    pinMode(fricken_laser, OUTPUT);
}

void loop()
{
    char buf[10];
    int num_read = 0;
    memset(buf,0,sizeof(buf));
    num_read = Serial.readBytesUntil('\n',buf,10);
    if (num_read == 10)
    {
        int pos1 = 0;
        int pos2 = 0;
        int laser_on = 0;
        sscanf(buf,"%d,%d,%d\n",&pos1,&pos2,&laser_on);
        s1.write(pos1);
        s2.write(pos2);
        digitalWrite(fricken_laser,laser_on ? LOW : HIGH);
        printf("p1: %d p2: %d laser: %d\n",pos1,pos2,laser_on);
    }
}

// samples datas
// 100,100,1

// 150,100,0

Add arduino code to run interface to robot.


/*

 This Sketch will update the firmware of the CC3000 to
 a version that works with this library.
 The fimware update takes about 10. If the upgrade is successfull
 the RED and GREEN LEDs will flash.

 Circuit:
 * WiFi BoosterPack

 Created: October 24, 2013 by Robert Wessels (http://energia.nu)
 */

#include <SPI.h>
#include <WiFi.h>

void setup() {
  Serial.begin(115200);
  // Gives you time to open the Serial monitor
  delay(5000);

  // Initialize the LEDs and turn them OFF
  pinMode(RED_LED, OUTPUT);
  pinMode(GREEN_LED, OUTPUT);
  digitalWrite(RED_LED, LOW);
  digitalWrite(GREEN_LED, LOW);

  // Set the CC3000 pins
  WiFi.setCSpin(18);  // 18: P2_2 @ F5529, PE_0 @ LM4F/TM4C
  WiFi.setENpin(2);   //  2: P6_5 @ F5529, PB_5 @ LM4F/TM4C
  WiFi.setIRQpin(19); // 19: P2_0 @ F5529, PB_2 @ LM4F/TM4C

  Serial.println("Updating CC3000 Firmware");
  Serial.println("RED and GREEN LED's will flash when complete");

  // Initialize the CC3000
  WiFi.begin();

  // Begin firmware update
  WiFi.updateFirmware();

  Serial.println("Firmware update success :-)");

  // Print the new firmware version
  printFirmwareVersion();
}

uint8_t state = 0;

void loop() {
  state = !state;
  digitalWrite(RED_LED, state);
  digitalWrite(GREEN_LED, !state);
  delay(500);
}

void printFirmwareVersion() {
  uint8_t *ver = WiFi.firmwareVersion();
  Serial.print("Version: ");
  Serial.print(ver[0]);
  Serial.print(".");
  Serial.println(ver[1]);
}

Add CC3000 Firmware update Sketch

Add CC3000 Firmware update Sketch


#include <Bridge.h>
#include <BridgeClient.h>

#include "Arduino-Websocket/WebSocketClient.h"

#include "vor_utils.h"
#include "vor_env.h"
#include "vor_led.h"
#include "vor_motion.h"
#include "vor_methane.h"

#define MAX_ATTEMPTS 10
#define INTERVAL 30000
#define HEARTBEAT_INTERVAL 25000

#define MOTION_PIN 2
#define METHANE_PIN A0

#define MESSAGE_FORMAT "42[\"message\",{\"id\":\"toilet8am\",\"type\":\"toilet\",\"reserved\":%s,\"methane\":%s}]"

BridgeClient client;
WebSocketClient ws(SERVER_URL);

VorLed led;
VorMotion motion(MOTION_PIN);
VorMethane methane(METHANE_PIN);

int prevMotionValue = HIGH;

uint64_t heartbeatTimestamp = 0;
uint64_t intervalTimestamp = 0;

uint8_t attempts = 0;
bool wifiRestarted = false;
bool lininoRebooted = false;

void setup() {
    Serial.begin(115200);
    bridge();
}

void loop() {
    if (client.connected()) {
        uint64_t now = millis();
        int motionValue = motion.read();
        float methaneValue = methane.readProcessed();
        bool change = prevMotionValue != motionValue;
        prevMotionValue = motionValue;
        bool reservedValue = motionValue == LOW;
        if (change || now - intervalTimestamp > INTERVAL) {
            intervalTimestamp = now;

            const char* reserved = reservedValue ? "true" : "false";
            char methane[8];
            dtostrf(methaneValue, 8, 2, methane);
            char message[128];
            sprintf(message, MESSAGE_FORMAT, reserved, methane);
            ws.sendData(message);
        }
        if ((now - heartbeatTimestamp) > HEARTBEAT_INTERVAL) {
            heartbeatTimestamp = now;
            ws.sendData("2");
            // TODO: check server response
        }
    } else {
        led.turnOn();
        Serial.println(0);
        if (!client.connect(SERVER_URL, SERVER_PORT)) {
            if (!wifiRestarted) {
                writeLog("Restarting Wi-Fi");
                connectToWifi(WIFI_SSID, WIFI_ENCRYPTION, WIFI_PASSWORD);
                delay(60000);
                wifiRestarted = true;
            } else if (!lininoRebooted) {
                writeLog("Rebooting Linino");
                resetAndRebootLinino();
                bridge();
                lininoRebooted = true;
            } else {
                writeLog("Resetting Arduino");
                resetArduino();
            }
        } else {
            wifiRestarted = false;
            lininoRebooted = false;
            if (ws.handshake(client)) {
                ws.sendData("5");
                // TODO: check server response
                led.turnOff();
            }
        }
    }
}

void bridge() {
    led.turnOn();
    delay(60000); // wait until linino has booted
    Bridge.begin();
    led.turnOff();
}

Add test sketch (to be removed).

Add test sketch (to be removed).


/*
 * Temperature Sensor Displayed on 4 Digit 7 segment common anode
 * Created by Rui Santos, http://randomnerdtutorials.com
*/

const int digitPins[4] = {
  4,5,6,7};                 //4 common anode pins of the display
const int clockPin = 11;    //74HC595 Pin 11
const int latchPin = 12;    //74HC595 Pin 12
const int dataPin = 13;     //74HC595 Pin 14
const int tempPin = A0;     //temperature sensor pin
const byte digit[10] =      //seven segment digits in bits
{
  B00111111, //0
  B00000110, //1
  B01011011, //2
  B01001111, //3
  B01100110, //4
  B01101101, //5
  B01111101, //6
  B00000111, //7
  B01111111, //8
  B01101111  //9
};
int digitBuffer[4] = {
  0};
int digitScan = 0;

void setup(){
  for(int i=0;i<4;i++)
  {
    pinMode(digitPins[i],OUTPUT);
  }
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

//writes the temperature on display
void updateDisp(){
  for(byte j=0; j<4; j++)
    digitalWrite(digitPins[j], LOW);

  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, B11111111);
  digitalWrite(latchPin, HIGH);

  delayMicroseconds(100);
  digitalWrite(digitPins[digitScan], HIGH);

  digitalWrite(latchPin, LOW);
  if(digitScan==2)
    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B10000000)); //print the decimal point on the 3rd digit
  else
    shiftOut(dataPin, clockPin, MSBFIRST, ~digit[digitBuffer[digitScan]]);

  digitalWrite(latchPin, HIGH);
  digitScan++;
  if(digitScan>3) digitScan=0;
}

void loop(){
  digitBuffer[3] = 2;
  digitBuffer[2] = 2;
  digitBuffer[1] = 2;
  digitBuffer[0] = 2;
  updateDisp();
  delay(2);
}

Backup of Working Slave Code

Backup of Working Slave Code


#include <SoftWire.h>
#include <AsyncDelay.h>

SoftWire sw(SDA, SCL);

void setup(void)
{
  Serial.begin(9600);
  sw.setTimeout_ms(40);
  sw.begin();

  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

  // Set how long we are willing to wait for a device to respond
  sw.setTimeout_ms(200);

  const uint8_t firstAddr = 1;
  const uint8_t lastAddr = 0x7F;
  Serial.println();
  Serial.print("Interrogating all addresses in range 0x");
  Serial.print(firstAddr, HEX);
  Serial.print(" - 0x");
  Serial.print(lastAddr, HEX);
  Serial.println(" (inclusive) ...");

  for (uint8_t addr = firstAddr; addr <= lastAddr; addr++) {
    digitalWrite(LED_BUILTIN, HIGH);
    delayMicroseconds(10);

    uint8_t startResult = sw.llStart((addr << 1) + 1); // Signal a read
    sw.stop();

    if (startResult == 0) {
      Serial.print("\rDevice found at 0x");
      Serial.println(addr, HEX);
      Serial.flush();
    }
    digitalWrite(LED_BUILTIN, LOW);

    delay(50);
  }
  Serial.println("Finished");

}

void loop(void)
{
  ;
}

Add example to list all addresses where a device is present.


#include <Wire.h>
#include "Adafruit_BMP085.h"

/*
 * BMP180 setup instructions:
 * ----------------------------------------
 * Connect BMP180 V-in   to 3.3V (NOT 5.0V)
 * Connect BMP180 GND    to Ground
 * Connect BMP180 SCL    to Analog 5
 * Connect BMP180 SDA    to Analog 4
 * ----------------------------------------
*/

Adafruit_BMP085 barometer;

void setup() {
  Serial.begin(9600); // 9600 bits/second
  if (!barometer.begin()) {
  	Serial.println("No BMP085 sensor found.");
  	while (1) { /* Trap the thread. */ }
  }
}

void printBaroData() {

    // Get temperature.
    Serial.print("Temperature = ");
    Serial.print(barometer.readTemperature());
    Serial.println(" *C");

    // Get pressure at sensor.
    Serial.print("Pressure = ");
    Serial.print(barometer.readPressure());
    Serial.println(" Pa");

    // Calculate pressure at 0 MSL. (0 meters mean sea-level)
    Serial.print("Calculated pressure at 0 MSL = ");
    Serial.print(barometer.readSealevelPressure());
    Serial.println(" Pa");

    // Get pressure altitude:
    // altitude with (default) altimeter setting at 101325 Pascals == 1013.25 millibars
    // == 29.92 inches mercury (i.e., std. pressure)
    Serial.print("Pressure altitude = ");
    Serial.print(barometer.readAltitude());
    Serial.println(" meters");

    // TODO:
    // Density altitude: pressure altitude corrected for nonstandard temperature
    // High density altitude (High, Hot, and Humid) means decreased performance.

    // Get indicated altitude:
    // pressure altitude corrected for non-standard pressure, with altimeter
    // setting 1015 millibars == 101500 Pascals
    // For pressure conversions, visit NOAA at: https://www.weather.gov/media/epz/wxcalc/pressureConversion.pdf.
    Serial.print("Indicated altitude = ");
    Serial.print(barometer.readAltitude(101500));
    Serial.println(" meters");

    Serial.println();
}
void loop() {
    printBaroData();
    delay(350);
}

Add new starting payload program

Add new starting payload program


/*
  Yún HTTP Client

 This example for the Arduino Yún shows how create a basic
 HTTP client that connects to the internet and downloads
 content. In this case, you'll connect to the Arduino
 website and download a version of the logo as ASCII text.

 created by Tom igoe
 May 2013

 This example code is in the public domain.

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

 */

#include <Bridge.h>
#include <HttpClient.h>

const char* msg = "{\"id\":\"1\",\"type\":\"room\",\"reserved\":false,\"temperature\":10,\"light\":10,\"dioxide\":10,\"noise\":10}";

void setup() {
  // Bridge takes about two seconds to start up
  // it can be helpful to use the on-board LED
  // as an indicator for when it has initialized
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  Bridge.begin();
  digitalWrite(13, HIGH);

  Serial.begin(9600);

  while (!Serial); // wait for a serial connection
}

void loop() {
  // Initialize the client library
  HttpClient client;
  client.setHeader("Content-Type: text/plain");
  // Make a HTTP request:
  client.post("rubix.futurice.com/messages", msg);

  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.print(c);
  }
  Serial.flush();

  delay(5000);
}

Add HTTP POST for Arduino Yun.

Add HTTP POST for Arduino Yun.


#include <OneWire.h>
#include <EEPROM.h>

// This is the pin with the 1-Wire bus on it
OneWire ds(PIN_D0);

// unique serial number read from the key
byte addr[8];

// poll delay (I think 750ms is a magic number for iButton)
int del = 1000;

// Teensy 2.0 has an LED on port 11
int ledpin = 11;

// number of values stored in EEPROM
byte n = 0;

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

  // wait for serial
  pinMode(ledpin, OUTPUT);
  digitalWrite(ledpin, HIGH);
  while (!Serial.dtr()) {};
  digitalWrite(ledpin, LOW);

  // Dump EEPROM to serial
  n = EEPROM.read(0);
  Serial.print(n, DEC); Serial.println(" keys stored:");

  int i, j;
  for(i=0; i<n; i++) {
    for(j=0; j<8; j++) {
      Serial.print(EEPROM.read(1 + (8 * i) + j), HEX);
      Serial.print(" ");
    }
    Serial.println("");
  }
}

void loop() {
  byte result;

  // search looks through all devices on the bus
  ds.reset_search();

  if(result = !ds.search(addr)) {
    // Serial.println("Scanning...");
  } else if(OneWire::crc8(addr, 7) != addr[7]) {
    Serial.println("Invalid CRC");
    delay(del);
    return;
  } else {
    EEPROM.write(0, n++);
    Serial.print("Storing key "); Serial.println(n, DEC);
    for(byte i=0; i<8; i++) {
      Serial.print(addr[i], HEX);
      EEPROM.write(1 + (8 * n) + i, addr[i]);
      Serial.print(" ");
    }
    Serial.print("\n");
    digitalWrite(ledpin, HIGH);
    delay(1000);
    digitalWrite(ledpin, LOW);
  }

  delay(del);
  return;
}

Add the Arduino sketch for reading and remembering key numbers. Doesn't build with ino atm.


/****************************************************************************
   PIRsensor : test program for PIR sensor module

   Author: Enrico Formenti
   Permissions: MIT licence

   Remarks:
    - OUT pin is connected to digital pin 2 of Arduino, change this if needed
    - DELAY times depend on the type of module and/or its configuration.
*****************************************************************************/

#include <Serial.h>
#include <PIR.h>

// OUT pin on PIR sensor connected to digital pin 2
// (any other digital pin will do, just change the value below)
#define PIRSensorPin 2

PIR myPIR(PIRSensorPin);

void setup() {
  myPIR.begin();
}

void loop() {

  if(myPIR.getStatus()) {
    Serial.println("Movement detected");

    // do something else at least for the delay between two seccessive
    // readings
    delay(myPIR.getDurationDelay());
  }
  else
    Serial.println("Nothing being detected...");
}

Test program for PIR module

Test program for PIR module


/***************************************************
  Simple serial server
****************************************************/

//serial
String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete

void setup(){
  //delay(100); //wait for bus to stabalise
  // serial
  Serial.begin(9600);
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
}

void loop(){
  // print the string when a newline arrives:
  if (stringComplete) {
    Serial.println(inputString);
    // clear the string:
    inputString = "";
    stringComplete = false;
  }
}

/*
 SerialEvent occurs whenever a new data comes in the
 hardware serial RX.  This routine is run between each
 time loop() runs, so using delay inside loop can delay
 response.  Multiple bytes of data may be available.
 */
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

Add arduino code to work with the serial_test


/**
 * Copyright (c) 2019, Łukasz Marcin Podkalicki <lpodkalicki@gmail.com>
 * ArduinoUno/001
 * Blinky with timer1 OVF.
 */

#define LED_PIN     (13)
#define TIMER_TCNT  (57723) // 65536 - 16MHz/1024/2

void setup() {
  pinMode(LED_PIN, OUTPUT); // set LED pin as output
  TCCR1A = 0;
  TCCR1B = _BV(CS12)|_BV(CS10); // set Timer1 prescaler to 1024
  TIMSK1 |= _BV(TOIE1); // enable Timer1 overflow interrupt
  TCNT1 = TIMER_TCNT; // reload timer counter
}

void loop() {
  // do nothing
}

ISR(TIMER1_OVF_vect) {
  TCNT1 = TIMER_TCNT; // reload timer counter
  digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle LED pin
}

Add next Arduino example - blinky with Timer1 OVF.


"""
@author:     Sze 'Ron' Chau
@source:     https://github.com/wodiesan/senior_design_spring
@Desc:       Adafruit Analog Light Sensor, modified by Ron Chau.

 1. Connect sensor output to Analog Pin 0
 2. Connect 5v to VCC and GND to GND
 3. Connect 3.3v to the AREF pin
"""

int led1 = 2;          // LED connected to digital pin 2
int led2 = 3;          // LED connected to digital pin 3
int led3 = 4;          // LED connected to digital pin 4
int sensorPin = A0;    // select the input pin for the potentiometer

float rawRange = 1024; // 3.3v
float logRange = 5.0; // 3.3v = 10^5 lux

// Random value chosen to test light sensing feature.
float lightLimit = 600;

void setup()
{
  analogReference(EXTERNAL); //
  Serial.begin(9600);
  Serial.println("Adafruit Analog Light Sensor Test");

  //LEF pins
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
}

void loop()
{
  // read the raw value from the sensor:
  int rawValue = analogRead(sensorPin);
  Serial.print("Raw = ");
  Serial.print(rawValue);
  Serial.print(" - Lux = ");

  Serial.println(RawToLux(rawValue));

  // LEDS on if rawValue greater or equal.
  if(rawValue <= 400){
    digitalWrite(led1, HIGH);   // LED on
    digitalWrite(led2, HIGH);
    digitalWrite(led3, HIGH);
  }
  else{
    digitalWrite(led1, LOW);   // LEDs off
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
  }
  delay(1000);

}

float RawToLux(int raw)
{
  float logLux = raw * logRange / rawRange;
  return pow(10, logLux);
}

Add basic GA1A12S202 light sensor Arduino testbed.


/**************************************************************
 * Blynk is a platform with iOS and Android apps to control
 * Arduino, Raspberry Pi and the likes over the Internet.
 * You can easily build graphic interfaces for all your
 * projects by simply dragging and dropping widgets.
 *
 *   Downloads, docs, tutorials: http://www.blynk.cc
 *   Blynk community:            http://community.blynk.cc
 *   Social networks:            http://www.fb.com/blynkapp
 *                               http://twitter.com/blynk_app
 *
 * Blynk library is licensed under MIT license
 * This example code is in public domain.
 *
 **************************************************************
 * This sketch prints all virtual pin operations!
 *
 **************************************************************/

#define BLYNK_PRINT Serial
#include <SPI.h>
#include <Ethernet.h>
#include <BlynkSimpleEthernet.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "YourAuthToken";

void setup()
{
  Serial.begin(9600); // See the connection status in Serial Monitor
  Blynk.begin(auth);
}

// This is called for all virtual pins, that don't have BLYNK_WRITE handler
BLYNK_WRITE_DEFAULT() {
  BLYNK_LOG("V%d input: ", request.pin);
  // Print all parameter values
  for (auto i = param.begin(); i < param.end(); ++i) {
    BLYNK_LOG("* %s", i.asString());
  }
}

// This is called for all virtual pins, that don't have BLYNK_READ handler
BLYNK_READ_DEFAULT() {
  // Generate random response
  int val = random(0, 100);
  BLYNK_LOG("V%d output: %d", request.pin, val);
  Blynk.virtualWrite(request.pin, val);
}

void loop()
{
  Blynk.run();
}

Print all virtual data example

Print all virtual data example


// Demo using DHCP and DNS to perform a web client request.
// 2011-06-08 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php

#include <EtherCard.h>

// ethernet interface mac address, must be unique on the LAN
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };

byte Ethernet::buffer[600];
static uint32_t timer;

const char website[] PROGMEM = "www.sweeparis.com";

// called when the client request is complete
static void my_callback (byte status, word off, word len) {
  Serial.println(">>>");
  Serial.print(off);Serial.print("/");Serial.print(len);Serial.print(">>>");
  Ethernet::buffer[min(699, off + len)] = 0;
  Serial.print((const char*) Ethernet::buffer + off);
  Serial.println("...");
}

void setup () {
  Serial.begin(57600);
  Serial.println(F("\n[webClient]"));

  if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
    Serial.println(F("Failed to access Ethernet controller"));
  if (!ether.dhcpSetup())
    Serial.println(F("DHCP failed"));

  ether.printIp("IP:  ", ether.myip);
  ether.printIp("GW:  ", ether.gwip);
  ether.printIp("DNS: ", ether.dnsip);

  if (!ether.dnsLookup(website))
    Serial.println("DNS failed");

  ether.printIp("SRV: ", ether.hisip);
}

void loop () {
  ether.packetLoop(ether.packetReceive());

  delay(100);

  if (millis() > timer) {
    timer = millis() + 10000;
    Serial.println();
    Serial.print("<<< REQ ");
    ether.browseUrl(PSTR("/riot-server/"), "", website, my_callback);
  }
}

Add tests for web client

Add tests for web client


/*
 * findBaudTest - Test all supported baud settings
 *
 * The progress and results are printed to Serial, so open the 'Serial
 * Montitor'.
 *
 * The progress and results will be easier to read if you disable the
 * debugging (comment out or delete the "#define DEBUG_HC05" line in
 * HC05.h.
 */
#include <Arduino.h>
#include "HC05.h"

#ifdef HC05_SOFTWARE_SERIAL
#include <SoftwareSerial.h>
HC05 btSerial = HC05(A2, A5, A3, A4);  // cmd, state, rx, tx
#else
HC05 btSerial = HC05(3, 2);  // cmd, state
#endif

void setup()
{
  DEBUG_BEGIN(57600);
  Serial.begin(57600);
  btSerial.findBaud();
  btSerial.setBaud(4800);
  Serial.println("---------- Starting test ----------");
}

void loop()
{
  int numTests = 0;
  int failed = 0;
  unsigned long rate = 0;
  unsigned long rates[] = {4800,9600,19200,38400,57600,115200};

  for (int i = 0; i < 6; i++)
  {
    for (int j = 0; j < 6; j++)
    {
      numTests++;
      Serial.print(rates[i]);
      btSerial.setBaud(rates[i]);
      rate = btSerial.findBaud();
      if (rate != rates[i])
      {
        Serial.print(" FAILED: found rate ");
        Serial.println(rate);
        failed++;
      }
      else
      {
        Serial.print("->");
        Serial.print(rates[j]);
        btSerial.setBaud(rates[j]);
        rate = btSerial.findBaud();
        if (rate != rates[j])
        {
          Serial.print("FAILED: found rate ");
          Serial.println(rate);
          failed++;
        }
        else
        {
          Serial.println(" PASSED");
        }
      }
    }
  }

  Serial.println("--------- Tests Complete ----------");
  Serial.print("Results: ");
  Serial.print(failed);
  Serial.print(" of ");
  Serial.print(numTests);
  Serial.println(" tests failed.");

  while (true)
  {
     ;
  }
}

Add example of setbaud and findbaud

Add example of setbaud and findbaud

On branch parityAndStopBits
new file:   Examples/findBaudTest/findBaudTest.ino


/*
   Digital Potentiometer control over BLE

   MCP4110 digital Pots SPI interface
*/

// inslude the SPI library:
#include <SPI.h>
#include <SoftwareSerial.h>

SoftwareSerial bleSerial(2, 3); // RX, TX

// set pot select pin
const int potSS = 10;

//const int potWriteCmd = B00100011;
const int potWriteCmd = B00010011;

void setup() {
  // set output pins:
  pinMode(potSS, OUTPUT);

  // initialize SPI:
  SPI.begin();

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

  bleSerial.begin(9600);
//  digitalPotWrite(0);
}

void loop() {
  //  //test
  //  digitalPotWrite(pot1SS,36);
  //  delay(100);
  //    Wire.readByte();

  if (bleSerial.available()) {
    int val = bleSerial.read();
    Serial.write("value = ");
    Serial.print(val,DEC);
    digitalPotWrite(val);
  }

  if (Serial.available()) {
    bleSerial.write(Serial.read());
  }

}

void digitalPotWrite(int value) {
  // put the SS pin to low in order to select the chip:
  digitalWrite(potSS, LOW);

  SPI.transfer(potWriteCmd);
  SPI.transfer(value);

  // put the SS pin to high for transfering the data
  digitalWrite(potSS, HIGH);
}

Add simple program that sets the first recived byte by BLE and write in the pot


#include <SoftwareSerial.h>

SoftwareSerial SSerial(10, 11);

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

void loop(void) {
  if (Serial.available() > 0) {
    SSerial.write(Serial.read());
  }
  if (SSerial.available() > 0) {
    Serial.write(SSerial.read());
  }
}

Add GSM Serial for testing AT Command

Add GSM Serial for testing AT Command


/**
 * @file CosaSince.ino
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2015, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * @section Description
 * Verify Watchdog::since() and RTC::since() wrap-around behavior.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#include "Cosa/RTC.hh"
#include "Cosa/Trace.hh"
#include "Cosa/Watchdog.hh"
#include "Cosa/OutputPin.hh"
#include "Cosa/IOStream/Driver/UART.hh"

OutputPin led(Board::LED);

// Start time in milli-seconds
const uint32_t START = 0xfffff000UL;

void setup()
{
  uart.begin(9600);
  trace.begin(&uart, PSTR("CosaSince: started"));
  trace.flush();

  // Start timers. Use RTC::delay()
  Watchdog::begin();
  RTC::begin();

  // Set timers to the start time
  Watchdog::millis(START);
  RTC::millis(START);
}

void loop()
{
  led.on();
  uint32_t rms = RTC::millis();
  uint32_t wms = Watchdog::millis();
  uint32_t wsd = Watchdog::since(START);
  uint32_t rsd = RTC::since(START);
  int32_t diff = wsd - rsd;

  trace << RTC::seconds() << ':'
	<< rms << ':'
	<< wms << ':'
	<< rsd << ':'
	<< wsd << ':'
	<< diff << ':'
	<< diff / Watchdog::ms_per_tick()
	<< endl;

  delay(1000 - RTC::since(rms));
  led.off();

  delay(1000);
}

Add sketch to verify Watchdog/RTC::since() behavior.


#include "DHT.h"
#define DHTPIN 2     // what pin we're connected to

// Uncomment whatever type you're using!
#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);

// Phant arduino lib
// git clone https://github.com/sparkfun/phant-arduino ~/sketchbook/libraries/Phant
#include <Phant.h>

// Arduino example stream
// http://data.sparkfun.com/streams/VGb2Y1jD4VIxjX3x196z
// hostname, public key, private key
Phant phant("data.sparkfun.com", "VGb2Y1jD4VIxjX3x196z", "9YBaDk6yeMtNErDNq4YM");

#include <EtherCard.h>

byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
byte Ethernet::buffer[700];
Stash stash;
const char website[] PROGMEM = "google.com";

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

  if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
    Serial.println(F("Failed to access Ethernet controller"));
  if (!ether.dhcpSetup())
    Serial.println(F("DHCP failed"));

  ether.printIp("IP:  ", ether.myip);
  ether.printIp("GW:  ", ether.gwip);
  ether.printIp("DNS: ", ether.dnsip);
  if (!ether.dnsLookup(website))
    Serial.println(F("DNS failed"));

  Serial.println("Setup completed");

}

void loop() {

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius
  float t = dht.readTemperature();

  phant.add("humidity", h);
  phant.add("temperature", t);

  Serial.println("Sending data...");
  byte sd = stash.create();
  stash.println(phant.post());
  stash.save();
  ether.tcpSend();

  // Wait a few seconds between measurements.
  delay(10000);
}

Add example of Iot device that posts to data.sparkfun.com


//Skript for testing the input-values of the arduino by displaying values in the serial monitor

int delayTime = 4000;
int buttonState = 0;

int piezo = A0;
int photo = A1;
int poti = A2;
int switchBtn = 11;
int buttonBtn = 12;
int extFlash = 8;
int camTrigger = 9;
int camFocus = 10;

int piezoValue = 0;
int photoValue = 0;
int potiValue = 0;
int btnState = 0;
int switchState = 0;

void setup()
{
 Serial.begin(9600);
 pinMode(piezo, INPUT); pinMode(photo, INPUT); pinMode(poti, INPUT); pinMode(switchBtn, INPUT);
 pinMode(buttonBtn, INPUT); pinMode(extFlash, OUTPUT); pinMode(camTrigger, OUTPUT); pinMode(camFocus, OUTPUT);
}

void loop()
{
  if(readSensors() == true)
  {
    takePicture();
  }
  delay(delayTime);
}

int readSensors()
{
piezoValue = analogRead(piezo);
photoValue = analogRead(photo);
potiValue = analogRead(poti);

btnState = digitalRead(buttonBtn);
switchState = digitalRead(switchBtn);

Serial.print("Piezo-Wert : ");Serial.println(piezoValue);
Serial.print("Photo-Resistor : ");Serial.println(photoValue);
Serial.print("Potentiometer : ");Serial.println(potiValue);
Serial.print("Taster : ");Serial.println(btnState);
Serial.print("Schalter : ");Serial.println(switchState);
Serial.println("  ");
return(true);
}

void takePicture()
{
// do stuff here
}

Test input values by displaying in the serial monitor


// Arduino MAVLink test code.

#include "/home/bat/sketchbook/libraries/mavlink/ardupilotmega/mavlink.h"        // Mavlink interface
long last_time = 0;
void setup() {
  Serial.begin(57600);
  pinMode(13, OUTPUT);
}

void loop() {
	// Define the system type (see mavlink_types.h for list of possible types)

	// Initialize the required buffers
	mavlink_message_t msg;
	uint8_t buf[MAVLINK_MAX_PACKET_LEN];

        long t = millis();
        if (fabs(t-last_time) >= 1000 )
        {
          digitalWrite(13, HIGH);
    	  // Pack the message
          // static inline uint16_t mavlink_msg_heartbeat_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
          //	uint8_t type, uint8_t autopilot, uint8_t base_mode, uint32_t custom_mode, uint8_t system_status)
    	  mavlink_msg_heartbeat_pack(100, 200, &msg, MAV_TYPE_KITE, MAV_AUTOPILOT_GENERIC, MAV_MODE_GUIDED_ARMED, 0, MAV_STATE_ACTIVE);

    	  // Copy the message to send buffer
    	  uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);

    	  // Send the message (.write sends as bytes)
    	  Serial.write(buf, len);
          //Serial.println("");
          last_time = t;
        }
        delay(100);
        digitalWrite(13, LOW);
}

void SerialEvent() {
	mavlink_message_t msg;
	mavlink_status_t status;

	//receive data over serial

        while(Serial.available() > 0) {
		uint8_t c = Serial.read();

		//try to get a new message
		if(mavlink_parse_char(MAVLINK_COMM_0, c, &msg, &status)) {
			// Handle message
 			switch(msg.msgid) {
			        case MAVLINK_MSG_ID_SET_MODE: {
			        	// set mode
			        }
			        break;
			        case MAVLINK_MSG_ID_COMMAND_ACK:
					// EXECUTE ACTION
				break;
				default:
					//Do nothing
				break;
			}
		}
		// And get the next one
	}
}

Add sketch to test mavlink protocol using mavlink 1.0 from https://github.com/mavlink/c_library


#include <TeensyDmx.h>

#define DMX_REDE 2

byte DMXVal[] = {50};

// This isn't required for DMX sending, but the code currently requires it.
struct RDMINIT rdmData {
  "TeensyDMX v0.1",
  "Teensyduino",
  1,  // Device ID
  "DMX Node",
  1,  // The DMX footprint
  0,  // The DMX startAddress - only used for RDM
  0,  // Additional commands length for RDM
  0   // Definition of additional commands
};

TeensyDmx Dmx(Serial1, &rdmData, DMX_REDE);

void setup() {
  Dmx.setMode(TeensyDmx::DMX_OUT);
}

void loop() {
  Dmx.setChannels(0,DMXVal,1);
  Dmx.loop();
}

Add a DMX send example

Add a DMX send example


/****************************************************************************************************************************\
 *
 * Arduino interrupt tests, as simple and understandable as possible.
 * © Aapo Rista 2017, MIT license
 * Tested with Wemos ESP8266 D1 Mini PRO
 * https://www.wemos.cc/product/d1-mini-pro.html
 *
\*************************************************************************************************************************/

// const byte interruptPin = 2; // D4 on Wemos ESP8266
const byte interruptPin = D4; // If the board is correctly set in Arduino IDE, you can use D1, D2 etc. directly
volatile byte interruptCounter = 0;
int numberOfInterrupts = 0;
int state = 0;

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println("Start");
  // pinMode(interruptPin, INPUT_PULLUP);
  // Only one interrupt type can be attached to a GPIO pin at a time
  // attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, FALLING);
  // attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, RISING);
  attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, CHANGE);
}

void handleInterrupt() {
  interruptCounter++;
  state = digitalRead(interruptPin);
}

void loop() {

  if(interruptCounter>0){

      interruptCounter--;
      numberOfInterrupts++;

      Serial.print("Interrupt ");
      if (state == 1) {
        Serial.print(" RISING");
      } else {
        Serial.print("FALLING");
      }
      Serial.print(" at ");
      Serial.print(millis());
      Serial.print(" ms uptime. Total: ");
      Serial.println(numberOfInterrupts);
  }

}

Add simple interrupt test script

Add simple interrupt test script


#include "AL_ILI9341.h"
#include "AL_Font.h"

// Wiring
#define TFT_PORT PORTF
#define TFT_PIN PINF
#define TFT_DDR DDRF
#define TFT_RST A12
#define TFT_CS A11
#define TFT_RS A10
#define TFT_WR A9
#define TFT_RD A8

AL_ILI9341 tft(
    &TFT_PORT, &TFT_PIN, &TFT_DDR,
    TFT_RST, TFT_CS, TFT_RS, TFT_WR, TFT_RD);

AL_RgbColor backColor{255, 255, 255};
AL_RgbColor text1Color{255, 0, 0};
AL_RgbColor text2Color{0, 255, 0};
AL_RgbColor text3Color{0, 0, 255};
AL_RgbColor text4Color{0, 255, 255};
AL_RgbColor text5Color{255, 255, 0};

void setup()
{
    tft.setup();
    tft.setOrientation(AL_SO_LANDSCAPE2);
    tft.fillRect(0, 0, tft.getWidth(), tft.getHeight(), backColor);

    tft.drawText(10, 10, text1Color, backColor, 1, "hello");
    tft.drawText(10, 26, text2Color, backColor, 2, "hello");
    tft.drawText(10, 58, text3Color, backColor, 3, "hello");
    tft.drawText(10, 106, text4Color, backColor, 4, "hello");
    tft.drawText(10, 170, text5Color, backColor, 5, "hello");
}

void loop()
{
}

Add draw text with scale example.

Add draw text with scale example.


#include <NewPing.h>

#define SONAR_NUM 4 // Number or sensors.
#define MAX_DISTANCE 200 // Maximum distance (in cm) to ping.
#define PING_INTERVAL 33 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).

unsigned long pingTimer[SONAR_NUM]; // Holds the times when the next ping should happen for each sensor.
unsigned int cm[SONAR_NUM];         // Where the ping distances are stored.
uint8_t currentSensor = 0;          // Keeps track of which sensor is active.

NewPing sonar[SONAR_NUM] = {     // Sensor object array.
  NewPing(11, 12, MAX_DISTANCE), // Each sensor's trigger pin, echo pin, and max distance to ping.
  NewPing(9, 10, MAX_DISTANCE),
  NewPing(2, 3, MAX_DISTANCE),
  NewPing(5, 6, MAX_DISTANCE)
};

void setup() {
  Serial.begin(115200);
  pingTimer[0] = millis() + 75;           // First ping starts at 75ms, gives time for the Arduino to chill before starting.
  for (uint8_t i = 1; i < SONAR_NUM; i++) // Set the starting time for each sensor.
    pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
}

void loop() {
  for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors.
    if (millis() >= pingTimer[i]) {         // Is it this sensor's time to ping?
      pingTimer[i] += PING_INTERVAL * SONAR_NUM;  // Set next time this sensor will be pinged.
      if (i == 0 && currentSensor == SONAR_NUM - 1) oneSensorCycle(); // Sensor ping cycle complete, do something with the results.
      sonar[currentSensor].timer_stop();          // Make sure previous timer is canceled before starting a new ping (insurance).
      currentSensor = i;                          // Sensor being accessed.
      cm[currentSensor] = 0;                      // Make distance zero in case there's no ping echo for this sensor.
      sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
    }
  }
  // The rest of your code would go here.
}

void echoCheck() { // If ping received, set the sensor distance to array.
  if (sonar[currentSensor].check_timer())
    cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
}

void oneSensorCycle() { // Sensor ping cycle complete, do something with the results.
  for (uint8_t i = 0; i < SONAR_NUM; i++) {
    Serial.print(i);
    Serial.print("=");
    Serial.print(cm[i]);
    Serial.print("cm ");
  }
  Serial.println();
}

Add test sketch for SR-04 ultasound sensors


// Program for testing a single strip of lights.
// Cycles through each possible combination of pure colors:
// #000000 #FF0000 #00FF00 #FFFF00 #0000FF #FF00FF #00FFFF #FFFFFF
// For each color, lights up lights one at a time with a slight delay between
// individual lights, then leaves the whole strip lit up for 2 seconds.

#include <FAB_LED.h>

const uint8_t numPixels = 20;

apa106<D, 6> LEDstrip;
rgb pixels[numPixels] = {};

void setup()
{
}

void loop()
{
  static int color;

  for (int i = 0; i < numPixels; ++i) {
    pixels[i].r = !!(color & 1) * 255;
    pixels[i].g = !!(color & 2) * 255;
    pixels[i].b = !!(color & 4) * 255;
    delay(100);
    LEDstrip.sendPixels(numPixels, pixels);
  }

  color = (color + 1) % 8;

  // Display the pixels on the LED strip.
  LEDstrip.sendPixels(numPixels, pixels);
  delay(2000);
}

Add Arduino sketch for testing individual strips

This program cycles through all patterns of fully lit R, G, and B lights
in a known pattern at a known rate, so we can test each strip as it is
made.


// VoteVisualization
//
// Author: sven.mentl@gmail.com
// Released under the GPLv3 license to match the rest of the AdaFruit NeoPixel library

#include <Adafruit_NeoPixel.h>
#include <avr/power.h>

// Digital I/O Pin connected to Data In of the NeoPixel Ring
#define PIN            13

// Number of NeoPixels
#define NUMPIXELS      24

// Configuration of NeoPixels
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

// Constants
const uint32_t RED = pixels.Color(255, 0, 0);
const uint32_t GREEN = pixels.Color(0, 255, 0);
const uint32_t BLUE = pixels.Color(0, 0, 255);
const uint32_t OFF = pixels.Color(0, 0, 0);
const int START_SEQUENCE_BLINK_DELAY = 200;

void setup() {

  // Setup the serial connection
  Serial.begin(9600);

  // Initialize the NeoPixel library
  pixels.begin();

  // Display the start sequence to show that the right code is loaded and that the arduino is ready to be used
  startSequence();
}

void loop() {

  // Blocking call
  if (Serial.available() > 0) {

    // A value between 0 and 1 is expected on the serial line.
    // The value expresses the ratio of positive votes in relation to all votes.
    float ratio = Serial.parseFloat();
    if(ratio < 0 || ratio > 1) return;

    int numberOfGreens = (ratio * 24)+0.5;
    lightFirstXInGreenRestInRed(numberOfGreens);
  }
}

void lightFirstXInGreenRestInRed(int numberOfGreens){

  for(int i=0; i<numberOfGreens; i++){
   pixels.setPixelColor(i, GREEN);
  }
  for(int i=0+numberOfGreens; i<NUMPIXELS; i++){
   pixels.setPixelColor(i, RED);
  }
  pixels.show();
}

void startSequence(){
 for(int j=0; j<10; j++){
   lightAllLeds(BLUE);
   delay(START_SEQUENCE_BLINK_DELAY);
   lightAllLeds(OFF);
   delay(START_SEQUENCE_BLINK_DELAY);
 }
}

void lightAllLeds(uint32_t color) {
 for(int i=0; i<NUMPIXELS; i++){
   pixels.setPixelColor(i, color);
  }
  pixels.show();
}

Add working code for the arduino uno

Add working code for the arduino uno


/*
 * Author: Manuel Parra Z.
 * Date: 14/11/2015
 * License: MIT License
 * Materials:
 *      - Arduino Uno R3
 *      - DFRobot DF-MD V1.3
 *      - DFRobot Pirate 4WD
 * Description:
 *  This sketch will use as a movement test, first the rover will go foward
 * on the track, then it will go reverse, then will turn to left and finally
 * will turn to right. This sketch will show you the if you connected the
 * engines and batteries properly. Don't forget to review the fritzing
 * electronic diagram in the document section of the project
 */

int M1 = 4;
int E1 = 5;
int E2 = 6;
int M2 = 7;

void setup()
{
  Serial.begin(9600);
  pinMode(M1, OUTPUT);
  pinMode(E1, OUTPUT);
  pinMode(M2, OUTPUT);
  pinMode(E2, OUTPUT);
  Serial.println("Setup finished.");
}

void loop()
{
  Serial.println("Foward for 3 seconds.");
  digitalWrite(M1, HIGH);
  digitalWrite(M2, HIGH);
  analogWrite(E1, 200);
  analogWrite(E2, 200);
  delay(3000);

  Serial.println("Reverse for 3 seconds.");
  digitalWrite(M1, LOW);
  digitalWrite(M2, LOW);
  analogWrite(E1, 200);
  analogWrite(E2, 200);
  delay(3000);

  Serial.println("Left for 3 seconds.");
  digitalWrite(M1, LOW);
  digitalWrite(M2, HIGH);
  analogWrite(E1, 200);
  analogWrite(E2, 200);
  delay(3000);

  Serial.println("Right for 3 seconds.");
  digitalWrite(M1, HIGH);
  digitalWrite(M2, LOW);
  analogWrite(E1, 200);
  analogWrite(E2, 200);
  delay(3000);
}

Add the arduino sketch to test the rover movement.


/**
 * Author Teemu Mäntykallio
 * Initializes the library and turns the motor in alternating directions.
*/

#define EN_PIN    38  // Nano v3:   16 Mega:    38  //enable (CFG6)
#define DIR_PIN   55  //            19          55  //direction
#define STEP_PIN  54  //            18          54  //step
#define CS_PIN    40  //            17          40  //chip select

constexpr uint32_t steps_per_mm = 80;

#include <TMC2130Stepper.h>
TMC2130Stepper driver = TMC2130Stepper(EN_PIN, DIR_PIN, STEP_PIN, CS_PIN);

#include <AccelStepper.h>
AccelStepper stepper = AccelStepper(stepper.DRIVER, STEP_PIN, DIR_PIN);

void setup() {
    Serial.begin(9600);
    while(!Serial);
    Serial.println("Start...");
    pinMode(CS_PIN, OUTPUT);
    digitalWrite(CS_PIN, HIGH);
    driver.begin();             // Initiate pins and registeries
    driver.rms_current(600);    // Set stepper current to 600mA. The command is the same as command TMC2130.setCurrent(600, 0.11, 0.5);
    driver.stealthChop(1);      // Enable extremely quiet stepping
    driver.stealth_autoscale(1);
    driver.microsteps(16);

    stepper.setMaxSpeed(50*steps_per_mm); // 100mm/s @ 80 steps/mm
    stepper.setAcceleration(1000*steps_per_mm); // 2000mm/s^2
    stepper.setEnablePin(EN_PIN);
    stepper.setPinsInverted(false, false, true);
    stepper.enableOutputs();
}

void loop() {
    if (stepper.distanceToGo() == 0) {
        stepper.disableOutputs();
        delay(100);
        stepper.move(100*steps_per_mm); // Move 100mm
        stepper.enableOutputs();
    }
    stepper.run();
}

Add example for pairing with AccelStepper library