Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Change to use automatic gain. | // Moving Average Example
// Shows how to use an FIR filter as a moving average on a simple
// set of data that can be easily verified by hand.
#include <FIR.h>
// Make an instance of the FIR filter. In this example we'll use
// floating point values and an 8 element filter. For a moving average
// that means an 8 point moving average.
FIR<float, 8> fir;
void setup() {
Serial.begin(115200); // Start a serial port
// For a moving average we want all of the coefficients to be unity.
float coef[8] = { 1., 1., 1., 1., 1., 1., 1., 1.};
// Set the coefficients
fir.setFilterCoeffs(coef);
// The gain should be the number of elements for a moving average.
float gain = 8;
// Set the gain
fir.setGain(gain);
}
void loop() {
// Calculate the moving average for a time series with the elements.
// 0, 1, 2, ...., 13, 14, 15
for (float i=0; i < 16; i++) {
Serial.println(fir.processReading(i));
}
while (true) {}; // Spin forever
}
| // Moving Average Example
// Shows how to use an FIR filter as a moving average on a simple
// set of data that can be easily verified by hand.
#include <FIR.h>
// Make an instance of the FIR filter. In this example we'll use
// floating point values and an 8 element filter. For a moving average
// that means an 8 point moving average.
FIR<float, 8> fir;
void setup() {
Serial.begin(115200); // Start a serial port
// For a moving average we want all of the coefficients to be unity.
float coef[8] = { 1., 1., 1., 1., 1., 1., 1., 1.};
// Set the coefficients
fir.setFilterCoeffs(coef);
Serial.print("Gain set: ");
Serial.println(fir.getGain());
}
void loop() {
// Calculate the moving average for a time series with the elements.
// 0, 1, 2, ...., 13, 14, 15
for (float i=0; i < 16; i++) {
Serial.println(fir.processReading(i));
}
while (true) {}; // Spin forever
}
|
Update SR04 example to new 5.0 API | #include <Smartcar.h>
SR04 front;
const int TRIGGER_PIN = 6; //D6
const int ECHO_PIN = 7; //D7
void setup() {
Serial.begin(9600);
front.attach(TRIGGER_PIN, ECHO_PIN); //trigger pin, echo pin
}
void loop() {
Serial.println(front.getDistance());
delay(100);
}
| #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);
}
|
Change baud rate to 9600. | int vinpin = A0;
int voutpin = A1;
int gndpin = A2;
int zpin = A3;
int ypin = A4;
int xpin = A5;
void setup() {
Serial.begin(115200);
pinMode(vinpin, OUTPUT); digitalWrite(vinpin, HIGH);
pinMode(gndpin, OUTPUT); digitalWrite(gndpin, LOW);
pinMode(voutpin, INPUT);
pinMode(xpin, INPUT);
pinMode(ypin, INPUT);
pinMode(zpin, INPUT);
}
void loop() {
Serial.print(analogRead(xpin)); Serial.print("\t");
Serial.print(analogRead(ypin)); Serial.print("\t");
Serial.print(analogRead(zpin)); Serial.println();
}
| int vinpin = A0;
int voutpin = A1;
int gndpin = A2;
int zpin = A3;
int ypin = A4;
int xpin = A5;
void setup() {
Serial.begin(9600);
pinMode(vinpin, OUTPUT); digitalWrite(vinpin, HIGH);
pinMode(gndpin, OUTPUT); digitalWrite(gndpin, LOW);
pinMode(voutpin, INPUT);
pinMode(xpin, INPUT);
pinMode(ypin, INPUT);
pinMode(zpin, INPUT);
}
void loop() {
Serial.print(analogRead(xpin)); Serial.print("\t");
Serial.print(analogRead(ypin)); Serial.print("\t");
Serial.print(analogRead(zpin)); Serial.println();
}
|
Implement custom BMP data structure in program | #include <Wire.h>
// begin SD card libraries
#include <BlockDriver.h>
#include <FreeStack.h>
#include <MinimumSerial.h>
#include <SdFat.h>
#include <SdFatConfig.h>
#include <SysCall.h>
// end SD card libraries
#include "Bmp180.h" // RCR header
File file; // file object
//SdFatSdio sd_card; // MicroSD card
namespace rcr {
namespace level1payload {
void setup() {
// Start serial communication.
Serial.begin(9600); // in bits/second
}
void printBmpData(void) {
Serial.print("Temperature = ");
Serial.print(bmp_data.temperature);
Serial.println(" °C");
Serial.print("Ambient pressure = ");
Serial.print(bmp_data.ambient_pressure);
Serial.println(" Pa");
Serial.print("Pressure altitude = ");
Serial.print(bmp_data.pressure_altitude);
Serial.println(" meters");
Serial.println();
}
void loop() {
printBmpData();
delay(1000);
}
} // namespace level1_payload
} // namespace rcr
| #include <Wire.h>
// begin SD card libraries
#include <BlockDriver.h>
#include <FreeStack.h>
#include <MinimumSerial.h>
#include <SdFat.h>
#include <SdFatConfig.h>
#include <SysCall.h>
// end SD card libraries
#include "Bmp180.h" // RCR header
namespace rcr {
namespace level1payload {
Bmp180 bmp;
File file; // file object
//SdFatSdio sd_card; // MicroSD card
void setup() {
// Start serial communication.
Serial.begin(9600); // in bits/second
}
void printBmpData(void) {
Serial.print("Temperature = ");
Serial.print(bmp.temperature());
Serial.println(" °C");
Serial.print("Ambient pressure = ");
Serial.print(bmp.ambient_pressure());
Serial.println(" Pa");
Serial.print("Pressure altitude = ");
Serial.print(bmp.pressure_altitude());
Serial.println(" meters");
Serial.println();
}
void loop() {
printBmpData();
delay(1000);
}
} // namespace level1_payload
} // namespace rcr
|
Fix order of Serial.println arguments for HEX printing | #include <stdint.h>
#include "zg01_fsm.h"
#define PIN_CLOCK 2
#define PIN_DATA 3
#define PIN_LED 13
static uint8_t buffer[5];
void setup(void)
{
// initialize ZG01 pins
pinMode(PIN_CLOCK, INPUT);
pinMode(PIN_DATA, INPUT);
// initialize LED
pinMode(PIN_LED, OUTPUT);
// initialize serial port
Serial.begin(9600);
Serial.println("Hello world!\n");
// initialize ZG01 finite state machine
zg01_init(buffer);
}
void loop(void)
{
// wait until clock is low
while (digitalRead(PIN_CLOCK) != LOW);
// indicate activity on LED
digitalWrite(PIN_LED, HIGH);
// sample data and process in the ZG01 state machine
uint8_t data = (digitalRead(PIN_DATA) == HIGH) ? 1 : 0;
unsigned long ms = millis();
bool ready = zg01_process(ms, data);
// process data if ready
if (ready) {
for (int i = 0; i < 5; i++) {
Serial.print(HEX, buffer[i]);
Serial.print(" ");
}
Serial.println();
}
// wait until clock is high again
while (digitalRead(PIN_CLOCK) == LOW);
// indicate activity on LED
digitalWrite(PIN_LED, LOW);
}
| #include <stdint.h>
#include "zg01_fsm.h"
#define PIN_CLOCK 2
#define PIN_DATA 3
#define PIN_LED 13
static uint8_t buffer[5];
void setup(void)
{
// initialize ZG01 pins
pinMode(PIN_CLOCK, INPUT);
pinMode(PIN_DATA, INPUT);
// initialize LED
pinMode(PIN_LED, OUTPUT);
// initialize serial port
Serial.begin(9600);
Serial.println("Hello world!\n");
// initialize ZG01 finite state machine
zg01_init(buffer);
}
void loop(void)
{
// wait until clock is low
while (digitalRead(PIN_CLOCK) != LOW);
// indicate activity on LED
digitalWrite(PIN_LED, HIGH);
// sample data and process in the ZG01 state machine
uint8_t data = (digitalRead(PIN_DATA) == HIGH) ? 1 : 0;
unsigned long ms = millis();
bool ready = zg01_process(ms, data);
// process data if ready
if (ready) {
for (int i = 0; i < 5; i++) {
Serial.print(buffer[i], HEX);
Serial.print(" ");
}
Serial.println();
}
// wait until clock is high again
while (digitalRead(PIN_CLOCK) == LOW);
// indicate activity on LED
digitalWrite(PIN_LED, LOW);
}
|
Update class name. ToDo: search slave address. | //
// FaBo AmbientLight Brick
//
// brick_i2c_ambientlight
//
#include <Wire.h>
#include "fabo-isl29034.h"
void setup()
{
Serial.begin(115200);
faboAmbientLight.configuration();
faboAmbientLight.powerOn();
}
void loop()
{
double ambient = faboAmbientLight.readData();
Serial.print("Ambient:");
Serial.println(ambient);
delay(1000);
}
| //
// FaBo AmbientLight Brick
//
// brick_i2c_ambientlight
//
#include <Wire.h>
#include "fabo-isl29034.h"
FaBoAmbientLight faboAmbientLight;
void setup()
{
Serial.begin(115200);
faboAmbientLight.configuration();
faboAmbientLight.powerOn();
}
void loop()
{
double ambient = faboAmbientLight.readData();
Serial.print("Ambient:");
Serial.println(ambient);
delay(1000);
}
|
Fix typo in string termination | /*
String replace()
Examples of how to replace characters or substrings of a string
created 27 July 2010
modified 2 Apr 2012
by Tom Igoe
Hardware Required:
* MSP-EXP430G2 LaunchPad
This example code is in the public domain.
*/
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
// send an intro:
Serial.println("\n\nString replace:\n");
Serial.println();
}
void loop() {
String stringOne = "<HTML><HEAD><BODY>"";
Serial.println(stringOne);
// replace() changes all instances of one substring with another:
// first, make a copy of th original string:
String stringTwo = stringOne;
// then perform the replacements:
stringTwo.replace("<", "</");
// print the original:
Serial.println("Original string: " + stringOne);
// and print the modified string:
Serial.println("Modified string: " + stringTwo);
// you can also use replace() on single characters:
String normalString = "bookkeeper";
Serial.println("normal: " + normalString);
String leetString = normalString;
leetString.replace('o', '0');
leetString.replace('e', '3');
Serial.println("l33tspeak: " + leetString);
// do nothing while true:
while(true);
} | /*
String replace()
Examples of how to replace characters or substrings of a string
created 27 July 2010
modified 2 Apr 2012
by Tom Igoe
Hardware Required:
* MSP-EXP430G2 LaunchPad
This example code is in the public domain.
*/
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
// send an intro:
Serial.println("\n\nString replace:\n");
Serial.println();
}
void loop() {
String stringOne = "<HTML><HEAD><BODY>";
Serial.println(stringOne);
// replace() changes all instances of one substring with another:
// first, make a copy of th original string:
String stringTwo = stringOne;
// then perform the replacements:
stringTwo.replace("<", "</");
// print the original:
Serial.println("Original string: " + stringOne);
// and print the modified string:
Serial.println("Modified string: " + stringTwo);
// you can also use replace() on single characters:
String normalString = "bookkeeper";
Serial.println("normal: " + normalString);
String leetString = normalString;
leetString.replace('o', '0');
leetString.replace('e', '3');
Serial.println("l33tspeak: " + leetString);
// do nothing while true:
while(true);
}
|
Update delay time for arduino button read | const int buttonPin = 2;
int buttonState = 0;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT);
}
void loop() {
int randNum = random(300);
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
Serial.println(randNum);
}
delay(500);
}
| const int buttonPin = 2;
int buttonState = 0;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT);
}
void loop() {
int randNum = random(300);
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
Serial.println(randNum);
while(buttonState) {
buttonState = digitalRead(buttonPin);
}
}
delay(50);
}
|
Add sendData func and diagonalLines test pattern | //Pin connected to ST_CP of 74HC595
const int latchPin = 12;
//Pin connected to SH_CP of 74HC595
const int clockPin = 11;
////Pin connected to DS of 74HC595
const int dataPin = 13;
void setup() {
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}
void loop() {
// count from 2 (0x00001) to 32 (0x10000)
// note: the furthest right pin is disconnected; drop the right most digit in binary
for (int a = 2 ; a< 32;a*=2) {
digitalWrite(latchPin, LOW);
// shift out the bits:
shiftOut(dataPin, clockPin, MSBFIRST, data[a]);
//take the latch pin high so the LEDs will light up:
digitalWrite(latchPin, HIGH);
// pause before next value:
delay(500);
}
}
| //Pin connected to ST_CP of 74HC595
const int LATCHPIN = 12;
//Pin connected to SH_CP of 74HC595
const int CLOCKPIN = 11;
// Pin connected to DS of 74HC595
const int DATAPIN = 13;
// Number of pins
const int BOARDHEIGHT = 5;
// Delay
const int DELAY = 200;
void sendData(byte data) {
// 001010
for (int i = 0; i < boardHeight; i++) {
digitalWrite(LATCHPIN, LOW);
// shift out the bits:
digitalWrite(DATAPIN, data[i]);
//take the latch pin high so the LEDs will light up:
digitalWrite(LATCHPIN, HIGH);
Serial.print(bitRead(data, i));
}
//digitalWrite(0);
Serial.print(0);
Serial.println();
}
void diagonalLines() {
// count from 1 (0x00001) to 32 (0x10000)
// note: the furthest right pin is disconnected; drop the right most digit in binary
for (byte a = 1; a< 32;a*=2) {
sendData(a);
delay(DELAY);
}
}
void setup() {
pinMode(LATCHPIN, OUTPUT);
pinMode(CLOCKPIN, OUTPUT);
pinMode(DATAPIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
diagonalLines()
}
|
Change the trigger frequency to 9Hz. |
//
// 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 );
}
}
|
Fix DEBUG compile flag issue | // 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 text shown on serial monitor. | /**
* 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 signature of callback function in subscriber example | /*
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();
}
|
Update hallsensor code to reflect changes in wiring on breadboard using pullup resistor | #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;
}
}
|
Add ability to input alt characters | #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);
}
|
Fix raw value output to serial terminal. | /**
* 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());
}
}
|
Add code for blinking LED on digital out 13 | 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);
}
|
Use the sensor id as the identifier. | #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();
}
|
Remove blink code since unused here | /*
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);
} |
Set up the LCD pin | #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);
}
|
Modify pin 19's pin description for EVT board | /*
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
}
|
Correct typo in setup/loop tuple | #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
}
|
Add sound when button is held down | 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);
}
} |
Work on snow animation for three rings of tree | #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);
}
|
Update pin numbers and load cell params | #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();
}
|
Tweak to code so it will use the builtin LED on any board | #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
}
|
Update arduino code to light 3 pixels at a time. | #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);
}
}
|
Facilitate how to define which robot is being configured, on .ino now. | #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();
}
| #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();
}
|
Change t* vars from ints to floats | 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 to include Redbear Duo | // 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
}
}
|
Update temperature example with more semantic topic | #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();
}
|
Add main to test the position logic. | #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();
}
|
Fix missing SD begin in C++ Wrapper test | #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(
)
{
} |
Use LED iso PIN to avoid confusion | /*
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);
}
|
Update for new Entropy API | /*
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 to tested and working code | // 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());
}
|
Use Arduino101 CurieIMU new APIs. | #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();
}
|
Split motor definitions into multiple lines | #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() {
}
|
Update for Particle Core and Photon | // 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
}
}
|
Adjust max sensor distance to something more suitable | #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);
}
|
Add main MIDI controller sketch | #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 a sort of intensity wave option |
#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 v0.2.0 conditioning Arduino source | #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, ¤tByte);
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 boilerplate .ino to implement the baro sensor | #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 sample for simple bluetooth data. | #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 arduino code to run interface to robot. | #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 CC3000 Firmware update Sketch | /*
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 test sketch (to be removed). | #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();
}
| |
Backup of Working Slave Code | /*
* 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);
}
| |
Add example to list all addresses where a device is present. | #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 new starting payload program | #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 HTTP POST for Arduino Yun. | /*
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 the Arduino sketch for reading and remembering key numbers. Doesn't build with ino atm. | #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;
}
| |
Test program for PIR module |
/****************************************************************************
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...");
}
| |
Add arduino code to work with the serial_test | /***************************************************
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 next Arduino example - blinky with Timer1 OVF. | /**
* 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 basic GA1A12S202 light sensor Arduino testbed. | """
@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);
} | |
Print all virtual data example | /**************************************************************
* 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();
}
| |
Add tests for web client | // 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 example of setbaud and findbaud | /*
* 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 simple program that sets the first recived byte by BLE and write in the pot | /*
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 GSM Serial for testing AT Command | #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 sketch to verify Watchdog/RTC::since() behavior. | /**
* @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 example of Iot device that posts to data.sparkfun.com | #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);
}
| |
Test input values by displaying in the serial monitor | //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
}
| |
Add a DMX send example | #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 draw text with scale example. | #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 test sketch for SR-04 ultasound sensors |
#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 Arduino sketch for testing individual strips | // 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 the arduino sketch to test the rover movement. | /*
* 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 example for pairing with AccelStepper library | /**
* 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 RedBearLab BLE Mini module | /**************************************************************
* 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 example shows how to use Arduino + RedBearLab BLE Mini
* to connect your project to Blynk.
*
* NOTE: BLE support is in beta!
*
**************************************************************/
//#define BLYNK_DEBUG
#define BLYNK_PRINT Serial
#define BLYNK_USE_DIRECT_CONNECT
#include <BlynkSimpleSerialBLE.h>
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "YourAuthToken";
#define SerialBLE Serial1 // Set Serial object
void setup()
{
// This is for debug prints
Serial.begin(9600);
SerialBLE.begin(57600); // BLE Mini uses baud 57600
Blynk.begin(auth, SerialBLE);
}
void loop()
{
Blynk.run();
}
| |
Add WiFiNINA, Arduino MKR WiFi 1010 support | /*************************************************************
Download latest Blynk library here:
https://github.com/blynkkk/blynk-library/releases/latest
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
Sketch generator: http://examples.blynk.cc
Blynk community: http://community.blynk.cc
Follow us: 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 example shows how to use Arduino MKR 1010
to connect your project to Blynk.
Note: This requires WiFiNINA library
from http://librarymanager/all#WiFiNINA
Feel free to apply it to any other example. It's simple!
*************************************************************/
/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial
#define BLYNK_DEBUG
#include <SPI.h>
#include <WiFiNINA.h>
#include <BlynkSimpleWiFiNINA.h>
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "YourAuthToken";
// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "YourNetworkName";
char pass[] = "YourPassword";
void setup()
{
// Debug console
Serial.begin(9600);
while (!Serial) {}
Blynk.begin(auth, ssid, pass);
// You can also specify server:
//Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
//Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
}
void loop()
{
Blynk.run();
}
| |
Add an example showing how to set the QoS value of a message to publish | /*
MQTT with QoS example
- connects to an MQTT server
- publishes "hello world" to the topic "outTopic" with a variety of QoS values
*/
#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(String topic, byte* payload, unsigned int length) {
// handle message arrived
}
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.publish("outTopic", "hello world qos=0"); // Simple publish with qos=0
client.publish(MQTT::Publish("outTopic", "hello world qos=1")
.set_qos(1, client.next_packet_id()));
client.publish(MQTT::Publish("outTopic", "hello world qos=2")
.set_qos(2, client.next_packet_id()));
}
}
void loop()
{
client.loop();
}
| |
Add Arduino example that receives ESP predictions over serial. | // Arduino example that streams accelerometer data from an ADXL335
// (or other three-axis analog accelerometer) to the ESP system and
// lights different LEDs depending on the predictions made by the
// ESP system. Use with the user_accelerometer_gestures.cpp ESP example.
// the accelerometer pins
int zpin = A3;
int ypin = A4;
int xpin = A5;
// the LED pins
int redpin = 9;
int greenpin = 10;
int bluepin = 11;
// These are only used if you're plugging the ADXL335 (on the
// Adafruit breakout board) directly into the analog input pins
// of your Arduino. See comment below.
int vinpin = A0;
int voutpin = A1;
int gndpin = A2;
void setup() {
Serial.begin(115200);
// Lower the serial timeout (from its default value of 1000 ms)
// so that the call to Serial.parseInt() below doesn't pause for
// too long and disrupt the sending of accelerometer data.
Serial.setTimeout(2);
// Uncomment the following lines if you're using an ADXL335 on an
// Adafruit breakout board (https://www.adafruit.com/products/163)
// and want to plug it directly into (and power it from) the analog
// input pins of your Arduino board.
// pinMode(vinpin, OUTPUT); digitalWrite(vinpin, HIGH);
// pinMode(gndpin, OUTPUT); digitalWrite(gndpin, LOW);
// pinMode(voutpin, INPUT);
pinMode(xpin, INPUT);
pinMode(ypin, INPUT);
pinMode(zpin, INPUT);
}
void loop() {
Serial.print(analogRead(xpin)); Serial.print("\t");
Serial.print(analogRead(ypin)); Serial.print("\t");
Serial.print(analogRead(zpin)); Serial.println();
delay(10);
// Check for a valid prediction.
int val = Serial.parseInt();
if (val != 0) {
// Turn off all the LEDs.
analogWrite(redpin, 0);
analogWrite(greenpin, 0);
analogWrite(bluepin, 0);
// Turn on the LED corresponding to the prediction.
if (val == 1) analogWrite(redpin, 255);
if (val == 2) analogWrite(greenpin, 255);
if (val == 3) analogWrite(bluepin, 255);
}
}
| |
Add demo on new functionality | /*
* IRremote: IRInvertModulate - demonstrates the ability enable/disable
* IR signal modulation and inversion.
* An IR LED must be connected to Arduino PWM pin 3.
* To view the results, attach an Oscilloscope or Signal Analyser across the
* legs of the IR LED.
* Version 0.1 November, 2013
* Copyright 2013 Aaron Snoswell
* http://elucidatedbinary.com
*/
#include <IRremote.h>
IRsend irsend;
void setup()
{
Serial.begin(9600);
Serial.println("Welcome, visitor");
Serial.println("Press 'm' to toggle IR modulation");
Serial.println("Press 'i' to toggle IR inversion");
}
bool modulate = true;
bool invert = false;
void loop() {
if (!Serial.available()) {
// Send some random data
irsend.sendNEC(0xa90, 12);
} else {
char c;
do {
c = Serial.read();
} while(Serial.available());
if(c == 'm') {
modulate = !modulate;
if(modulate) Serial.println("Enabling Modulation");
else Serial.println("Disabling Modulation");
irsend.enableIRModulation(modulate);
} else if(c == 'i') {
invert = !invert;
if(invert) Serial.println("Enabling Invert");
else Serial.println("Disabling Invert");
irsend.enableIRInvert(invert);
} else {
Serial.println("Unknown Command");
}
}
delay(300);
}
| |
Bring up verification of GroveMoisture | int sensorPin = A1; // select the input pin for the potentiometer
float sensorValue[0];
float get_sensor_data_moisture(){
// read the value from the sensor:
return analogRead(sensorPin);
}
void setup() {
// declare the ledPin as an OUTPUT:
Serial.begin(115200);
}
void loop() {
sensorValue[0]=get_sensor_data_moisture();
Serial.print("sensor = " );
Serial.println(sensorValue[0]);
delay(1000);
}
| |
Add example sketch for testing out "will" messages | /*
MQTT "will" message example
- connects to an MQTT server with a will message
- publishes a message
- waits a little bit
- disconnects the socket *without* sending a disconnect packet
You should see the will message published when we disconnect
*/
#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);
WiFiClient wclient;
PubSubClient client(wclient, server);
void setup() {
// Setup console
Serial.begin(115200);
delay(10);
Serial.println();
Serial.println();
}
void loop() {
delay(1000);
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Connecting to ");
Serial.print(ssid);
Serial.println("...");
WiFi.begin(ssid, pass);
if (WiFi.waitForConnectResult() != WL_CONNECTED)
return;
Serial.println("WiFi connected");
}
if (WiFi.status() == WL_CONNECTED) {
MQTT::Connect con("arduinoClient");
con.set_will("test", "I am down.");
// Or to set a binary message:
// char msg[4] = { 0xde, 0xad, 0xbe, 0xef };
// con.set_will("test", msg, 4);
if (client.connect(con)) {
client.publish("test", "I am up!");
delay(1000);
wclient.stop();
} else
Serial.println("MQTT connection failed.");
delay(10000);
}
}
| |
Test code for the line follow | #define FAR_LEFT A0
#define LEFT A1
#define CENTER_LEFT A2
#define CENTER_RIGHT A3
#define RIGHT A4
#define FAR_RIGHT A5
#define WB_THRESHOLD 400
#define IR_DELAY 140
void setup()
{
Serial.begin(9600);
pinMode(FAR_LEFT, INPUT);
pinMode(LEFT, INPUT);
pinMode(CENTER_LEFT, INPUT);
pinMode(CENTER_RIGHT, INPUT);
pinMode(RIGHT, INPUT);
pinMode(FAR_RIGHT, INPUT);
pinMode(LED_BUILTIN, OUTPUT);
}
boolean toDigital(uint8_t pin){
int reading = analogRead(pin);
delayMicroseconds(IR_DELAY);
// Serial.println(reading);
return reading > WB_THRESHOLD;
}
void print_digital_readings(){
boolean far_left = toDigital(FAR_LEFT);
boolean left = toDigital(LEFT);
boolean center_left = toDigital(CENTER_LEFT);
boolean center_right = toDigital(CENTER_RIGHT);
boolean right = toDigital(RIGHT);
boolean far_right = toDigital(FAR_RIGHT);
Serial.print(far_left);
Serial.print("\t");
Serial.print(left);
Serial.print("\t");
Serial.print(center_left);
Serial.print("\t");
Serial.print(center_right);
Serial.print("\t");
Serial.print(right);
Serial.print("\t");
Serial.println(far_right);
}
void print_analog_readings(){
int far_left = analogRead(FAR_LEFT);
int left = analogRead(LEFT);
int center_left = analogRead(CENTER_LEFT);
int center_right = analogRead(CENTER_RIGHT);
int right = analogRead(RIGHT);
int far_right = analogRead(FAR_RIGHT);
Serial.print(far_left);
Serial.print("\t");
Serial.print(left);
Serial.print("\t");
Serial.print(center_left);
Serial.print("\t");
Serial.print(center_right);
Serial.print("\t");
Serial.print(right);
Serial.print("\t");
Serial.println(far_right);
}
void loop(){
print_analog_readings();
//print_digital_readings();
delay(20);
}
| |
Add blink file too for ease of access | /*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
Most Arduinos have an on-board LED you can control. On the Uno and
Leonardo, it is attached to digital pin 13. If you're unsure what
pin the on-board LED is connected to on your Arduino model, check
the documentation at http://arduino.cc
This example code is in the public domain.
modified 8 May 2014
by Scott Fitzgerald
*/
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
| |
Add arduino stepper motor control |
/*
Stepper Motor Control
*/
#include <Stepper.h>
const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
// for your motor
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0; // number of steps the motor has taken
int stepValue = 0; // current step number the motor is on
void setup() {
// initialize the serial port:
Serial.begin(9600);
myStepper.setSpeed(200);
}
void loop() {
// step one step:
myStepper.step(1);
//Serial.print("steps:");
Serial.println(stepValue);
//Serial.print("degrees: ");
//Serial.println(stepCount*1.8);
stepCount++;
stepValue = stepCount + 1;
if (stepValue > 200)
{
stepValue = stepValue - 200;
}
delay(100);
}
| |
Add super simple arduino servo-based cutdown program. | #include <Servo.h>
Servo myservo;
int pos = 0;
void setup() {
myservo.attach(9);
myservo.write(45); // Start out in a good position
delay(5000); // Wait as long as you like. (milliseconds)
}
void loop() {
myservo.write(130) // End in a release position
while(true); // Do nothing, forever.
}
| |
Add simple Arduino test program | void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
Keyboard.begin();
//setup buttons
pinMode(2, INPUT_PULLUP); //Button 1
pinMode(3, INPUT_PULLUP); //Button 2
pinMode(4, INPUT_PULLUP); //Button 3
pinMode(5, INPUT_PULLUP); //Button 4
//setup mainboard connection
pinMode(6, OUTPUT); //Reset pin
digitalWrite(6, LOW); //active high pulse
pinMode(7, OUTPUT); //Power on pin
digitalWrite(7, LOW); //active high pulse
//setup coin detector
pinMode(8, INPUT_PULLUP); //Coin 1
pinMode(9, INPUT_PULLUP); //Coin 2
pinMode(10, INPUT_PULLUP); //Coin 3
pinMode(11, INPUT_PULLUP); //Reject button
pinMode(12, OUTPUT); //Accept all coins
digitalWrite(12, LOW);
}
void loop() {
// read the input pin:
int buttonState2 = digitalRead(2);
int buttonState3 = digitalRead(3);
int buttonState4 = digitalRead(4);
int buttonState5 = digitalRead(5);
int buttonState8 = digitalRead(8);
int buttonState9 = digitalRead(9);
int buttonState10 = digitalRead(10);
int buttonState11 = digitalRead(11);
// print out the state of the buttons:
Serial.print(buttonState2);
Serial.print(buttonState3);
Serial.print(buttonState4);
Serial.print(buttonState5);
Serial.print(buttonState8);
Serial.print(buttonState9);
Serial.print(buttonState10);
Serial.print(buttonState11);
Serial.print('\n');
delay(25); // delay in between reads for stability
if(buttonState2 == LOW) {
Keyboard.write('A');
digitalWrite(6, HIGH); //push reset
}
else {
digitalWrite(6, LOW);
}
if(buttonState3 == LOW) {
Keyboard.write('B');
digitalWrite(7, HIGH); //push power
}
else {
digitalWrite(7, LOW);
}
if(buttonState4 == LOW) {
Keyboard.write('C');
}
if(buttonState5 == LOW) {
Keyboard.write('D');
}
if(buttonState8 == LOW) {
Keyboard.write('1');
}
if(buttonState9 == LOW) {
Keyboard.write('2');
}
if(buttonState10 == LOW) {
Keyboard.write('3');
}
}
| |
Add a tool for auto calibration of watchdog based clock. | /**
* @file CosaAutoCalibration.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
* Calibrate Watchdog clock with RTC clock as reference. Automatically
* adjust Watchdog clock to RTC clock tick.
*
* This file is part of the Arduino Che Cosa project.
*/
#include "Cosa/RTC.hh"
#include "Cosa/Watchdog.hh"
#include "Cosa/Trace.hh"
#include "Cosa/IOStream/Driver/UART.hh"
RTC::Clock clock;
Watchdog::Clock bark;
void setup()
{
// Start trace output stream on the serial port
uart.begin(57600);
trace.begin(&uart, PSTR("CosaAutoCalibration: started"));
// Start the watchdog and internal real-time clock
Watchdog::begin();
RTC::begin();
// Synchronized clocks
uint32_t now = clock.await();
delay(500);
bark.time(now + 1);
}
void loop()
{
static int32_t cycle = 1;
// Wait for clock update
uint32_t now = clock.await();
// Calculate error and possible adjustment
int32_t diff = bark.time() - now;
int32_t err = (1000 * diff) / cycle;
if (err != 0) {
bark.adjust(err / 2);
trace << endl << PSTR("calibration=") << bark.calibration() << endl;
cycle = 1;
clock.time(0);
now = clock.await();
delay(500);
bark.time(now + 1);
}
else {
trace << '.';
cycle += 1;
}
}
| |
Add TFmini plus (lidar) test code | // set this to the hardware serial port you wish to use
#define HWSERIAL Serial1
byte byteArray [9];
// Byte0 Byte 1 Byte2 Byte3 Byte4 Byte5 Byte6 Byte7 Byte8
// 0x89 0x89 Dist_L Dist_H Strength_L Strength_H Temp_L Temp_H Checksum
// byte2 is distance, overflows into byte3
byte configOutput [5] = {0x5A, 0x05, 0x07, 0x01, 0x11}; // write this array to HWSERIAL to enable output
byte configUART [5] = {0x5A, 0x05, 0x0A, 0x00, 0x11}; // write this array to HWSERIAL to set sensor to UART mode
// more config commands on datasheet https://acroname.com/sites/default/files/assets/sj-gu-tfmini_plus-01-a04-datasheet_en.pdf
void setup() {
Serial.begin(115200);
HWSERIAL.begin(115200);// default baud rate
HWSERIAL.write(configUART, 5); // set sensor to UART mode
HWSERIAL.write(configOutput, 5); // enable output
}
void loop() {
if (HWSERIAL.available() > 0) {
HWSERIAL.readBytes(byteArray, 9); // write output of read to an array of length 9
for (int i =0;i<9;i++){
Serial.println(byteArray[i]);
}
}
}
| |
Test for motor using enable pins and buttons operation. | #include <Stepper.h>
#define P1 P4_5
#define P2 P1_1
const int stepsPerRevolution = 200;
Stepper myStepper(stepsPerRevolution, 12,13,5,9);
short forward;
short backward;
void setup() {
// set the speed at 60 rpm:
myStepper.setSpeed(60);
// initialize the serial port:
Serial.begin(9600);
// Enable pin pull-up for the buttons
pinMode(P4_5, INPUT_PULLUP);
pinMode(P1_1, INPUT_PULLUP);
// Set modes for enable pins
pinMode(18, OUTPUT);
pinMode(19, OUTPUT);
}
void loop() {
// Read button pins
forward = digitalRead(P1);
backward = digitalRead(P2);
Serial.print(forward);
// Enable or disable motor
if (forward == 0 || backward == 0) {
digitalWrite(18, HIGH);
digitalWrite(19, HIGH);
}
else {
digitalWrite(18, LOW);
digitalWrite(19, LOW);
}
// Turn motor if a button is pressed
if (forward == 0) {
myStepper.step(1);
}
if (backward == 0) {
myStepper.step(-1);
}
// Delay before next loop. Determines how fast the motor turns
delay(4);
}
| |
Add canbus FD send example | // demo: CAN-BUS Shield, send data
// loovee@seeed.cc
#include <SPI.h>
#include "mcp2518fd_can.h"
/*SAMD core*/
#ifdef ARDUINO_SAMD_VARIANT_COMPLIANCE
#define SERIAL SerialUSB
#else
#define SERIAL Serial
#endif
#define CAN_2518FD
// the cs pin of the version after v1.1 is default to D9
// v0.9b and v1.0 is default D10
const int SPI_CS_PIN = BCM8;
#ifdef CAN_2518FD
mcp2518fd CAN(SPI_CS_PIN); // Set CS pin
#endif
void setup() {
SERIAL.begin(115200);
while(!Serial){};
CAN.setMode(0);
while (0 != CAN.begin((byte)CAN_500K_1M)) { // init can bus : baudrate = 500k
SERIAL.println("CAN BUS Shield init fail");
SERIAL.println(" Init CAN BUS Shield again");
delay(100);
}
byte mode = CAN.getMode();
SERIAL.printf("CAN BUS get mode = %d\n\r",mode);
SERIAL.println("CAN BUS Shield init ok!");
}
unsigned char stmp[64] = {0};
void loop() {
// send data: id = 0x00, standrad frame, data len = 8, stmp: data buf
stmp[63] = stmp[63] + 1;
if (stmp[63] == 100) {
stmp[63] = 0;
stmp[63] = stmp[63] + 1;
if (stmp[6] == 100) {
stmp[6] = 0;
stmp[5] = stmp[6] + 1;
}
}
CAN.sendMsgBuf(0x00, 0, 15, stmp);
delay(100); // send data per 100ms
SERIAL.println("CAN BUS sendMsgBuf ok!");
}
// END FILE
| |
Add ECDSA test for Arduino | #include <uECC.h>
#include <j0g.h>
#include <js0n.h>
#include <lwm.h>
#include <bitlash.h>
#include <GS.h>
#include <SPI.h>
#include <Wire.h>
#include <Scout.h>
#include <Shell.h>
#include <uECC.h>
extern "C" {
static int RNG(uint8_t *p_dest, unsigned p_size)
{
while(p_size) {
long v = random();
unsigned l_amount = min(p_size, sizeof(long));
memcpy(p_dest, &v, l_amount);
p_size -= l_amount;
p_dest += l_amount;
}
return 1;
}
void px(uint8_t *v, uint8_t num)
{
uint8_t i;
for(i=0; i<num; ++i)
{
Serial.print(v[i]); Serial.print(" ");
}
Serial.println();
}
}
void setup() {
Scout.setup();
uint8_t l_private[uECC_BYTES];
uint8_t l_public[uECC_BYTES * 2];
uint8_t l_hash[uECC_BYTES];
uint8_t l_sig[uECC_BYTES*2];
Serial.print("Testing ECDSA\n");
uECC_set_rng(&RNG);
for(;;) {
unsigned long a = millis();
if(!uECC_make_key(l_public, l_private))
{
Serial.println("uECC_make_key() failed");
continue;
}
unsigned long b = millis();
Serial.print("Made key 1 in "); Serial.println(b-a);
memcpy(l_hash, l_public, uECC_BYTES);
a = millis();
if(!uECC_sign(l_private, l_hash, l_sig))
{
Serial.println("uECC_sign() failed\n");
continue;
}
b = millis();
Serial.print("ECDSA sign in "); Serial.println(b-a);
a = millis();
if(!uECC_verify(l_public, l_hash, l_sig))
{
Serial.println("uECC_verify() failed\n");
continue;
}
b = millis();
Serial.print("ECDSA verify in "); Serial.println(b-a);
}
}
void loop() {
// put your main code here, to run repeatedly:
}
| |
Add sketch for reading button press | int BUTTON_PIN = 2;
void setup() {
pinMode(BUTTON_PIN, INPUT);
Serial.begin(9600);
}
void loop() {
//Serial.println("Hello computer!");
//Serial.print("This line will mash together with the next.");
int buttonPressed = digitalRead(BUTTON_PIN);
if(buttonPressed == 1) {
Serial.println("I pressed the button, and the button is:");
Serial.println(buttonPressed);
}
}
| |
Add sketch that includes all LCD interface implementations and adapters. | /**
* @file CosaLCDverify.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 build of all implementations of LCD and adapters.
*
* This file is part of the Arduino Che Cosa project.
*/
#include <HD44780.h>
#include <PCF8574.h>
#include <MJKDZ_LCD_Module.h>
#include <GY_IICLCD.h>
#include <DFRobot_IIC_LCD_Module.h>
#include <SainSmart_LCD2004.h>
#include <MCP23008.h>
#include <Adafruit_I2C_LCD_Backpack.h>
#include <ERM1602_5.h>
#include <Canvas.h>
#include <PCD8544.h>
#include <ST7565.h>
#include <VLCD.h>
| |
Add firmware for LightBlueBean Token | // Token's firmware working copy
// Code based on RFDUINO hardware, uses C char arrays
#include <ArduinoJson.h>
//Test JSON strings
char OFF[]= "{\"device\":\"LED\",\"event\":\"off\"}";
char GREEN[] = "{\"device\":\"LED\",\"event\":\"on\",\"color\":\"green\"}";
char RED[] = "{\"device\":\"LED\",\"event\":\"on\",\"color\":\"red\"}";
char BLUE[] = "{\"device\":\"LED\",\"event\":\"on\",\"color\":\"blue\"}";
char WHITE[] = "{\"device\":\"LED\",\"event\":\"on\",\"color\":\"white\"}";
void setup() {
//Serial.begin(9600); //Streams debug messagges over the serial port DEFAULT: OFF
// Test LED on startup
parseJSON(GREEN);
delay(300);
parseJSON(RED);
delay(300);
parseJSON(BLUE);
delay(300);
parseJSON(WHITE);
delay(300);
parseJSON(OFF);
delay(300);
//Initialise bluetooth
}
void loop() {
}
//Parses JSON messages
void parseJSON(char *payload) {
char sel;
// char json[200];
// payload.toCharArray(json, 50);
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(payload);
// Serial.print("DEBUG: "); Serial.println(json);
if (!root.success()) {
Serial.println("parseObject() failed");
return;
}
const char* device = root["device"];
const char* event = root["event"];
const char* color = root["color"];
if(strcmp(device, "LED") == 0)
{
if(strcmp(event, "on") == 0)
{
sel = color[0];
ledON(sel);
}
if (strcmp(event, "off") == 0)
{
ledOFF();
}
}
}
// Turns the LED off
void ledOFF(){
Bean.setLed(0, 0, 0);
}
// Turns on the LED on a specific color: r=red, g=gree, osv..
void ledON(char sel){
switch(sel)
{
case 'r':
{
Bean.setLed(255, 0, 0);
Serial.println("DEBUG: LED RED ON");
break;
}
case 'g':
{
Bean.setLed(0, 255, 0);
Serial.println("DEBUG: LED GREEN ON");
break;
}
case 'b':
{
Bean.setLed(0, 0, 255);
Serial.println("DEBUG: LED BLUE ON");
break;
}
case 'w':
{
Bean.setLed(255, 255, 255);
Serial.println("DEBUG: LED WITHE ON");
break;
}
}}
| |
Add new sketch for ESP8266 | /*
* Blink for esp8266
*/
#define ESP8266_LED 2
void setup() {
// put your setup code here, to run once:
pinMode(ESP8266_LED, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(ESP8266_LED, HIGH);
delay(1000);
digitalWrite(ESP8266_LED, LOW);
delay(1000);
}
| |
Add example to help find suitable contrast value. | /** Contrast Helper
*
* Loops through a range of contrast values and prints each one.
*
* To set the contrast in your sketch, simply put lcd.setContrast(xx);
* after your lcd.begin().
*
* Experimentally determined, contrast values around 65-70 tend to
* work reasonably well on most displays. The best contrast value
* for each display is specific to that particular display due to
* manufacturing tolerances and so forth.
*
*/
#include <SPI.h>
#include "PCD8544_Simple.h"
PCD8544_Simple lcd;
const uint8_t contrastMin = 40;
const uint8_t contrastMax = 80;
static uint8_t contrastDirection = 1;
static uint8_t contrast = (contrastMax-contrastMin)/2+contrastMin;
void setup()
{
lcd.begin();
}
void loop()
{
if(contrastDirection)
{
if(contrast++ > contrastMax)
{
contrastDirection = 0;
}
}
else
{
if(contrast-- < contrastMin)
{
contrastDirection = 1;
}
}
lcd.setContrast(contrast);
lcd.print("lcd.setContrast(");
lcd.print(contrast);
lcd.println(");");
delay(500);
} | |
Add Arduino program to generate camera and light trigger. |
//
// Generate a 9Hz square signal to trigger camera and lightning
//
// Arduino setup
void setup()
{
// Output signal
pinMode( 13, OUTPUT );
}
// Main loop
void loop()
{
// High state (11ms)
digitalWrite( 13, HIGH );
delay( 11 );
// Low state (100ms)
digitalWrite( 13, LOW );
delay( 100 );
}
| |
Add test sketch which simply runs each motor separately, without input from Android | #include "DualVNH5019MotorShield.h"
DualVNH5019MotorShield md;
void stopIfFault()
{
if (md.getM1Fault())
{
Serial.println("M1 fault");
while(1);
}
if (md.getM2Fault())
{
Serial.println("M2 fault");
while(1);
}
}
void setup()
{
Serial.begin(19200);
Serial.println("Dual VNH5019 Motor Shield");
md.init();
}
void loop()
{
for (int i = 0; i <= 400; i++)
{
md.setM1Speed(i);
stopIfFault();
if (i%200 == 100)
{
Serial.print("M1 current: ");
Serial.println(md.getM1CurrentMilliamps());
}
delay(2);
}
for (int i = 400; i >= -400; i--)
{
md.setM1Speed(i);
stopIfFault();
if (i%200 == 100)
{
Serial.print("M1 current: ");
Serial.println(md.getM1CurrentMilliamps());
}
delay(2);
}
for (int i = -400; i <= 0; i++)
{
md.setM1Speed(i);
stopIfFault();
if (i%200 == 100)
{
Serial.print("M1 current: ");
Serial.println(md.getM1CurrentMilliamps());
}
delay(2);
}
for (int i = 0; i <= 400; i++)
{
md.setM2Speed(i);
stopIfFault();
if (i%200 == 100)
{
Serial.print("M2 current: ");
Serial.println(md.getM2CurrentMilliamps());
}
delay(2);
}
for (int i = 400; i >= -400; i--)
{
md.setM2Speed(i);
stopIfFault();
if (i%200 == 100)
{
Serial.print("M2 current: ");
Serial.println(md.getM2CurrentMilliamps());
}
delay(2);
}
for (int i = -400; i <= 0; i++)
{
md.setM2Speed(i);
stopIfFault();
if (i%200 == 100)
{
Serial.print("M2 current: ");
Serial.println(md.getM2CurrentMilliamps());
}
delay(2);
}
}
| |
Add source code for Jarbas | #include <ESP8266HTTPClient.h>
#include <ESP8266WiFiMulti.h>
#define RELAY D1
const int HTTPS_PORT = 443;
const char* WIFI = "WIFI";
const char* PASSWORD = "PASSWORD";
const char* HOST = "hooks.slack.com";
const char* URL = "URL";
String PAYLOAD = String("{\"text\": \"@here Café quentinho na cafeteira!\", \"link_names\": 1}");
ESP8266WiFiMulti wifi;
bool turnOff = false;
bool coffeeIsReady = false;
void prepareCoffee() {
delay(9 * 60 * 1000); // Wait 9 minutes.
coffeeIsReady = true;
}
void notifySlack() {
HTTPClient client;
client.begin(HOST, HTTPS_PORT, URL, String("AC:95:5A:58:B8:4E:0B:CD:B3:97:D2:88:68:F5:CA:C1:0A:81:E3:6E"));
client.addHeader("Content-Type", "application/x-www-form-urlencoded");
client.POST(PAYLOAD);
client.end();
}
void waitAndTurnOffCoffeeMachine() {
delay(10 * 60 * 1000); // Wait 10 minutes.
digitalWrite(RELAY, LOW); // Turn off.
turnOff = true;
}
void setup() {
wifi.addAP(WIFI, PASSWORD);
pinMode(RELAY, OUTPUT);
digitalWrite(RELAY, HIGH);
}
void loop() {
if (!turnOff && !coffeeIsReady) prepareCoffee();
if (!turnOff && coffeeIsReady && wifi.run() == WL_CONNECTED) {
notifySlack();
waitAndTurnOffCoffeeMachine();
}
delay(1000);
}
| |
Add simple sketch to test Ultrasonic sensor | /*
Test Ultrasonic sensor readings
Created 2 7 2014
Modified 2 7 2014
*/
// Ultrasonic sensor settings
const byte ULTRASONIC_PIN = A6;
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.println(analogRead(ULTRASONIC_PIN));
delay(1000);
} | |
Add Simblee BLE example | /**************************************************************
* 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 example shows how to use Simblee BLE
* to connect your project to Blynk.
*
* NOTE: BLE support is in beta!
*
**************************************************************/
//#define BLYNK_DEBUG
#define BLYNK_PRINT Serial
//#define BLYNK_USE_DIRECT_CONNECT
#include <BlynkSimpleSimbleeBLE.h>
#include <SimbleeBLE.h>
char auth[] = "YourAuthToken";
void setup()
{
Serial.begin(9600);
SimbleeBLE.deviceName = "Simblee";
SimbleeBLE.advertisementInterval = MILLISECONDS(300);
SimbleeBLE.txPowerLevel = -20; // (-20dbM to +4 dBm)
// start the BLE stack
SimbleeBLE.begin();
Blynk.begin(auth);
Serial.println("Bluetooth device active, waiting for connections...");
}
void loop()
{
Blynk.run();
}
| |
Add example of a custom function in serial | #include "VdlkinoSerial.h"
VdlkinoSerial vdlkino(14, 6, &Serial);
uint16_t get_analog_byte(void *block) {
VdlkinoBlock *vblock = (VdlkinoBlock*) block;
return map(analogRead(vblock->pin), 0, 1023, 0, 255);
}
void setup() {
Serial.begin(9600);
vdlkino.operations[8] = &get_analog_byte;
}
void loop() {
vdlkino.run();
}
| |
Add a simple example sketch with many explanatory comments | /*
NeoPixel Ring simple sketch (c) 2013 Shae Erisson
released under the GPLv3 license to match the rest of the AdaFruit NeoPixel library
*/
#include <Adafruit_NeoPixel.h>
#ifdef __AVR_ATtiny85__ // Trinket, Gemma, etc.
#include <avr/power.h>
#endif
// Which pin on the FLORA is connected to the NeoPixel ring?
#define PIN 6
// We're using only one ring with 16 NeoPixel
#define NUMPIXELS 16
// When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
int delayval = 500; // delay for half a second
void setup() {
#ifdef __AVR_ATtiny85__ // Trinket, Gemma, etc.
if(F_CPU == 16000000) clock_prescale_set(clock_div_1);
// Seed random number generator from an unused analog input:
randomSeed(analogRead(2));
#else
randomSeed(analogRead(A0));
#endif
pixels.begin(); // This initializes the NeoPixel library.
}
void loop() {
// for one ring of 16, the first NeoPixel is 0, second is 1, all the way up to 15
for(int i=0;i<NUMPIXELS;i++){
// pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
pixels.setPixelColor(i,pixels.Color(0,150,0)); // we choose green
pixels.show(); // this sends the value once the color has been set
delay(delayval);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.