doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
8f02e916-58ea-4f95-96fe-94a794b9a792
{ "language": "Arduino" }
```arduino /* Basic MQTT example with Authentication - connects to an MQTT server, providing username and password - publishes "hello world" to the topic "outTopic" - 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(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"); } client.set_auth("testeruser", "testpass"); if (client.connect("arduinoClient")) { client.publish("outTopic","hello world"); client.subscribe("inTopic"); } } void loop() { client.loop(); } ``` Update the authentication example using an MQTT::Connect object directly
```arduino /* Basic MQTT example with Authentication - connects to an MQTT server, providing username and password - publishes "hello world" to the topic "outTopic" - 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(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(MQTT::Connect("arduinoClient") .set_auth("testeruser", "testpass"))) { client.publish("outTopic","hello world"); client.subscribe("inTopic"); } } void loop() { client.loop(); } ```
aa89a5c6-0d3c-4fbc-8a82-ded4eef524bc
{ "language": "Arduino" }
```arduino # 2 "TestSystemInfo.ino" #include <Arduino.h> #include <Arduino_FreeRTOS.h> #include <StandardCplusplus.h> #include <RabirdToolkit.h> #include <RTest.h> #include <RRawPointer.h> #include <RSharedPointer.h> #include <RFormatter.h> RTEST(TestSystemInfo) { RFormatter formatter(manager()->printer()); formatter("Size of int : %s").arg(sizeof(int)); formatter("Size of uintptr_t : %s").arg(sizeof(uintptr_t)); formatter("Size of rsize : %s").arg(sizeof(rsize)); formatter("Size of rnumber : %s").arg(sizeof(rnumber)); formatter("Size of ruint : %s").arg(sizeof(ruint)); }; void setup() { Serial.begin(9600); while(!Serial) // for the Arduino Leonardo/Micro only { } RTestApplication testApp; testApp.addTest(&RTEST_INSTANCE(TestSystemInfo)); testApp.run(); } void loop() { } ``` Use assert macro for print out system info
```arduino # 2 "TestSystemInfo.ino" #include <Arduino.h> #include <Arduino_FreeRTOS.h> #include <StandardCplusplus.h> #include <RabirdToolkit.h> #include <RTest.h> RTEST(TestSystemInfo) { RASSERT_MORE(sizeof(int), 0); RASSERT_MORE(sizeof(uintptr_t), 0); RASSERT_MORE(sizeof(rsize), 0); RASSERT_MORE(sizeof(rnumber), 0); RASSERT_MORE(sizeof(ruint), 0); }; void setup() { Serial.begin(9600); while(!Serial) // for the Arduino Leonardo/Micro only { } RTestApplication testApp; testApp.addTest(&RTEST_INSTANCE(TestSystemInfo)); testApp.run(); } void loop() { } ```
9c02a082-5c81-4e89-ac27-1dc5413eaee2
{ "language": "Arduino" }
```arduino #include <Arduboy.h> #include <ArdVoice.h> #include "voices.h" Arduboy arduboy; ArdVoice ardvoice; void setup() { arduboy.begin(); arduboy.setFrameRate(30); ardvoice.playVoice(merry_q6); } void loop() { if (!(arduboy.nextFrame())) return; if (arduboy.pressed(B_BUTTON)){ ardvoice.playVoice(merry_q6); } if (arduboy.pressed(A_BUTTON)){ ardvoice.stopVoice(); } } ``` Modify samples to use Arduboy2 library
```arduino #include <Arduboy2.h> #include <ArdVoice.h> #include "voices.h" Arduboy2 arduboy; ArdVoice ardvoice; void setup() { arduboy.begin(); arduboy.setFrameRate(30); ardvoice.playVoice(merry_q6); } void loop() { if (!(arduboy.nextFrame())) return; if (arduboy.pressed(B_BUTTON)){ ardvoice.playVoice(merry_q6); } if (arduboy.pressed(A_BUTTON)){ ardvoice.stopVoice(); } } ```
d8ffb084-6054-42e4-9e52-e009b5d08071
{ "language": "Arduino" }
```arduino 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(); } ``` Comment out power pins in ADXL example code.
```arduino int zpin = A3; int ypin = A4; int xpin = A5; // 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. //int vinpin = A0; //int voutpin = A1; //int gndpin = A2; 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(); } ```
0da8e2d0-5e84-4d29-8cfa-31545cfe3cf3
{ "language": "Arduino" }
```arduino #include "display.h" #include "sensor.h" #include <LiquidCrystal.h> // Arduino LCD library #include <Arduino.h> // enables use of byte pics void setup() { LCD::setup(); Sensor::setup(); } void loop() { int temp = Sensor::readTemp(); LCD::displayTemp(temp); delay(5000); LCD::clearScreen(); } ``` Update lcd to display and add loop functionality
```arduino #include "display.h" #include "sensor.h" #include <LiquidCrystal.h> // Arduino LCD library #include <Arduino.h> // enables use of byte pics void setup() { Display::setup(); Sensor::setup(); } void loop() { int temp = Sensor::readTemp(); int hum = Sensor::readHum(); Display::displayTemp(temp); Display::displayHum(hum); delay(3000); } ```
3c8c0a8e-b964-4cdc-8af8-3dd48c1197ac
{ "language": "Arduino" }
```arduino int motorPin = 9; int switchPin = 7; int motorStep = 0; int maxStep = 200; int minimumStepDelay = 2; String motorState = String("off"); void makeStep() { digitalWrite(motorPin, HIGH); digitalWrite(motorPin, LOW); motorStep += 1; if (motorStep > maxStep) { motorStep = 0; } } void resetMotor() { for (int i = motorStep; i < maxStep; i++) { makeStep(); delay(minimumStepDelay); } } void setup() { pinMode(switchPin, INPUT); pinMode(motorPin, OUTPUT); digitalWrite(switchPin, HIGH); Serial.begin(9600); } void loop() { if(Serial.available() > 0) { char command = Serial.read(); switch (command) { case 'd': Serial.println(String("Current step: ") + motorStep); break; case 's': makeStep(); Serial.println(motorStep); break; case 'r': resetMotor(); Serial.println(String("Motor reset. (Step is ") + motorStep + String(")")); } } } ``` Add correct pinout for all optional pins
```arduino int enablePin = 4; int MS1Pin = 5; int MS2Pin = 6; int MS3Pin = 7; int resetPin = 9; int sleepPin = 10; int motorPin = 11; int directionPin = 12; int switchPin = 13; // Stepping: Full, half, quarter, eigth, sixteenth int[] stepping = { B000, B100, B010, B110, B111 } int motorStep = 0; int maxStep = 200; int minimumStepDelay = 2; String motorState = String("off"); void makeStep() { digitalWrite(motorPin, HIGH); digitalWrite(motorPin, LOW); motorStep += 1; if (motorStep > maxStep) { motorStep = 0; } } void resetMotor() { for (int i = motorStep; i < maxStep; i++) { makeStep(); delay(minimumStepDelay); } } void setup() { pinMode(switchPin, INPUT); pinMode(motorPin, OUTPUT); digitalWrite(switchPin, HIGH); Serial.begin(9600); } void loop() { if(Serial.available() > 0) { char command = Serial.read(); switch (command) { case 'd': Serial.println(String("Current step: ") + motorStep); break; case 's': makeStep(); Serial.println(motorStep); break; case 'r': resetMotor(); Serial.println(String("Motor reset. (Step is ") + motorStep + String(")")); } } } ```
3dcf50a0-9fec-415a-bccb-b42be73bbb22
{ "language": "Arduino" }
```arduino #define DEBUG #include "TheThingsUno.h" const byte devAddr[4] = { 0x02, 0xDE, 0xAE, 0x00 }; const byte appSKey[16] = { 0x0D, 0x0E, 0x0A, 0x0D, 0x0B, 0x0E, 0x0E, 0x0F, 0x0C, 0x0A, 0x0F, 0x0E, 0x0B, 0x0A, 0x0B, 0x0E }; const byte nwkSKey[16] = { 0x0D, 0x0E, 0x0A, 0x0D, 0x0B, 0x0E, 0x0E, 0x0F, 0x0C, 0x0A, 0x0F, 0x0E, 0x0B, 0x0A, 0x0B, 0x0E }; #define debugSerial Serial #define loraSerial Serial1 // These are the input pins of your sensors #define TEMPSENSOR 0 #define SOILSENSOR 1 TheThingsUno ttu; void setup() { debugSerial.begin(115200); loraSerial.begin(57600); ttu.init(loraSerial, debugSerial); ttu.reset(); ttu.personalize(devAddr, nwkSKey, appSKey); #ifdef DEBUG ttu.debugStatus(); #endif Serial.println("Setup for The Things Network."); } void loop() { while (debugSerial.available()) loraSerial.write((char)debugSerial.read()); while (loraSerial.available()) debugSerial.write((char)loraSerial.read()); delay(1); } ``` Remove pre-filled DevAddr and Keys
```arduino #define DEBUG #include "TheThingsUno.h" const byte devAddr[4] = { /* copy DevAddr here */ }; const byte appSKey[16] = { /* copy AppSKey here */ }; const byte nwkSKey[16] = { /* copy NwkSKey here */ }; #define debugSerial Serial #define loraSerial Serial1 // These are the input pins of your sensors #define TEMPSENSOR 0 #define SOILSENSOR 1 TheThingsUno ttu; void setup() { debugSerial.begin(115200); loraSerial.begin(57600); ttu.init(loraSerial, debugSerial); ttu.reset(); ttu.personalize(devAddr, nwkSKey, appSKey); #ifdef DEBUG ttu.debugStatus(); #endif Serial.println("Setup for The Things Network."); } void loop() { while (debugSerial.available()) loraSerial.write((char)debugSerial.read()); while (loraSerial.available()) debugSerial.write((char)loraSerial.read()); delay(1); } ```
1624b262-b90c-410f-93eb-5572ebe2af96
{ "language": "Arduino" }
```arduino /* TestSuite sketch Use this sketch when running the Liberty Arduino Feature test suite. */ #include <EEPROM.h> #include <Liberty.h> Liberty liberty("TestNode"); boolean ns = false; int nc = 0; unsigned long ln; byte bs[20]; void setup() { liberty.sram(sramBytes, 20); liberty.invocable("foo", &foo); liberty.invocable("bar", &bar); liberty.invocable("qaz", &qaz); liberty.invocable("times", &times); liberty.invocable("start", &nstart); liberty.invocable("stop", &nstop); liberty.begin(); } void loop() { liberty.update(); if (ns) { unsigned long x = millis(); if (x - ln > 200) { ln = x; nc++; liberty.notify("testN1", nc); } } } int foo() { return bs[0]; } int bar() { return 42; } int qaz(int x) { return x * 4; } int times(int x, int y) { return x * y; } int nstart() { ns = true; nc = 0; ln = millis(); } int nstop() { ns = false; return nc; }``` Fix bug in sram size
```arduino /* TestSuite sketch Use this sketch when running the Liberty Arduino Feature test suite. */ #include <EEPROM.h> #include <Liberty.h> Liberty liberty("TestNode"); boolean ns = false; int nc = 0; unsigned long ln; byte bs[50]; void setup() { liberty.sram(bs, 50); liberty.invocable("foo", &foo); liberty.invocable("bar", &bar); liberty.invocable("qaz", &qaz); liberty.invocable("times", &times); liberty.invocable("start", &nstart); liberty.invocable("stop", &nstop); liberty.begin(); } void loop() { liberty.update(); if (ns) { unsigned long x = millis(); if (x - ln > 200) { ln = x; nc++; liberty.notify("testN1", nc); } } } int foo() { return bs[0]; } int bar() { return 42; } int qaz(int x) { return x * 4; } int times(int x, int y) { return x * y; } int nstart() { ns = true; nc = 0; ln = millis(); } int nstop() { ns = false; return nc; }```
b0abaf72-f827-4682-acee-4e16fb511ef5
{ "language": "Arduino" }
```arduino // https://github.com/thomasfredericks/Metro-Arduino-Wiring #include <Metro.h> const int MOTORPIN = 2; Metro blink = Metro(400); bool isVibrationOn = false; bool isMotorOn = false; uint32_t now; void onMotor(void) { digitalWrite(MOTORPIN, HIGH); isMotorOn = true; } void offMotor(void) { digitalWrite(MOTORPIN, LOW); isMotorOn = false; } void beginVibration(void) { blink.reset(); isVibrationOn = true; } void endVibration(void) { offMotor(); isVibrationOn = false; } void vibrationLoop(void) { if (!isVibrationOn) { return; } if (blink.check()) { if (isMotorOn) { offMotor(); } else { onMotor(); } } } void parseMessage(char letter) { switch (letter) { case 'v': beginVibration(); break; case 'V': endVibration(); break; default: break; } } void setup() { Serial.begin(115200); Mouse.begin(); pinMode(MOTORPIN, OUTPUT); } static void mouseLoop() { // move mouse to avoid screen saver static uint32_t mprevms = 0; const uint32_t PCLOCKMS = 540000; // 9 [min] if (now - mprevms > PCLOCKMS) { mprevms = now; Mouse.move(1, 0, 0); //Serial.write("M"); } } void loop() { now = millis(); vibrationLoop(); mouseLoop(); while (Serial.available()) { char letter = Serial.read(); parseMessage(letter); } } ``` Use TimerThree library to blink motor
```arduino // https://www.pjrc.com/teensy/td_libs_TimerOne.html #include <TimerThree.h> const int MOTORPIN = 5; void parseMessage(int letter) { switch (letter) { case 'v': Timer3.pwm(MOTORPIN, 512); break; case 'V': Timer3.pwm(MOTORPIN, 0); break; default: break; } } void setup() { Serial.begin(115200); Mouse.begin(); Timer3.initialize(400000); } void loop() { while (Serial.available()) { char letter = Serial.read(); parseMessage(letter); } } ```
21e81dcf-5aa9-49eb-94e5-3586c63e3a2e
{ "language": "Arduino" }
```arduino int incomingByte = 0; // for incoming serial data int relay1 = 4; int relay2 = 5; boolean state1 = false; boolean state2 = false; void setup() { Serial.begin(9600); pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); } void loop() { if (Serial.available() > 0) { incomingByte = Serial.read(); if (incomingByte == '1') { Serial.println("Toggling light 1"); if (state1 == false) { state1 = true; } else { state1 = false; } digitalWrite(led1, state1); } else if (incomingByte == '2') { Serial.println("Toggling light 2"); if (state2 == false){ state2 = true; } else { state2 = false; } digitalWrite(led2, state2); } } } ``` Fix variable name bug in Arduino code
```arduino int incomingByte = 0; // for incoming serial data int relay1 = 4; int relay2 = 5; boolean state1 = false; boolean state2 = false; void setup() { Serial.begin(9600); pinMode(relay1, OUTPUT); pinMode(relay2, OUTPUT); } void loop() { if (Serial.available() > 0) { incomingByte = Serial.read(); if (incomingByte == '1') { Serial.println("Toggling light 1"); if (state1 == false) { state1 = true; } else { state1 = false; } digitalWrite(relay1, state1); } else if (incomingByte == '2') { Serial.println("Toggling light 2"); if (state2 == false){ state2 = true; } else { state2 = false; } digitalWrite(relay2, state2); } } } ```
c7a8b257-ae45-4354-85b0-7e2bee053f4d
{ "language": "Arduino" }
```arduino /** * Wrapper for a thermometer. * * In this case it's a BMP085 barometric sensor, because that's what I had laying around. */ #include <Wire.h> #include <I2Cdev.h> #include <BMP085.h> BMP085 barometer; boolean hasThermometer; boolean initThermometer () { Serial.print(F("Setting up BMP085 for temperature...")); Wire.begin(); barometer.initialize(); if (barometer.testConnection()) { // request temperature barometer.setControl(BMP085_MODE_TEMPERATURE); // wait appropriate time for conversion (4.5ms delay) int32_t lastMicros = micros(); while (micros() - lastMicros < barometer.getMeasureDelayMicroseconds()); Serial.println(F(" done.")); hasThermometer = true; } else { Serial.println(F(" error.")); hasThermometer = false; } return hasThermometer; } float getTemperature () { return (hasThermometer) ? barometer.getTemperatureF() : 0.0; } ``` Switch to Adafruit's BPM085 library.
```arduino /** * Wrapper for a thermometer. * * In this case it's a BMP085 barometric sensor, because that's what I had laying around. */ #include <Wire.h> #include <Adafruit_BMP085.h> Adafruit_BMP085 barometer; boolean hasThermometer; boolean initThermometer () { Serial.print(F("Setting up BMP085 for temperature...")); if (barometer.begin()) { Serial.println(F(" done.")); hasThermometer = true; } else { Serial.println(F(" error.")); hasThermometer = false; } return hasThermometer; } float getTemperature () { return (hasThermometer) ? barometer.readTemperature() * 9 / 5 + 32 : 0.0; } ```
002691f7-a3e6-4d96-ae30-5831651be9e6
{ "language": "Arduino" }
```arduino void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: } ``` Implement initial setup for Wave Shield
```arduino #include <WaveHC.h> #include <WaveUtil.h> SdReader card; // This object holds the information for the card FatVolume vol; // This holds the information for the partition on the card FatReader root; // This holds the information for the volumes root directory WaveHC wave; // This is the only wave (audio) object, since we will only play one at a time void setupSdReader(SdReader &card) { if (!card.init()) Serial.println("Card init failed"); card.partialBlockRead(true); // Optimization. Disable if having issues } void setupFatVolume(FatVolume &vol) { uint8_t slot; // There are 5 slots to look at. for (slot = 0; slot < 5; slot++) if (vol.init(card, slot)) break; if (slot == 5) Serial.println("No valid FAT partition"); } void setupFatReader(FatReader &root) { if (!root.openRoot(vol)) Serial.println("Can't open root dir"); } void setup() { Serial.begin(9600); setupSdReader(card); setupFatVolume(vol); setupFatReader(root); } void loop() { } ```
02e50770-6971-42a3-ab17-5ca3c8018f48
{ "language": "Arduino" }
```arduino /************************************************************* 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 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 ESP32 BLE to connect your project to Blynk. Warning: Bluetooth support is in beta! *************************************************************/ /* Comment this out to disable prints and save space */ #define BLYNK_PRINT Serial #define BLYNK_USE_DIRECT_CONNECT #include <BlynkSimpleEsp32_BLE.h> #include <BLEDevice.h> #include <BLEServer.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourAuthToken"; void setup() { // Debug console Serial.begin(9600); Serial.println("Waiting for connections..."); Blynk.begin(auth); } void loop() { Blynk.run(); } ``` Add setDeviceName for ESP32 BLE
```arduino /************************************************************* 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 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 ESP32 BLE to connect your project to Blynk. Warning: Bluetooth support is in beta! *************************************************************/ /* Comment this out to disable prints and save space */ #define BLYNK_PRINT Serial #define BLYNK_USE_DIRECT_CONNECT #include <BlynkSimpleEsp32_BLE.h> #include <BLEDevice.h> #include <BLEServer.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourAuthToken"; void setup() { // Debug console Serial.begin(9600); Serial.println("Waiting for connections..."); Blynk.setDeviceName("Blynk"); Blynk.begin(auth); } void loop() { Blynk.run(); } ```
8357f55a-203b-48a1-8be1-89498def190a
{ "language": "Arduino" }
```arduino const int PIN_DATA = 4; const int PIN_LATCH = 3; const int PIN_CLOCK = 2; byte arrivalStatus = 1; void setup() { pinMode(PIN_DATA, OUTPUT); pinMode(PIN_CLOCK, OUTPUT); pinMode(PIN_LATCH, OUTPUT); } void loop() { digitalWrite(PIN_LATCH, LOW); shiftOut(PIN_DATA, PIN_CLOCK, MSBFIRST, arrivalStatus); digitalWrite(PIN_LATCH, HIGH); simulate_motion(); } /** * Pretend Update arrivalStatus as if this * was a bus that is getting closer to the * desired stop */ void simulate_motion() { arrivalStatus <<= 1; if (!arrivalStatus) arrivalStatus = 1; delay(1000); } ``` Read data from serial port
```arduino const int PIN_DATA = 4; const int PIN_LATCH = 3; const int PIN_CLOCK = 2; void setup() { //Initialize Shift register pinMode(PIN_DATA, OUTPUT); pinMode(PIN_CLOCK, OUTPUT); pinMode(PIN_LATCH, OUTPUT); //Initialize Serial Port Serial.begin(9600); } void loop() { //Wait for a single byte while (Serial.available() < 1); byte arrivalStatus = Serial.read(); Serial.write(arrivalStatus); //Update LEDs digitalWrite(PIN_LATCH, LOW); shiftOut(PIN_DATA, PIN_CLOCK, MSBFIRST, arrivalStatus); digitalWrite(PIN_LATCH, HIGH); } ```
388d68b1-2846-494b-8559-217a66558840
{ "language": "Arduino" }
```arduino const byte SCALE_VALUE[] = { 0b00000100, 0b00001100, 0b00011100, 0b00111100}; int senzor = A0; void setup() { Serial.begin(9600); pinMode(senzor, INPUT); // porty 2,3,4,5 jako vystup DDRD |= 0b00111100; } void loop() { int light = analogRead(senzor); Serial.println(light); int scale = map(light, 400, 800, 0, 3); Serial.println(scale); PORTD = 0b00000000; PORTD |= (0b00000100 << scale); // PORTD |= SCALE_VALUE[scale]; delay(200); } ``` Update map and bit mask
```arduino const byte SCALE_VALUE[] = { 0b00000100, 0b00001100, 0b00011100, 0b00111100}; // fotorezistor - A1, termistor - A0 int senzor = A1; void setup() { Serial.begin(9600); pinMode(senzor, INPUT); // porty 2,3,4,5 jako vystup DDRD |= 0b00111100; } void loop() { int light = analogRead(senzor); Serial.println(light); int scale = map(light, 300, 1000, 0, 3); Serial.println(scale); PORTD &= !0b00111100; // nastaveni vychoziho stavu - zhasnuto PORTD |= (0b00000100 << scale); // PORTD |= SCALE_VALUE[scale]; delay(200); } ```
d244ce8f-82d6-491f-9e7f-593a03a50edd
{ "language": "Arduino" }
```arduino void setup() { Serial.begin(9600); pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); pinMode(8, OUTPUT); pinMode(9, OUTPUT); pinMode(10, OUTPUT); pinMode(11, OUTPUT); pinMode(12, OUTPUT); pinMode(13, OUTPUT); for (int x = 2; x<=13; x++){ digitalWrite(x, HIGH); } } void loop() { char c; char l; int pin; int state; if (Serial.available()) { c = Serial.read(); if (c == 'O') { pin = Serial.parseInt(); l = Serial.read(); state = Serial.parseInt(); if (pin == 99) { for (int x = 2; x<=13; x++){ digitalWrite(x, state); } } else { digitalWrite(pin, state); } Serial.println('r'); } } } ``` Change initial state of all pins to LOW for new Relay Module
```arduino void setup() { Serial.begin(9600); pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); pinMode(8, OUTPUT); pinMode(9, OUTPUT); pinMode(10, OUTPUT); pinMode(11, OUTPUT); pinMode(12, OUTPUT); pinMode(13, OUTPUT); for (int x = 2; x<=13; x++){ digitalWrite(x, LOW); } } void loop() { char c; char l; int pin; int state; if (Serial.available()) { c = Serial.read(); if (c == 'O') { pin = Serial.parseInt(); l = Serial.read(); state = Serial.parseInt(); if (pin == 99) { for (int x = 2; x<=13; x++){ digitalWrite(x, state); } } else { digitalWrite(pin, state); } Serial.println('r'); } } } ```
d410e246-546d-4ad4-9520-48f5a2d95660
{ "language": "Arduino" }
```arduino #define LED 53 void setup() { pinMode(LED, OUTPUT); } void loop() { digitalWrite(LED, HIGH); delay(500); digitalWrite(LED, LOW); delay(500); } ``` Add blank line for tuto sample.
```arduino #define LED 53 void setup() { pinMode(LED, OUTPUT); } void loop() { digitalWrite(LED, HIGH); delay(500); digitalWrite(LED, LOW); delay(500); } ```
5d7fa53d-8feb-4e12-ae5d-53aed9b8ce2a
{ "language": "Arduino" }
```arduino void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: } ``` Revert "make editor folding happy"
```arduino void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: } ```
ad189790-e95c-4447-b0a6-216f8ea525bf
{ "language": "Arduino" }
```arduino #include <MINDS-i-Drone.h> ServoGenerator::Servo drive, steer; void setup() { drive.attach(12 /* APM pin 1 */); steer.attach(11 /* APM pin 2 */); ServoGenerator::begin(); //set the initial throttle/direction for the ESC/servo drive.write(90); steer.write(90); APMRadio::setup(); Serial.begin(9600); //delay 2 seconds for arming delay(2000); } void loop() { static uint32_t timer = micros(); uint32_t dt = timer+micros(); timer = -micros(); int driveSig = APMRadio::get(0); int steerSig = APMRadio::get(1); Serial.print(dt); Serial.print(" "); Serial.print(driveSig); Serial.print(" "); Serial.print(steerSig); Serial.println(); drive.write( driveSig ); steer.write( steerSig ); } ``` Add backsteer to drone radio drive
```arduino #include <MINDS-i-Drone.h> ServoGenerator::Servo drive, steer, backsteer; void setup() { drive.attach(12 /* APM pin 1 */); steer.attach(11 /* APM pin 2 */); backsteer.attach(8 /* APM pin 3 */); ServoGenerator::begin(); //set the initial throttle/direction for the ESC/servo drive.write(90); steer.write(90); backsteer.write(90); APMRadio::setup(); Serial.begin(9600); //delay 2 seconds for arming delay(2000); } void loop() { static uint32_t timer = micros(); uint32_t dt = timer+micros(); timer = -micros(); int driveSig = APMRadio::get(0); int steerSig = APMRadio::get(1); Serial.print(dt); Serial.print(" "); Serial.print(driveSig); Serial.print(" "); Serial.print(steerSig); Serial.println(); drive.write( driveSig ); steer.write( steerSig ); backsteer.write( 90 - steerSig ); } ```
8f28f284-9e8b-44cd-9e97-66345ffa3ef5
{ "language": "Arduino" }
```arduino /* Arduino based self regulating kitchen garden */ #include <DHT.h> // temperature related setup #define DHTPIN 2 // Humidity and temperature sensor pin #define DHTTYPE DHT22 // Model DHT 22 (AM2302) DHT airSensor(DHTPIN, DHTTYPE); // setup DHT sensor float airHumidity; float airTemperature; // light related setup int lightSensorPin = 3; // Set to whereever light sensor is connected int lampRelay = 4; // Set to whereever relay for lamp is connected // activity led setup int ledPin = 13; // this is just for checking activity // Initialize settings void setup() { // Initialize output pins. pinMode(ledPin, OUTPUT); // Initialize input pins. pinMode(lightSensorPin, INPUT); airSensor.begin(); // begin DHT so it is ready for reading } // Main loop void loop() { // Read sensor values analogRead(lightSensorPin); airSensor.readHumidity(); // read humidity from DHT airSensor.readTemperature(); // read temperature from DHT } ``` Add SHT10 sensor and fix some setup
```arduino /* Arduino based self regulating kitchen garden */ #include <SHT1x.h> #include <DHT.h> // soil related setup #define soilDataPin 3 #define soilClockPin 4 SHT1x soilSensor(soilDataPin, soilClockPin); float soilTemperature; float soilMoisture; // air temperature related setup #define DHTPIN 2 // Humidity and temperature sensor pin #define DHTTYPE DHT22 // Model DHT 22 (AM2302) DHT airSensor(DHTPIN, DHTTYPE); // setup DHT sensor float airHumidity; float airTemperature; // light related setup #define lightSensorPin A0 // Set to whereever light sensor is connected // activity led setup int ledPin = 13; // this is just for checking activity // Initialize settings void setup() { // Initialize output pins. pinMode(ledPin, OUTPUT); // Initialize input pins. pinMode(lightSensorPin, INPUT); // Is this needed? It is analog pin.. airSensor.begin(); // begin DHT so it is ready for reading } // Main loop void loop() { // Read sensor values analogRead(lightSensorPin); // read light level from LDR airSensor.readHumidity(); // read humidity from DHT airSensor.readTemperature(); // read temperature from DHT sht1x.readTemperatureC(); // read humidity from SHT10 sht1x.readHumidity(); // read temperature from SHT10 } ```
e28f95bb-7ca6-4b4d-b806-49d7ceff0af4
{ "language": "Arduino" }
```arduino #ifndef BOLTARDUINO #define BOLTARDUINO #include "button.h" #include "led.h" #include "screen.h" #include "game.h" #include "const.h" #include "clock.h" void setup() { Serial.begin(115200); //Attach interrupt for 64 button shield attachInterrupt(digitalPinToInterrupt(P_BUTTON_INTERRUPT), button_ISR, FALLING); //Generate new random seed randomSeed(analogRead(0)); } void loop() { screen_display("READY"); led_set(1, LED_STATE_FLASHING); button_wait(1); game_start(); } #endif ``` Add missing import to main .ino file
```arduino #ifndef BOLTARDUINO #define BOLTARDUINO #include "button.h" #include "led.h" #include "screen.h" #include "game.h" #include "const.h" #include "clock.h" #include "controller.h" void setup() { Serial.begin(115200); //Attach interrupt for 64 button shield attachInterrupt(digitalPinToInterrupt(P_BUTTON_INTERRUPT), button_ISR, FALLING); //Generate new random seed randomSeed(analogRead(0)); } void loop() { screen_display("READY"); led_set(1, LED_STATE_FLASHING); button_wait(1); game_start(); } #endif ```
6e7bc549-9af7-4364-8632-273f9866f78f
{ "language": "Arduino" }
```arduino #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(); } ``` Put opening braces on separate line
```arduino #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(); } ```
9e87bd28-aa3d-4ebe-ab58-f414afbb6e19
{ "language": "Arduino" }
```arduino #include <Bridge.h> #include "logger.h" #include "thingspeakReceiver.h" ThingspeakReceiver thingspeakReceiver; #include <Adafruit_LEDBackpack.h> #include <Adafruit_GFX.h> #include <Wire.h> #define PIN_LED 13 Adafruit_7segment matrix = Adafruit_7segment(); void setup() { pinMode(PIN_LED, OUTPUT); Bridge.begin(); //Yun Bridge logger->init(); // init 7-segments matrix matrix.begin(0x70); matrix.setBrightness(2); displayCounter(0); //setup the IoT platforms logger->log("Start setup connection with IoT platforms...\n"); thingspeakReceiver.init(); //Everything seems to be ok, let's start ! logger->log("\nBottle Opener up, Let's start to play :) !!!\n"); //highlight blue led just to prevent everything is OK. Useful when logs are disabled digitalWrite(PIN_LED, HIGH); } /** Arduino Loop */ void loop() { int counter = thingspeakReceiver.receiveCounter(); displayCounter(counter); delay(500); } /** Display Counter on è */ void displayCounter(int counter) { matrix.print(counter); matrix.writeDisplay(); } ``` Use of ShiftrConnector as receiver
```arduino #include <Bridge.h> #include "logger.h" ///////////////////////////////////////////// // Include of Iot Platform's connectors #include "thingspeakReceiver.h" ThingspeakReceiver thingspeakReceiver; int thingsSpeakCounter = 0; #include "shiftrConnector.h" ShiftrConnector shiftrConnector; int shiftrCounter = 0; ///////////////////////////////////////////// #include <Adafruit_LEDBackpack.h> #include <Adafruit_GFX.h> #include <Wire.h> #define PIN_LED 13 Adafruit_7segment matrix = Adafruit_7segment(); void setup() { pinMode(PIN_LED, OUTPUT); Bridge.begin(); //Yun Bridge logger->init(); // init 7-segments matrix matrix.begin(0x70); matrix.setBrightness(2); displayCounter(0); //setup the IoT platforms logger->log("Start setup connection with IoT platforms...\n"); thingspeakReceiver.init(); shiftrConnector.init(); //Everything seems to be ok, let's start ! logger->log("\nBottle Opener up, Let's start to play :) !!!\n"); //highlight blue led just to prevent everything is OK. Useful when logs are disabled digitalWrite(PIN_LED, HIGH); } /** Arduino Loop */ void loop() { //need to refresh shiftr API in order to send and receive new messages shiftrConnector.loop(); thingsSpeakCounter = thingspeakReceiver.receiveCounter(); shiftrCounter = shiftrConnector.receiveMessage(); //display whatever counter, they should be the same, independently of the platform displayCounter(shiftrCounter); delay(10); } /** Display Counter on è */ void displayCounter(int counter) { matrix.print(counter); matrix.writeDisplay(); } ```
9cb2ca8c-f0b9-494c-963b-45179e5d4b63
{ "language": "Arduino" }
```arduino #include <M5Stack.h> // the setup routine runs once when M5Stack starts up void setup(){ // initialize the M5Stack object M5.begin(); // Lcd display M5.Lcd.println("This is software power off demo"); M5.Lcd.println("Press the button A to power off."); // Set the wakeup button M5.Power.setWakeupButton(BUTTON_A_PIN); } // the loop routine runs over and over again forever void loop() { if(M5.BtnA.wasPressed()) { M5.Power.powerOFF(); } M5.update(); } ``` Remove settin wakeup button from poserOFF example
```arduino #include <M5Stack.h> // the setup routine runs once when M5Stack starts up void setup(){ // initialize the M5Stack object M5.begin(); // Lcd display M5.Lcd.println("This is software power off demo"); M5.Lcd.println("Press the button A to power off."); } // the loop routine runs over and over again forever void loop() { if(M5.BtnA.wasPressed()) { M5.Power.powerOFF(); } M5.update(); } ```
b6d00218-d56e-4e37-abd1-46432d1994b6
{ "language": "Arduino" }
```arduino #include <Bridge.h> #include "thingspeakReceiver.h" ThingspeakReceiver thingspeakReceiver; #include <Adafruit_LEDBackpack.h> #include <Adafruit_GFX.h> #include <Wire.h> #define PIN_LED_KO 12 #define PIN_LED_OK 13 Adafruit_7segment matrix = Adafruit_7segment(); void setup() { pinMode(PIN_LED_KO, OUTPUT); pinMode(PIN_LED_OK, OUTPUT); _setKO(); Bridge.begin(); //Yun Bridge Serial.begin(9600); while (!Serial); matrix.begin(0x70); matrix.setBrightness(2); displayCounter(0); thingspeakReceiver.init(); Serial.println("Counter Up !!!"); _setOK(); } void loop() { int counter = thingspeakReceiver.receiveCounter(); displayCounter(counter); delay(100); } void displayCounter(int counter) { matrix.print(counter); matrix.writeDisplay(); Serial.println(counter); } void _setOK() { digitalWrite(PIN_LED_KO, LOW); digitalWrite(PIN_LED_OK, HIGH); } void _setKO() { digitalWrite(PIN_LED_OK, LOW); digitalWrite(PIN_LED_KO, HIGH); } ``` Remove non-necessary code for the demo
```arduino #include <Bridge.h> #include "logger.h" #include "thingspeakReceiver.h" ThingspeakReceiver thingspeakReceiver; #include <Adafruit_LEDBackpack.h> #include <Adafruit_GFX.h> #include <Wire.h> #define PIN_LED 13 Adafruit_7segment matrix = Adafruit_7segment(); void setup() { pinMode(PIN_LED, OUTPUT); Bridge.begin(); //Yun Bridge logger->init(); // init 7-segments matrix matrix.begin(0x70); matrix.setBrightness(2); displayCounter(0); //setup the IoT platforms logger->log("Start setup connection with IoT platforms...\n"); thingspeakReceiver.init(); //Everything seems to be ok, let's start ! logger->log("\nBottle Opener up, Let's start to play :) !!!\n"); //highlight blue led just to prevent everything is OK. Useful when logs are disabled digitalWrite(PIN_LED, HIGH); } /** Arduino Loop */ void loop() { int counter = thingspeakReceiver.receiveCounter(); displayCounter(counter); delay(500); } /** Display Counter on è */ void displayCounter(int counter) { matrix.print(counter); matrix.writeDisplay(); } ```
921b8385-af8d-4647-a74e-a0784814d24e
{ "language": "Arduino" }
```arduino #include <SPI.h> #define SPI_READ_CMD 0x03 #define CS_PIN 10 unsigned int num_bytes; unsigned int i; void setup() { Serial.begin(115200); pinMode(CS_PIN, OUTPUT); digitalWrite(CS_PIN, HIGH); SPI.begin(); } void read_eeprom(unsigned int num_bytes) { unsigned int addr; byte resp; digitalWrite(CS_PIN, LOW); /* transmit read command with 3 byte start address */ SPI.transfer(SPI_READ_CMD); SPI.transfer(0x00); SPI.transfer(0x00); SPI.transfer(0x00); for (addr = 0; addr < num_bytes; addr++) { resp = SPI.transfer(0xff); Serial.write(resp); } digitalWrite(CS_PIN, HIGH); } void loop() { /* wait for the integer with the requested number of bytes */ if (Serial.available() == 4) { num_bytes = 0; /* merge four bytes to single integer */ for (i = 0; i < 4; i++) num_bytes |= Serial.read() << (i * 8); read_eeprom(num_bytes); } } ``` Convert global variables to local
```arduino #include <SPI.h> #define SPI_READ_CMD 0x03 #define CS_PIN 10 void setup() { Serial.begin(115200); pinMode(CS_PIN, OUTPUT); digitalWrite(CS_PIN, HIGH); SPI.begin(); } void read_eeprom(unsigned int num_bytes) { unsigned int addr; byte resp; digitalWrite(CS_PIN, LOW); /* transmit read command with 3 byte start address */ SPI.transfer(SPI_READ_CMD); SPI.transfer(0x00); SPI.transfer(0x00); SPI.transfer(0x00); for (addr = 0; addr < num_bytes; addr++) { resp = SPI.transfer(0xff); Serial.write(resp); } digitalWrite(CS_PIN, HIGH); } void loop() { unsigned int num_bytes; unsigned int i; /* wait for the integer with the requested number of bytes */ if (Serial.available() == 4) { num_bytes = 0; /* merge four bytes to single integer */ for (i = 0; i < 4; i++) num_bytes |= Serial.read() << (i * 8); read_eeprom(num_bytes); } } ```
07afc135-6874-4eea-aa2f-afbd352929a9
{ "language": "Arduino" }
```arduino #include <Wire.h> #include <LiquidCrystal_I2C.h> static constexpr unsigned long TimeChunk = 2 * 1000; static LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); static unsigned long endTime; static bool previousPressed; void setup() { lcd.begin(16,2); lcd.backlight(); pinMode(A0, INPUT_PULLUP); delay(10); endTime = millis() + 10000 * TimeChunk; previousPressed = false; } void loop() { lcd.setCursor(0,0); unsigned long currentTime = millis(); if (currentTime >= endTime) { lcd.print("GAME OVER!"); } else { bool currentPressed = digitalRead(A0); if (currentPressed && !previousPressed) { endTime += 10 * TimeChunk; } previousPressed = currentPressed; unsigned long remainingChunk = (endTime - currentTime) / TimeChunk; char buf[12]; lcd.print(itoa(remainingChunk, buf, 10)); } delay(10); } ``` Fix ghost press at launch
```arduino #include <Wire.h> #include <LiquidCrystal_I2C.h> static constexpr unsigned long TimeChunk = 2 * 1000; static LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); static unsigned long endTime; static bool previousPressed; void setup() { lcd.begin(16,2); lcd.backlight(); pinMode(A0, INPUT_PULLUP); delay(10); endTime = millis() + 10000 * TimeChunk; previousPressed = HIGH; } void loop() { lcd.setCursor(0,0); unsigned long currentTime = millis(); if (currentTime >= endTime) { lcd.print("GAME OVER!"); } else { bool currentPressed = digitalRead(A0); if (currentPressed && !previousPressed) { endTime += 10 * TimeChunk; } previousPressed = currentPressed; unsigned long remainingChunk = (endTime - currentTime) / TimeChunk; char buf[12]; lcd.print(itoa(remainingChunk, buf, 10)); } delay(10); } ```
e0f36114-83dc-4a34-8ca8-9c8b21c773b8
{ "language": "Arduino" }
```arduino #include "pn532_i2c_particle/pn532_i2c_particle.h" #include "pn532_i2c_particle/PN532.h" #include "pn532_i2c_particle/NfcAdapter.h" PN532_I2C pn532_i2c(Wire); NfcAdapter nfc = NfcAdapter(pn532_i2c); void setup(void) { Serial.begin(9600); Serial.println("NDEF Reader"); nfc.begin(); } void loop(void) { Serial.println("\nScan a NFC tag\n"); if (nfc.tagPresent()) { NfcTag tag = nfc.read(); //tag.print(); if(tag.hasNdefMessage()){ NdefMessage tagMessage = tag.getNdefMessage(); int i; for (i = 0; i < tagMessage.getRecordCount() ; i++) { // NdefRecord tagRecord = tagMessage.getRecord(i); tagRecord.print(); } } } delay(5000); } ``` Update readTag to fetch just the payload from the messages on the tag
```arduino #include "pn532_i2c_particle/pn532_i2c_particle.h" #include "pn532_i2c_particle/PN532.h" #include "pn532_i2c_particle/NfcAdapter.h" PN532_I2C pn532_i2c(Wire); NfcAdapter nfc = NfcAdapter(pn532_i2c); void setup(void) { Serial.begin(9600); Serial.println("NDEF Reader"); nfc.begin(); } void loop(void) { Serial.println("\nScan a NFC tag\n"); if (nfc.tagPresent()) { NfcTag tag = nfc.read(); if(tag.hasNdefMessage()){ NdefMessage tagMessage = tag.getNdefMessage(); int i; for (i = 0; i < tagMessage.getRecordCount() ; i++) { // NdefRecord tagRecord = tagMessage.getRecord(i); tagRecord.print(); } } } delay(5000); } ```
988af812-87a3-49af-8429-13fcf74a5a26
{ "language": "Arduino" }
```arduino #include "Wire.h" #include "SPI.h" #include "MINDS-i-Drone.h" #include "platforms/Quadcopter.h" void setup(){ calibrateESCs(); } void loop(){ output.stop(); } ``` Disable the output after calibrating instead of deprecated stop
```arduino #include "Wire.h" #include "SPI.h" #include "MINDS-i-Drone.h" #include "platforms/Quadcopter.h" void setup(){ calibrateESCs(); output.disable(); } void loop(){ } ```
0ad84d52-cc58-46cc-ae8c-c545ff26b7fa
{ "language": "Arduino" }
```arduino #include <M5Stack.h> // the setup routine runs once when M5Stack starts up void setup(){ // initialize the M5Stack object M5.begin(); // Lcd display M5.Lcd.println("This is software power off demo"); M5.Lcd.println("Press the button A to power off."); // Set the wakeup button M5.setWakeupButton(BUTTON_A_PIN); } // the loop routine runs over and over again forever void loop() { if(M5.BtnA.wasPressed()) { M5.powerOFF(); } M5.update(); } ``` Update poser off example for new api.
```arduino #include <M5Stack.h> // the setup routine runs once when M5Stack starts up void setup(){ // initialize the M5Stack object M5.begin(); // Lcd display M5.Lcd.println("This is software power off demo"); M5.Lcd.println("Press the button A to power off."); // Set the wakeup button M5.Power.setWakeupButton(BUTTON_A_PIN); } // the loop routine runs over and over again forever void loop() { if(M5.BtnA.wasPressed()) { M5.Power.deepSleep(); } M5.update(); } ```
d7c0ab36-fc1d-48c6-b0df-3a3ae0e0efc5
{ "language": "Arduino" }
```arduino #include "lcd.h" #include "sensor.h" void setup() { LCD::setup(); LCD::helloworld(); // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: } ``` Remove useless comments from ino
```arduino #include "lcd.h" #include "sensor.h" void setup() { LCD::setup(); LCD::helloworld(); } void loop() { } ```
d0901e5e-4ec8-4426-aaee-f961bd8d8d0f
{ "language": "Arduino" }
```arduino #include "receiver.h" Receiver rx1 = Receiver(2, 3, 4); Receiver rx2 = Receiver(2, 3, 5); Receiver rx3 = Receiver(2, 3, 6); Receiver rx4 = Receiver(2, 3, 7); void setup() { // Wait for modules to settle. delay(1000); // Set to race frequencies. rx1.setFrequency(5665); rx2.setFrequency(5745); rx3.setFrequency(5885); rx4.setFrequency(5945); } void loop() { // Do nothing. delay(1000); } ``` Add some delays between setting channels + flash LED
```arduino #include "receiver.h" Receiver rx1 = Receiver(2, 3, 4); Receiver rx2 = Receiver(2, 3, 5); Receiver rx3 = Receiver(2, 3, 6); Receiver rx4 = Receiver(2, 3, 7); void setup() { // Wait for modules to settle. delay(2000); // Set to race frequencies. rx1.setFrequency(5805); delay(500); rx2.setFrequency(5745); delay(500); rx3.setFrequency(5885); delay(500); rx4.setFrequency(5945); } void loop() { // Flash the LED. digitalWrite(13, HIGH); delay(1000); digitalWrite(13, LOW); delay(1000); } ```
b3836f75-3660-4b89-aa72-9251864af334
{ "language": "Arduino" }
```arduino #include "button.h" #include "led.h" #include "screen.h" #include "game.h" #include "clock.h" #include "const.h" #include "controller.h" #include "flasher.h" #include "logger.h" void setup() { Serial.begin(115200); //Attach interrupt for 64 button shield attachInterrupt(digitalPinToInterrupt(P_BUTTON_INTERRUPT), button_ISR, FALLING); //Generate new random seed randomSeed(analogRead(0)); led_setup(); flasher_setup(); clock_setup(); logger(LOGGER_TYPE_INFO, "main", "Setup done"); } void loop() { screen_display("READY"); led_setState(1, LED_STATE_FLASHING); button_wait(1); game_start(); } ``` Change flashing button to 0 from 1
```arduino #include "button.h" #include "led.h" #include "screen.h" #include "game.h" #include "clock.h" #include "const.h" #include "controller.h" #include "flasher.h" #include "logger.h" void setup() { Serial.begin(115200); //Attach interrupt for 64 button shield attachInterrupt(digitalPinToInterrupt(P_BUTTON_INTERRUPT), button_ISR, FALLING); //Generate new random seed randomSeed(analogRead(0)); led_setup(); flasher_setup(); clock_setup(); logger(LOGGER_TYPE_INFO, "main", "Setup done"); } void loop() { screen_display("READY"); led_setState(0, LED_STATE_FLASHING); button_wait(0); game_start(); } ```
87066902-3887-494a-a552-80e294e5de98
{ "language": "Arduino" }
```arduino #include "button.h" #include "led.h" #include "screen.h" #include "game.h" #include "timer.h" #include "const.h" #include "controller.h" #include "flasher.h" #include "logger.h" #include "helper.h" void setup() { Serial.begin(115200); //Generate new random seed randomSeed(analogRead(0)); //Setup button::setup(); led::setup(); flasher::setup(); timer::setup(); logger::log(logger::TYPE_INFO, "main", "Setup done"); } void loop() { screen::display("READY"); //Wait for center button to be pressed led::setState(0, led::STATE_FLASHING); button::wait(0); led::setState(0, led::STATE_OFF); //Start game game::start(); helper::waitTime(5000); } ``` Move main to setup to not repeat
```arduino #include "button.h" #include "led.h" #include "screen.h" #include "game.h" #include "timer.h" #include "const.h" #include "controller.h" #include "flasher.h" #include "logger.h" #include "helper.h" void setup() { Serial.begin(115200); //Generate new random seed randomSeed(analogRead(0)); //Setup button::setup(); led::setup(); flasher::setup(); timer::setup(); logger::log(logger::TYPE_INFO, "main", "Setup done"); screen::display("READY"); //Wait for center button to be pressed led::setState(0, led::STATE_FLASHING); button::wait(0); led::setState(0, led::STATE_OFF); //Start game game::start(); helper::waitTime(5000); } void loop() { } ```
73d766a0-93b5-4c01-b983-e58e5fd71e26
{ "language": "Arduino" }
```arduino /* Author: Andrea Stagi <[email protected]> Example: ReadAll Description: fetch all devices and relative temperatures on the wire bus on pin 5 and send them via serial port. */ #include <OneWire.h> #include <DSTemperature.h> DSTemperature ds(5); // on pin 5 void setup(void) { Serial.begin(9600); ds.begin(); } void sendAddress(DSAddress ds) { for(int i = 0 ; i < 8 ; i++) { Serial.print(ds.value[i], HEX); Serial.print(" "); } Serial.println(); } void loop(void) { for(int i = 0 ; i < ds.getDeviceCount() ; i++) { Serial.println("-------------------------------------------"); Serial.print("DEVICE ADDRESS: "); sendAddress(ds.getAddressFromIndex(i)); Serial.print("TEMPERATURE VALUE: "); Serial.print(ds.getCelsius(i)); Serial.println(" C"); } /* TODO: try to get index from 28 DA E5 D1 3 0 0 77 and 28 DA 19 0 0 0 20 32 */ } ``` Use ds_addr instead of ds
```arduino /* Author: Andrea Stagi <[email protected]> Example: ReadAll Description: fetch all devices and relative temperatures on the wire bus on pin 5 and send them via serial port. */ #include <OneWire.h> #include <DSTemperature.h> DSTemperature ds(5); // on pin 5 void setup(void) { Serial.begin(9600); ds.begin(); } void sendAddress(DSAddress ds_addr) { for(int i = 0 ; i < 8 ; i++) { Serial.print(ds_addr.value[i], HEX); Serial.print(" "); } Serial.println(); } void loop(void) { for(int i = 0 ; i < ds.getDeviceCount() ; i++) { Serial.println("-------------------------------------------"); Serial.print("DEVICE ADDRESS: "); sendAddress(ds.getAddressFromIndex(i)); Serial.print("TEMPERATURE VALUE: "); Serial.print(ds.getCelsius(i)); Serial.println(" C"); } /* TODO: try to get index from 28 DA E5 D1 3 0 0 77 and 28 DA 19 0 0 0 20 32 */ } ```
1e7a8815-7989-4ad5-9f0d-0ea97ced036c
{ "language": "Arduino" }
```arduino #include "Constants.h" #include "Display.h" #include "Buttons.h" Display display; Buttons buttons; unsigned long start_time = 0; void setup() { Serial.begin(9600); pinMode(13, OUTPUT); start_time = millis(); } void loop() { unsigned long current_time = millis() - start_time; display.displayTime( current_time / 1000 ); int button = buttons.get_button_press(); if ( button == BUTTON_RESTART ) { // reset the start time start_time = millis(); } } ``` Change code to count down instead of up
```arduino #include "Constants.h" #include "Display.h" #include "Buttons.h" Display display; Buttons buttons; unsigned long countdown_ends; unsigned long countdown_duration; void setup() { Serial.begin(9600); pinMode(13, OUTPUT); countdown_ends = 0; countdown_duration = 900000; // 15 mins in ms countdown_ends = millis() + countdown_duration; } void loop() { long time_remaining = countdown_ends - millis(); Serial.println(countdown_duration); display.displayTime( time_remaining / 1000 ); int button = buttons.get_button_press(); if ( button == BUTTON_RESTART ) { // reset the start time countdown_ends = millis() + countdown_duration + 500; } } ```
8015b864-9854-4aea-9383-8955d6f91710
{ "language": "Arduino" }
```arduino #include <ros.h> ros::NodeHandle nh; std_msgs::Float64 state; void callback(const std_msgs::Float64 cmd); { } ros::Publisher state_pub("state", &state); ros::Subscriber<std_msgs::Float64> cmd_sub("command", &callback); void setup() { nh.initNode(); nh.advertise(state_pub); } void loop() { nh.spinOnce(); state[0] = port_servo_pos; state[1] = stbd_servo_pos; state_pub.publish(&state); delay(33); } ``` Add i2c to thruster control sketch.
```arduino #include <Wire.h> #include <ros.h> #include <std_msgs/Int8.h> ros::NodeHandle nh; std_msgs::Int8 state; ros::Publisher state_pub("state", &state); void callback(const std_msgs::Int8 &cmd) { state.data = 0; state_pub.publish(&state); Wire.beginTransmission(3); Wire.write(0x10); Wire.write(0x10); Wire.write(0x10); Wire.endTransmission(); delay(5); Wire.beginTransmission(3); Wire.write(0x20); Wire.write(0x20); Wire.write(0x20); Wire.endTransmission(); delay(5); Wire.requestFrom(0x10, 4); while(Wire.available()) { char c = Wire.read(); state.data = c; state_pub.publish(&state); } } ros::Subscriber<std_msgs::Int8> cmd_sub("command", &callback); void setup() { Wire.begin(); nh.initNode(); nh.advertise(state_pub); } void loop() { nh.spinOnce(); delay(33); } ```
8761f629-95fa-4823-881f-84ee9f970301
{ "language": "Arduino" }
```arduino /** * Use this sketch to talk directly to the LoRa module. * * In Serial Monitor, select "Both NL & CR" and "9600 baud" in * the bottom right dropdowns and send command a command like: * * mac get deveui * sys reset */ #define loraSerial Serial1 #define debugSerial Serial void setup() { loraSerial.begin(57600); debugSerial.begin(9600); } void loop() { while (debugSerial.available()) { loraSerial.write(debugSerial.read()); } while (loraSerial.available()) { debugSerial.write(loraSerial.read()); } }``` Update pass through to work with Node
```arduino /** * Use this sketch to talk directly to the LoRa module. * * In Serial Monitor, select "Both NL & CR" and "115200 baud" in * the bottom right dropdowns and send command a command like: * * mac get deveui * sys reset */ #define loraSerial Serial1 #define debugSerial Serial void setup() { while(!debugSerial || !loraSerial); debugSerial.begin(115200); delay(1000); loraSerial.begin(57600); } void loop() { while (debugSerial.available()) { loraSerial.write(debugSerial.read()); } while (loraSerial.available()) { debugSerial.write(loraSerial.read()); } }```
6c501d79-a66f-4a8f-9f83-5983f68a8f18
{ "language": "Arduino" }
```arduino #include <M5Stack.h> // the setup routine runs once when M5Stack starts up void setup(){ // initialize the M5Stack object M5.begin(); // Lcd display M5.Lcd.println("This is software power off demo"); M5.Lcd.println("Press the button A to power off."); // Set the wakeup button M5.Power.setWakeupButton(BUTTON_A_PIN); } // the loop routine runs over and over again forever void loop() { if(M5.BtnA.wasPressed()) { M5.Power.deepSleep(); } M5.update(); } ``` Use powerOFF on powerOFF example
```arduino #include <M5Stack.h> // the setup routine runs once when M5Stack starts up void setup(){ // initialize the M5Stack object M5.begin(); // Lcd display M5.Lcd.println("This is software power off demo"); M5.Lcd.println("Press the button A to power off."); // Set the wakeup button M5.Power.setWakeupButton(BUTTON_A_PIN); } // the loop routine runs over and over again forever void loop() { if(M5.BtnA.wasPressed()) { M5.Power.powerOFF(); } M5.update(); } ```
bb71be24-3242-49bc-b7d3-3d73ca16cc25
{ "language": "Arduino" }
```arduino /* This example is basically the same as SimpleSerialPrinter but utilize the EnableInterrupt library. EnableInterrupt make pin change interrupts available and thus allows to use arbitrary pins. */ // EnableInterrupt from https://github.com/GreyGnome/EnableInterrupt // include it before RadiationWatch.h #include "EnableInterrupt.h" #include "RadiationWatch.h" // Use any pin as you like // Here: signPin = 5, noisePin = 6 RadiationWatch radiationWatch(5, 6); void onRadiation() { Serial.println("A wild gamma ray appeared"); Serial.print(radiationWatch.uSvh()); Serial.print(" uSv/h +/- "); Serial.println(radiationWatch.uSvhError()); } void onNoise() { Serial.println("Argh, noise, please stop moving"); } void setup() { Serial.begin(9600); radiationWatch.setup(); // Register the callbacks. radiationWatch.registerRadiationCallback(&onRadiation); radiationWatch.registerNoiseCallback(&onNoise); } void loop() { radiationWatch.loop(); } ``` Add link to EnableInterupt pin beastiary
```arduino /* This example is basically the same as SimpleSerialPrinter but utilize the EnableInterrupt library. The EnableInterrupt library make pin change interrupts available and thus allows to use arbitrary pins. See a list of pins supported here: https://github.com/GreyGnome/EnableInterrupt/wiki/Usage#pin--port-bestiary You can install the library from the Arduino Library Manager: http://www.arduinolibraries.info/libraries/enable-interrupt */ // EnableInterrupt from https://github.com/GreyGnome/EnableInterrupt // include it before RadiationWatch.h #include "EnableInterrupt.h" #include "RadiationWatch.h" // Use any pin as you like // Here: signPin = 5, noisePin = 6 RadiationWatch radiationWatch(5, 6); void onRadiation() { Serial.println("A wild gamma ray appeared"); Serial.print(radiationWatch.uSvh()); Serial.print(" uSv/h +/- "); Serial.println(radiationWatch.uSvhError()); } void onNoise() { Serial.println("Argh, noise, please stop moving"); } void setup() { Serial.begin(9600); radiationWatch.setup(); // Register the callbacks. radiationWatch.registerRadiationCallback(&onRadiation); radiationWatch.registerNoiseCallback(&onNoise); } void loop() { radiationWatch.loop(); } ```
947acf9c-5985-4132-b096-34749a4a6ef5
{ "language": "Arduino" }
```arduino #include "pn532_i2c_particle/pn532_i2c_particle.h" #include "pn532_i2c_particle/PN532.h" #include "pn532_i2c_particle/NfcAdapter.h" PN532_I2C pn532_i2c(Wire); NfcAdapter nfc = NfcAdapter(pn532_i2c); void setup(void) { Serial.begin(9600); Serial.println("NDEF Reader"); nfc.begin(); } void loop(void) { Serial.println("\nScan a NFC tag\n"); if (nfc.tagPresent()) { NfcTag tag = nfc.read(); //tag.print(); if(tag.hasNdefMessage()){ NdefMessage tagMessage = tag.getNdefMessage(); } } } delay(5000); } ``` Update readTag to fetch just the payload from the messages on the tag
```arduino #include "pn532_i2c_particle/pn532_i2c_particle.h" #include "pn532_i2c_particle/PN532.h" #include "pn532_i2c_particle/NfcAdapter.h" PN532_I2C pn532_i2c(Wire); NfcAdapter nfc = NfcAdapter(pn532_i2c); void setup(void) { Serial.begin(9600); Serial.println("NDEF Reader"); nfc.begin(); } void loop(void) { Serial.println("\nScan a NFC tag\n"); if (nfc.tagPresent()) { NfcTag tag = nfc.read(); //tag.print(); if(tag.hasNdefMessage()){ NdefMessage tagMessage = tag.getNdefMessage(); int i; for (i = 0; i < tagMessage.getRecordCount() ; i++) { // NdefRecord tagRecord = tagMessage.getRecord(i); tagRecord.print(); } } } delay(5000); } ```
d01d745a-5652-4c11-a20d-bcaa2d06f470
{ "language": "Arduino" }
```arduino #include <FastLED.h> #define WIDTH 16 #define HEIGHT 16 #define NUM_LEDS (WIDTH * HEIGHT) #define PIN 6 #define BAUD 115200 #define BRIGHTNESS 32 CRGB leds[NUM_LEDS]; int r, g, b; int x, y, yy; void setup() { FastLED.addLeds<WS2812B, PIN>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip); FastLED.setBrightness(BRIGHTNESS); Serial.begin(BAUD); FastLED.show(); } void loop() { Serial.write("R"); for (x = 0; x < WIDTH; x++) { for (y = 0; y < HEIGHT; y++) { while (Serial.available() < 3); r = Serial.read(); g = Serial.read(); b = Serial.read(); if (x % 2 == 0) { yy = HEIGHT - y - 1; } else { yy = y; } leds[yy + x * HEIGHT] = CRGB(g, r, b); // Seems to be running as GRB, not RGB } } FastLED.show(); } ``` Reduce led brightness to save my eyes.
```arduino #include <FastLED.h> #define WIDTH 16 #define HEIGHT 16 #define NUM_LEDS (WIDTH * HEIGHT) #define PIN 6 #define BAUD 115200 #define BRIGHTNESS 8 CRGB leds[NUM_LEDS]; int r, g, b; int x, y, yy; void setup() { FastLED.addLeds<WS2812B, PIN>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip); FastLED.setBrightness(BRIGHTNESS); Serial.begin(BAUD); FastLED.show(); } void loop() { Serial.write("R"); for (x = 0; x < WIDTH; x++) { for (y = 0; y < HEIGHT; y++) { while (Serial.available() < 3); r = Serial.read(); g = Serial.read(); b = Serial.read(); if (x % 2 == 0) { yy = HEIGHT - y - 1; } else { yy = y; } leds[yy + x * HEIGHT] = CRGB(g, r, b); // Seems to be running as GRB, not RGB } } FastLED.show(); } ```
ec19912b-7444-46eb-a664-96aff35f152f
{ "language": "Arduino" }
```arduino #include <MiniRobot.h> MiniRobot robot; void setup() { } void loop() { if (robot.leftEdge() && robot.distanceToEnemy() == 0) { robot.leftBack(); } else { robot.leftForward(); } if (robot.rightEdge() && robot.distanceToEnemy() == 0) { robot.rightBack(); } else { robot.rightForward(); } } ``` Use interrupt to IR sensors
```arduino #include <MiniRobot.h> MiniRobot robot; byte status = 2; /* 0 - don't need changes; 1 - counter only 2 - drive straight back; 3 - drive straight forward; 4 - spin around - enemy forward; */ int count = 0; void setup() { PCMSK1 |= bit(0) | bit(1); PCIFR |= bit(1); PCICR |= bit(1); pinMode(A0,INPUT); // set Pin as Input (default) digitalWrite(A0,HIGH); // enable pullup resistor pinMode(A1,INPUT); // set Pin as Input (default) digitalWrite(A1,HIGH); // enable pullup resistor } ISR (PCINT1_vect) { if (robot.leftEdge() || robot.rightEdge()) { status = 4; } } void loop() { switch (status) { case 1: count--; if (count <= 0) { status = 3; } break; case 2: robot.back(); count = 15; status = 1; break; case 3: robot.forward(); status = 0; break; case 4: robot.leftBack(); robot.rightForward(); count = 10; status = 1; break; } } ```
eff07b90-e17e-415f-80fa-a93f003f6567
{ "language": "Arduino" }
```arduino #include "Watering.h" void setup () { //Init serial connection Serial.begin(SERIAL_BAUD); //Init LED Pin pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); } void loop() { if ( Serial.available() ) { byte command = Serial.read(); switch( command ) { case WATER_LEVEL: break; case SUNLIGHT_LEVEL: break; case RELAY_ON: digitalWrite(LED_PIN, HIGH); break; case RELAY_OFF: digitalWrite(LED_PIN, LOW); break; default: break; } } }``` Send a response after the Arduino has completed its work.
```arduino #include "Watering.h" void setup () { //Init serial connection Serial.begin(SERIAL_BAUD); //Init LED Pin pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); } void loop() { if ( Serial.available() ) { byte command = Serial.read(); byte output[4]; byte numBytes = 0; switch( command ) { case WATER_LEVEL: break; case SUNLIGHT_LEVEL: break; case RELAY_ON: digitalWrite(LED_PIN, HIGH); // Prepping to send a response output[0] = command; output[1] = 0; numBytes = 2; break; case RELAY_OFF: digitalWrite(LED_PIN, LOW); // Prepping to send a response output[0] = command; output[1] = 0; numBytes = 2; break; default: break; } //Sending a response after the command has completed Serial.write(output, numBytes); } }```
8b3d03c4-0280-437e-ab79-961ab3aa4c54
{ "language": "Arduino" }
```arduino /* Pines of the first sensor. */ #define S1echo 7 #define S1trig 8 /* Pines of the second sensor. */ #define S2echo 10 #define S2trig 11 long duration, distance; void setup() { /* Setup of the echo & trig of everysensor. */ pinMode(S1echo, INPUT); //pinMode(S2echo, INPUT); pinMode(S1trig, OUTPUT); //pinMode(S2trig, OUTPUT); } void loop() { printReadings("Testing",0); estimateDistance(S1trig, S1echo); delayMicroseconds(1000); } void printReadings(String label, long value){ String phrase = label+": "+value; Serial.print(phrase); } /* Estimate the distance received from the ultrasonic sensor. */ int estimateDistance(int trig, int echo){ digitalWrite(trig,LOW); delayMicroseconds(2); digitalWrite(trig,HIGH); delayMicroseconds(10); digitalWrite(trig,LOW); //Claculate Duration of pulse. duration = pulseIn(echo,HIGH); printReadings("Duration", duration); //Distance in centimeters distance = duration/58.2; printReadings("Distance", distance); return distance; } ``` Change on Serial stuff to show data
```arduino /* Pines of the first sensor. */ #define S1echo 7 #define S1trig 8 /* Pines of the second sensor. */ #define S2echo 10 #define S2trig 11 long duration, distance; void setup() { Serial.begin(9600); /* Setup of the echo & trig of everysensor. */ pinMode(S1echo, INPUT); //pinMode(S2echo, INPUT); pinMode(S1trig, OUTPUT); //pinMode(S2trig, OUTPUT); } void loop() { printString("Testing"); estimateDistance(S1trig, S1echo); delay(10000); } void printReadings(String label, long value){ String phrase = label+": "+value; printString(phrase); } void printString(String phrase){ Serial.println(phrase); Serial.println(" "); } /* Estimate the distance received from the ultrasonic sensor. */ int estimateDistance(int trig, int echo){ digitalWrite(trig,LOW); delayMicroseconds(2); digitalWrite(trig,HIGH); delayMicroseconds(10); digitalWrite(trig,LOW); //Calculate Duration of pulse. duration = pulseIn(echo,HIGH); printReadings("Duration", duration); //Distance in centimeters distance = duration/58.2; printReadings("Distance", distance); return distance; } ```
5929f704-3ddf-40d7-9dd0-da7132368a1a
{ "language": "Arduino" }
```arduino /************************************************************** * 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 ordinary Arduino Serial * to connect your project to Blynk. * Feel free to apply it to any other example. It's simple! * ************************************************************** * USB HOWTO: http://tiny.cc/BlynkUSB **************************************************************/ #define BLYNK_PRINT Serial1 #include <BlynkSimpleSerial.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourAuthToken"; void setup() { // Debug prints on pins 39 (RX), 40 (TX) Serial1.begin(9600); // Blynk will work through Serial Serial.begin(9600); Blynk.begin(auth, Serial); } void loop() { Blynk.run(); } ``` Switch chipKIT UNO32 to use new Stream API
```arduino /************************************************************** * 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 ordinary Arduino Serial * to connect your project to Blynk. * Feel free to apply it to any other example. It's simple! * ************************************************************** * USB HOWTO: http://tiny.cc/BlynkUSB **************************************************************/ #define BLYNK_PRINT Serial1 #include <BlynkSimpleStream.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourAuthToken"; void setup() { // Debug prints on pins 39 (RX), 40 (TX) Serial1.begin(9600); // Blynk will work through Serial Serial.begin(9600); Blynk.begin(auth, Serial); } void loop() { Blynk.run(); } ```
3c9b7486-4dd5-477f-8f0e-093a47581127
{ "language": "Arduino" }
```arduino #include <Homie.h> const int doorPin = 16; Bounce debouncer = Bounce(); // Bounce is built into Homie, so you can use it without including it first unsigned long lastDoorValue = -1; HomieNode doorNode("door", "door"); void loopHandler() { int doorValue = debouncer.read(); if (doorValue != lastDoorValue) { Serial.print("Door is now: "); Serial.println(doorValue ? "open" : "close"); if (Homie.setNodeProperty(doorNode, "open", String(doorValue ? "true" : "false"), true)) { lastDoorValue = doorValue; } else { Serial.println("Sending failed"); } } } void setup() { pinMode(doorPin, INPUT); digitalWrite(doorPin, HIGH); debouncer.attach(doorPin); debouncer.interval(50); Homie.setFirmware("awesome-door", "1.0.0"); Homie.registerNode(doorNode); Homie.setLoopFunction(loopHandler); Homie.setup(); } void loop() { Homie.loop(); debouncer.update(); } ``` Fix caps in constant example
```arduino #include <Homie.h> const int PIN_DOOR = 16; Bounce debouncer = Bounce(); // Bounce is built into Homie, so you can use it without including it first unsigned long lastDoorValue = -1; HomieNode doorNode("door", "door"); void loopHandler() { int doorValue = debouncer.read(); if (doorValue != lastDoorValue) { Serial.print("Door is now: "); Serial.println(doorValue ? "open" : "close"); if (Homie.setNodeProperty(doorNode, "open", String(doorValue ? "true" : "false"), true)) { lastDoorValue = doorValue; } else { Serial.println("Sending failed"); } } } void setup() { pinMode(PIN_DOOR, INPUT); digitalWrite(PIN_DOOR, HIGH); debouncer.attach(PIN_DOOR); debouncer.interval(50); Homie.setFirmware("awesome-door", "1.0.0"); Homie.registerNode(doorNode); Homie.setLoopFunction(loopHandler); Homie.setup(); } void loop() { Homie.loop(); debouncer.update(); } ```
766ee8de-15ef-476c-8c9f-e64844c32f93
{ "language": "Arduino" }
```arduino // 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 } ``` Change to use automatic gain.
```arduino // 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 } ```
871262bf-f7e0-4066-b80c-8edb1858d5c5
{ "language": "Arduino" }
```arduino #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); } ``` Update SR04 example to new 5.0 API
```arduino #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); } ```
012040db-740e-4d99-931a-7d1e264ad63a
{ "language": "Arduino" }
```arduino 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(); } ``` Change baud rate to 9600.
```arduino 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(); } ```
45637e83-aa0e-468d-93d3-356f46f0f5f1
{ "language": "Arduino" }
```arduino #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 ``` Implement custom BMP data structure in program
```arduino #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 ```
026171c0-66a9-42d7-a540-2cfd5cd19759
{ "language": "Arduino" }
```arduino #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); } ``` Fix order of Serial.println arguments for HEX printing
```arduino #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); } ```
8ace0c3f-38ca-4875-8b8e-202c5759fff5
{ "language": "Arduino" }
```arduino // // 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); } ``` Update class name. ToDo: search slave address.
```arduino // // 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); } ```
684bbefe-251d-4144-8a3e-b8eee58a036d
{ "language": "Arduino" }
```arduino // This provides a variable, colour, a function to set the variable from a hex // string, set_colour, and programs the RGB LED on the spark core to reflect // the RRGGBB value last programmed. The default on reboot is black. // BEWARE: British spelling ahead! #include "spark-parse.h" static int colour = 0; int set_colour(String args) { // parse_hex only likes uppercase args.toUpperCase(); // Parse arg to colour settings int val = parse_hex(args); if (val != -1) { colour = val; } // Returns the value, if it took, or the previous colour setting, if // it didn't. return colour; } void setup() { RGB.control(true); Spark.function("set_colour", set_colour); Spark.variable("colour", &colour, INT); } void loop() { // Colour value is the standard RRGGBB layout, which we break up here. RGB.color((colour >> 16) & 255, (colour >> 8) & 255, colour & 255); } ``` Correct the include path to the one the Spark IDE wants
```arduino #include "spark-parse/spark-parse.h" // This provides a variable, colour, a function to set the variable from a hex // string, set_colour, and programs the RGB LED on the spark core to reflect // the RRGGBB value last programmed. The default on reboot is black. // BEWARE: British spelling ahead! static int colour = 0; int set_colour(String args) { // parse_hex only likes uppercase args.toUpperCase(); // Parse arg to colour settings int val = parse_hex(args); if (val != -1) { colour = val; } // Returns the value, if it took, or the previous colour setting, if // it didn't. return colour; } void setup() { RGB.control(true); Spark.function("set_colour", set_colour); Spark.variable("colour", &colour, INT); } void loop() { // Colour value is the standard RRGGBB layout, which we break up here. RGB.color((colour >> 16) & 255, (colour >> 8) & 255, colour & 255); } ```
84734ee8-5a09-4515-b209-5f543284ddcc
{ "language": "Arduino" }
```arduino /* 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); }``` Fix typo in string termination
```arduino /* 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); } ```
08ac8abd-b7e1-41fe-a5a4-f0034585711a
{ "language": "Arduino" }
```arduino 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); } ``` Update delay time for arduino button read
```arduino 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); } ```
1b654d92-9de5-4338-b6a1-4b1bc08dc4ce
{ "language": "Arduino" }
```arduino /* Battery indicator on the TFT screen. */ #include <ArduinoRobot.h> #include "RobotBattery.h" RobotBattery battery = RobotBattery(); int bat_val_prev = 0; void setup() { // initialize the robot Robot.begin(); // initialize the screen Robot.beginTFT(); // Black screen Robot.background(0,0,0); // Draw the battery icon with white edges. battery.beginIcon(255, 255, 255); } void loop() { int bat_val = battery.update(); if (bat_val != bat_val_prev) { bat_val_prev = bat_val; // Large number center screen // Clear Robot.stroke(0,0,0); Robot.textSize(3); Robot.text(bat_val_prev, 15, 50); // Write Robot.stroke(0,255,0); Robot.textSize(3); Robot.text(bat_val, 15, 50); Robot.textSize(2); Robot.text("mV", 92, 58); } delay(2000); } ``` Clear the text before setting the previous value
```arduino /* Battery indicator on the TFT screen. */ #include <ArduinoRobot.h> #include "RobotBattery.h" RobotBattery battery = RobotBattery(); int bat_val_prev = 0; void setup() { // initialize the robot Robot.begin(); // initialize the screen Robot.beginTFT(); // Black screen Robot.background(0,0,0); // Draw the battery icon with white edges. battery.beginIcon(255, 255, 255); } void loop() { int bat_val = battery.update(); if (bat_val != bat_val_prev) { // Large number center screen // Clear Robot.stroke(0,0,0); Robot.textSize(3); Robot.text(bat_val_prev, 15, 50); // Write Robot.stroke(0,255,0); Robot.textSize(3); Robot.text(bat_val, 15, 50); Robot.textSize(2); Robot.text("mV", 92, 58); bat_val_prev = bat_val; } delay(2000); } ```
c7b45266-6072-4af9-b1b8-e4a7971f3681
{ "language": "Arduino" }
```arduino //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); } } ``` Add sendData func and diagonalLines test pattern
```arduino //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() } ```
ffc00f07-8fdd-4d79-8ce7-f400002a7ec9
{ "language": "Arduino" }
```arduino // // 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 ); } } ``` Change the trigger frequency to 9Hz.
```arduino // // 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 ); } } ```
e3bd0aaa-c9bc-435e-84bf-ec2367baba17
{ "language": "Arduino" }
```arduino // 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 } } ``` Fix DEBUG compile flag issue
```arduino // 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 } } ```
0e500b18-715d-448e-80cb-9a61cac9369f
{ "language": "Arduino" }
```arduino /** * 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); } ``` Fix text shown on serial monitor.
```arduino /** * 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); } ```
4848dcbd-7203-4f01-8a43-e13aaff95bab
{ "language": "Arduino" }
```arduino /* 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(); } ``` Fix signature of callback function in subscriber example
```arduino /* 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(); } ```
0f219132-c9f9-4451-bb3c-d6c0f849ec37
{ "language": "Arduino" }
```arduino #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; } } ``` Update hallsensor code to reflect changes in wiring on breadboard using pullup resistor
```arduino #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; } } ```
0b6b81e9-82c4-4dcb-a9b4-1b42625df8bf
{ "language": "Arduino" }
```arduino #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); } ``` Add ability to input alt characters
```arduino #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); } ```
dfaaa3dd-538a-4056-a8db-6ad1c9c1eecd
{ "language": "Arduino" }
```arduino /** * 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); } } ``` Fix raw value output to serial terminal.
```arduino /** * 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()); } } ```
85f5247b-6fe1-46fc-a931-56846a863081
{ "language": "Arduino" }
```arduino void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: } ``` Add code for blinking LED on digital out 13
```arduino /* 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); } ```
94b59854-87d7-40d6-bead-92dce34dd4ff
{ "language": "Arduino" }
```arduino #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(); } ``` Use the sensor id as the identifier.
```arduino #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(); } ```
b8cdd9ab-c950-4b9c-bffa-c03c0d345506
{ "language": "Arduino" }
```arduino /* 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); }``` Remove blink code since unused here
```arduino /* 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); }```
b02f193a-f532-453b-89c7-d7e16975eed2
{ "language": "Arduino" }
```arduino #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); } ``` Set up the LCD pin
```arduino #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); } ```
dd7d6533-7465-450d-bc03-19aecdd167fa
{ "language": "Arduino" }
```arduino /* Controlling a servo position using a potentiometer (variable resistor) by Michal Rinott <http://people.interaction-ivrea.it/m.rinott> modified on 8 Nov 2013 by Scott Fitzgerald http://www.arduino.cc/en/Tutorial/Knob */ #include <Servo.h> Servo myservo; // create servo object to control a servo int potpin = 0; // analog pin used to connect the potentiometer int val; // variable to read the value from the analog pin void setup() { myservo.attach(9); // attaches the servo on pin 9 to the servo object } void loop() { val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023) val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180) myservo.write(val); // sets the servo position according to the scaled value delay(15); // waits for the servo to get there } ``` Modify pin 19's pin description for EVT board
```arduino /* 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 } ```
342b2ec8-5d31-4c4a-a91f-d0949e9b0228
{ "language": "Arduino" }
```arduino #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 } ``` Correct typo in setup/loop tuple
```arduino #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 } ```
4ac12e7c-337e-487b-b4b5-91b0908b92a2
{ "language": "Arduino" }
```arduino 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; }``` Add sound when button is held down
```arduino 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); } }```
69ab2f5a-283a-49c5-ad35-ff862133d6d1
{ "language": "Arduino" }
```arduino #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); } ``` Work on snow animation for three rings of tree
```arduino #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); } ```
aaed6260-0dce-4056-88fe-0f37952670f7
{ "language": "Arduino" }
```arduino #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(); } ``` Update pin numbers and load cell params
```arduino #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(); } ```
fd21b1ac-6f7c-48a9-9bf4-45764717db55
{ "language": "Arduino" }
```arduino #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 } ``` Tweak to code so it will use the builtin LED on any board
```arduino #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 } ```
4f9381b8-709e-4f03-b228-ede36aeacc1b
{ "language": "Arduino" }
```arduino #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); } } ``` Update arduino code to light 3 pixels at a time.
```arduino #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); } } ```
32d13407-8842-42fe-857c-b234ff250481
{ "language": "Arduino" }
```arduino #include <pins.h> #include <radio.h> #include <motor.h> #include <encoder.h> #include <control.h> void setup(void) { Serial.begin(115200); Radio::Setup(); Motor::Setup(); Encoder::Setup(); Control::acc = 0; } void loop(){ Control::stand(); } ``` Facilitate how to define which robot is being configured, on .ino now.
```arduino #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(); } ```
855d109a-7193-49da-8f65-0f267f996752
{ "language": "Arduino" }
```arduino 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); } } ``` Change t* vars from ints to floats
```arduino 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); } } ```
c09266d6-774a-4c35-9c39-50d9754477e2
{ "language": "Arduino" }
```arduino // 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 } } ``` Change to include Redbear Duo
```arduino // 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 } } ```
a52cb78d-4489-406f-8ad2-f7d4ea5c8cfd
{ "language": "Arduino" }
```arduino #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(); } ``` Update temperature example with more semantic topic
```arduino #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(); } ```
2c387ef5-e40e-4613-ac43-56471fcc3255
{ "language": "Arduino" }
```arduino #include "brotherKH930.h" void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: } ``` Add main to test the position logic.
```arduino #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(); } ```
1351cd44-4580-45ae-a1b3-0cf0d53f59ee
{ "language": "Arduino" }
```arduino #include <Arduino.h> #include "test_cpp_wrapper.h" void setup( ) { Serial.begin(BAUD_RATE); runalltests_cpp_wrapper(); } void loop( ) { }``` Fix missing SD begin in C++ Wrapper test
```arduino #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( ) { }```
d7321a55-de80-4793-9db5-49b40aba0b34
{ "language": "Arduino" }
```arduino /* 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); } ``` Use LED iso PIN to avoid confusion
```arduino /* 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); } ```
b75ec0e7-0668-4231-8de8-b92697517c6b
{ "language": "Arduino" }
```arduino /* ArcFour Entropy Seeding Demo created 10 Jun 2014 by Pascal de Bruijn */ #include <Entropy.h> #include <ArcFour.h> ArcFour ArcFour; int ledPin = 13; void setup() { Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo and Due } Entropy.Initialize(); ArcFour.initialize(); for (int i = 0; i < ARCFOUR_MAX; i++) { if (i / 4 % 2) digitalWrite(ledPin, LOW); else digitalWrite(ledPin, HIGH); ArcFour.seed(i, Entropy.random(WDT_RETURN_BYTE)); } ArcFour.finalize(); for (int i = 0; i < ARCFOUR_MAX; i++) { ArcFour.random(); } digitalWrite(ledPin, HIGH); } void loop() { Serial.println(ArcFour.random()); delay(1000); } ``` Update for new Entropy API
```arduino /* 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); } ```
a0f867c0-8585-4e5d-9075-170b258d2e38
{ "language": "Arduino" }
```arduino // 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); } }``` Update to tested and working code
```arduino // 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()); } ```
f88aa3a6-4271-4a05-9f3a-d9bbee984294
{ "language": "Arduino" }
```arduino #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(); } ``` Use Arduino101 CurieIMU new APIs.
```arduino #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(); } ```
a5fa4489-0f15-4ac5-ad52-2c21a885273a
{ "language": "Arduino" }
```arduino #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() { } ``` Split motor definitions into multiple lines
```arduino #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() { } ```
a29b351b-2c25-4242-ae97-916b6f6eedb8
{ "language": "Arduino" }
```arduino // 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 } } ``` Update for Particle Core and Photon
```arduino // 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 } } ```
4fc89a9b-5cec-4864-b355-a7a84ce49d3b
{ "language": "Arduino" }
```arduino #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); } ``` Adjust max sensor distance to something more suitable
```arduino #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); } ```
7574bd02-da60-4e64-a9e0-64752e985bc9
{ "language": "Arduino" }
```arduino #include <SoftwareSerial.h> // Serial speed #define SERIAL_BAUDRATE 9600 #define LIGHTSENSOR_PIN 3 #define FETCH_INTERVAL 100 #define POST_INTERVAL 5000 const int numLedSamples = POST_INTERVAL / FETCH_INTERVAL; int ledSamples[numLedSamples]; int ledSampleCounter = 0; int light = 0; // Software serial for XBee module SoftwareSerial xbeeSerial(2, 3); // RX, TX void setup() { Serial.begin(SERIAL_BAUDRATE); xbeeSerial.begin(SERIAL_BAUDRATE); } void loop() { readLightsensor(); if (ledSampleCounter >= numLedSamples) sendLightData(); delay(FETCH_INTERVAL); } void readLightsensor() { int sample = analogRead(LIGHTSENSOR_PIN); Serial.print("d:");Serial.println(sample); ledSamples[ledSampleCounter] = sample; ledSampleCounter++; } void sendLightData() { float avg = 0.0f; for (int i = 0; i < numLedSamples; i++) avg += ledSamples[i]; avg /= numLedSamples; xbeeSerial.print("l=");xbeeSerial.println(avg); ledSampleCounter = 0; } ``` Implement LED data as ringbuffer.
```arduino #include <SoftwareSerial.h> // Serial speed #define SERIAL_BAUDRATE 9600 #define LIGHTSENSOR_PIN 3 #define FETCH_INTERVAL 100 #define POST_INTERVAL 5000 const int numLedSamples = POST_INTERVAL / FETCH_INTERVAL; int ledSamples[numLedSamples]; int ledSampleCounter = 0; int light = 0; // Software serial for XBee module SoftwareSerial xbeeSerial(2, 3); // RX, TX void setup() { Serial.begin(SERIAL_BAUDRATE); xbeeSerial.begin(SERIAL_BAUDRATE); } void loop() { readLightsensor(); if (ledSampleCounter >= numLedSamples) sendLightData(); delay(FETCH_INTERVAL); } void readLightsensor() { ledSamples[ledSampleCounter] = analogRead(LIGHTSENSOR_PIN); ledSampleCounter++; ledSampleCounter %= numLedSamples; } void sendLightData() { float avg = 0.0f; for (int i = 0; i < numLedSamples; i++) avg += ledSamples[i]; avg /= numLedSamples; xbeeSerial.print("l=");xbeeSerial.println(avg); } ```
80b85718-eda9-4126-afae-b1741b9cc637
{ "language": "Arduino" }
```arduino ``` Add main MIDI controller sketch
```arduino #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. } ```
ba2fc078-9a11-4bdb-9b27-e1f9cf28a299
{ "language": "Arduino" }
```arduino ``` Add example with no devices
```arduino /****************************************************************** Example starting point sketch for ParticleIoT library This example contains no devices. It is provided for comparison with other example sketches. http://www.github.com/rlisle/ParticleIoT Written by Ron Lisle BSD license, check LICENSE for more information. All text above must be included in any redistribution. Changelog: 2017-03-11: Initial creation ******************************************************************/ /****************/ /*** INCLUDES ***/ /****************/ #include <IoT.h> /*****************/ /*** VARIABLES ***/ /*****************/ IoT *iot; /*************/ /*** SETUP ***/ /*************/ void setup() { iot = IoT::getInstance(); iot->setControllerName("lislerv"); iot->setPublishName("RonTest"); iot->begin(); } /************/ /*** LOOP ***/ /************/ void loop() { long currentMillis = millis(); iot->loop(currentMillis); } ```
c8e1d817-b952-41c4-815b-1bd72e471607
{ "language": "Arduino" }
```arduino ``` Add a sort of intensity wave option
```arduino #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++; } } } ```
c68ef062-4ee8-41b1-9339-26e05edcb084
{ "language": "Arduino" }
```arduino ``` Add v0.2.0 conditioning Arduino source
```arduino #include "AES.h" #include "CBC.h" #define CHAIN_SIZE 2 #define BLOCK_SIZE 16 #define SAMPLE_SIZE (BLOCK_SIZE * CHAIN_SIZE) byte key[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}; CBC<AES128> cbc; byte sourcePool[SAMPLE_SIZE]; void setup() { Serial.begin(115200); //Set B pins to input DDRB = B00000000; delay(1000); } void loop() { static byte currentByte = 0x00; byte pinVal = (PINB >> 3) & B00000001; boolean byteReady = collectBit(pinVal, &currentByte); if (byteReady){ //Serial.println("ByteCollected"); boolean poolFull = collectByte(currentByte); if (poolFull){ conditionPool(); //Serial.write(sourcePool, SAMPLE_SIZE); } currentByte = 0; } } //@return true if byte is full/complete boolean collectBit(byte inputBit, byte *currentByte){ static int bitCounter = 0; *currentByte |= inputBit << bitCounter; bitCounter = ++bitCounter % 8; if (bitCounter == 0) { return true; } return false; } //@return true if sourcePool is full boolean collectByte(byte currentByte){ static int byteCount = 0; sourcePool[byteCount] = currentByte; byteCount = ++byteCount % SAMPLE_SIZE; //Serial.println(byteCount); if (byteCount == 0){ return true; } return false; } //TODO: this should return encrypted pool, and mac should //be sent in the calling function void conditionPool(){ //Serial.println("Conditioning"); static byte iv[BLOCK_SIZE] = {0}; byte output[SAMPLE_SIZE]; cbc.clear(); cbc.setKey(key, 16); cbc.setIV(iv, 16); cbc.encrypt(output, sourcePool, SAMPLE_SIZE); //advance pointer to last block (the MAC) byte *outBuf = &output[SAMPLE_SIZE - BLOCK_SIZE]; Serial.write(outBuf, BLOCK_SIZE); } ```
9287f07f-0136-4bd2-b43e-67550200a76b
{ "language": "Arduino" }
```arduino ``` Add boilerplate .ino to implement the baro sensor
```arduino #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); }```
c0a0756a-4544-46c8-aa57-85b6de4c37ba
{ "language": "Arduino" }
```arduino ``` Add sample for simple bluetooth data.
```arduino #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); } } } ```
d0a46676-3723-4578-a2c7-7911dd4f04ba
{ "language": "Arduino" }
```arduino ``` Add arduino code to run interface to robot.
```arduino #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 ```
014107c5-d2b8-43c3-8cd9-de36c8084f4a
{ "language": "Arduino" }
```arduino ``` Add CC3000 Firmware update Sketch
```arduino /* 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]); } ```
daec62a9-3e44-4e38-ad5c-98a17ae7504a
{ "language": "Arduino" }
```arduino ``` Add test sketch (to be removed).
```arduino #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(); } ```
0fd4695e-31db-4235-aa0a-177fc3198ecc
{ "language": "Arduino" }
```arduino ``` Backup of Working Slave Code
```arduino /* * 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); } ```