doc_id
stringlengths
36
36
metadata
dict
input
stringlengths
28
4.3k
output
stringlengths
11
5.45k
7e23224c-0b21-41f5-9b5d-60dd4a3990a5
{ "language": "Arduino" }
```arduino ``` Add example to list all addresses where a device is present.
```arduino #include <SoftWire.h> #include <AsyncDelay.h> SoftWire sw(SDA, SCL); void setup(void) { Serial.begin(9600); sw.setTimeout_ms(40); sw.begin(); pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, LOW); // Set how long we are willing to wait for a device to respond sw.setTimeout_ms(200); const uint8_t firstAddr = 1; const uint8_t lastAddr = 0x7F; Serial.println(); Serial.print("Interrogating all addresses in range 0x"); Serial.print(firstAddr, HEX); Serial.print(" - 0x"); Serial.print(lastAddr, HEX); Serial.println(" (inclusive) ..."); for (uint8_t addr = firstAddr; addr <= lastAddr; addr++) { digitalWrite(LED_BUILTIN, HIGH); delayMicroseconds(10); uint8_t startResult = sw.llStart((addr << 1) + 1); // Signal a read sw.stop(); if (startResult == 0) { Serial.print("\rDevice found at 0x"); Serial.println(addr, HEX); Serial.flush(); } digitalWrite(LED_BUILTIN, LOW); delay(50); } Serial.println("Finished"); } void loop(void) { ; } ```
1e1474b5-aa97-4fca-9fdb-438ff6d192cd
{ "language": "Arduino" }
```arduino ``` Add new starting payload program
```arduino #include <Wire.h> #include "Adafruit_BMP085.h" /* * BMP180 setup instructions: * ---------------------------------------- * Connect BMP180 V-in to 3.3V (NOT 5.0V) * Connect BMP180 GND to Ground * Connect BMP180 SCL to Analog 5 * Connect BMP180 SDA to Analog 4 * ---------------------------------------- */ Adafruit_BMP085 barometer; void setup() { Serial.begin(9600); // 9600 bits/second if (!barometer.begin()) { Serial.println("No BMP085 sensor found."); while (1) { /* Trap the thread. */ } } } void printBaroData() { // Get temperature. Serial.print("Temperature = "); Serial.print(barometer.readTemperature()); Serial.println(" *C"); // Get pressure at sensor. Serial.print("Pressure = "); Serial.print(barometer.readPressure()); Serial.println(" Pa"); // Calculate pressure at 0 MSL. (0 meters mean sea-level) Serial.print("Calculated pressure at 0 MSL = "); Serial.print(barometer.readSealevelPressure()); Serial.println(" Pa"); // Get pressure altitude: // altitude with (default) altimeter setting at 101325 Pascals == 1013.25 millibars // == 29.92 inches mercury (i.e., std. pressure) Serial.print("Pressure altitude = "); Serial.print(barometer.readAltitude()); Serial.println(" meters"); // TODO: // Density altitude: pressure altitude corrected for nonstandard temperature // High density altitude (High, Hot, and Humid) means decreased performance. // Get indicated altitude: // pressure altitude corrected for non-standard pressure, with altimeter // setting 1015 millibars == 101500 Pascals // For pressure conversions, visit NOAA at: https://www.weather.gov/media/epz/wxcalc/pressureConversion.pdf. Serial.print("Indicated altitude = "); Serial.print(barometer.readAltitude(101500)); Serial.println(" meters"); Serial.println(); } void loop() { printBaroData(); delay(350); } ```
5070d7dc-c43a-4ae0-ba16-1d5af8327c56
{ "language": "Arduino" }
```arduino ``` Add HTTP POST for Arduino Yun.
```arduino /* Yún HTTP Client This example for the Arduino Yún shows how create a basic HTTP client that connects to the internet and downloads content. In this case, you'll connect to the Arduino website and download a version of the logo as ASCII text. created by Tom igoe May 2013 This example code is in the public domain. http://www.arduino.cc/en/Tutorial/HttpClient */ #include <Bridge.h> #include <HttpClient.h> const char* msg = "{\"id\":\"1\",\"type\":\"room\",\"reserved\":false,\"temperature\":10,\"light\":10,\"dioxide\":10,\"noise\":10}"; void setup() { // Bridge takes about two seconds to start up // it can be helpful to use the on-board LED // as an indicator for when it has initialized pinMode(13, OUTPUT); digitalWrite(13, LOW); Bridge.begin(); digitalWrite(13, HIGH); Serial.begin(9600); while (!Serial); // wait for a serial connection } void loop() { // Initialize the client library HttpClient client; client.setHeader("Content-Type: text/plain"); // Make a HTTP request: client.post("rubix.futurice.com/messages", msg); // if there are incoming bytes available // from the server, read them and print them: while (client.available()) { char c = client.read(); Serial.print(c); } Serial.flush(); delay(5000); } ```
59a6b813-f223-42aa-a7d4-27c6c36d199d
{ "language": "Arduino" }
```arduino ``` Add the Arduino sketch for reading and remembering key numbers. Doesn't build with ino atm.
```arduino #include <OneWire.h> #include <EEPROM.h> // This is the pin with the 1-Wire bus on it OneWire ds(PIN_D0); // unique serial number read from the key byte addr[8]; // poll delay (I think 750ms is a magic number for iButton) int del = 1000; // Teensy 2.0 has an LED on port 11 int ledpin = 11; // number of values stored in EEPROM byte n = 0; void setup() { Serial.begin(9600); // wait for serial pinMode(ledpin, OUTPUT); digitalWrite(ledpin, HIGH); while (!Serial.dtr()) {}; digitalWrite(ledpin, LOW); // Dump EEPROM to serial n = EEPROM.read(0); Serial.print(n, DEC); Serial.println(" keys stored:"); int i, j; for(i=0; i<n; i++) { for(j=0; j<8; j++) { Serial.print(EEPROM.read(1 + (8 * i) + j), HEX); Serial.print(" "); } Serial.println(""); } } void loop() { byte result; // search looks through all devices on the bus ds.reset_search(); if(result = !ds.search(addr)) { // Serial.println("Scanning..."); } else if(OneWire::crc8(addr, 7) != addr[7]) { Serial.println("Invalid CRC"); delay(del); return; } else { EEPROM.write(0, n++); Serial.print("Storing key "); Serial.println(n, DEC); for(byte i=0; i<8; i++) { Serial.print(addr[i], HEX); EEPROM.write(1 + (8 * n) + i, addr[i]); Serial.print(" "); } Serial.print("\n"); digitalWrite(ledpin, HIGH); delay(1000); digitalWrite(ledpin, LOW); } delay(del); return; } ```
b5794573-868c-4d47-8c22-b4782488c800
{ "language": "Arduino" }
```arduino ``` Test program for PIR module
```arduino /**************************************************************************** PIRsensor : test program for PIR sensor module Author: Enrico Formenti Permissions: MIT licence Remarks: - OUT pin is connected to digital pin 2 of Arduino, change this if needed - DELAY times depend on the type of module and/or its configuration. *****************************************************************************/ #include <Serial.h> #include <PIR.h> // OUT pin on PIR sensor connected to digital pin 2 // (any other digital pin will do, just change the value below) #define PIRSensorPin 2 PIR myPIR(PIRSensorPin); void setup() { myPIR.begin(); } void loop() { if(myPIR.getStatus()) { Serial.println("Movement detected"); // do something else at least for the delay between two seccessive // readings delay(myPIR.getDurationDelay()); } else Serial.println("Nothing being detected..."); } ```
dee8bbb4-4538-4d9d-a1c9-52c6191afd7e
{ "language": "Arduino" }
```arduino ``` Add arduino code to work with the serial_test
```arduino /*************************************************** Simple serial server ****************************************************/ //serial String inputString = ""; // a string to hold incoming data boolean stringComplete = false; // whether the string is complete void setup(){ //delay(100); //wait for bus to stabalise // serial Serial.begin(9600); // reserve 200 bytes for the inputString: inputString.reserve(200); } void loop(){ // print the string when a newline arrives: if (stringComplete) { Serial.println(inputString); // clear the string: inputString = ""; stringComplete = false; } } /* SerialEvent occurs whenever a new data comes in the hardware serial RX. This routine is run between each time loop() runs, so using delay inside loop can delay response. Multiple bytes of data may be available. */ void serialEvent() { while (Serial.available()) { // get the new byte: char inChar = (char)Serial.read(); // add it to the inputString: inputString += inChar; // if the incoming character is a newline, set a flag // so the main loop can do something about it: if (inChar == '\n') { stringComplete = true; } } } ```
9e8d6efa-5575-43f3-8cd8-e4e5b6c2faf2
{ "language": "Arduino" }
```arduino ``` Add next Arduino example - blinky with Timer1 OVF.
```arduino /** * Copyright (c) 2019, Łukasz Marcin Podkalicki <[email protected]> * ArduinoUno/001 * Blinky with timer1 OVF. */ #define LED_PIN (13) #define TIMER_TCNT (57723) // 65536 - 16MHz/1024/2 void setup() { pinMode(LED_PIN, OUTPUT); // set LED pin as output TCCR1A = 0; TCCR1B = _BV(CS12)|_BV(CS10); // set Timer1 prescaler to 1024 TIMSK1 |= _BV(TOIE1); // enable Timer1 overflow interrupt TCNT1 = TIMER_TCNT; // reload timer counter } void loop() { // do nothing } ISR(TIMER1_OVF_vect) { TCNT1 = TIMER_TCNT; // reload timer counter digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle LED pin } ```
a6c20a9f-c382-4113-8370-025c75088f47
{ "language": "Arduino" }
```arduino ``` Add basic GA1A12S202 light sensor Arduino testbed.
```arduino """ @author: Sze 'Ron' Chau @source: https://github.com/wodiesan/senior_design_spring @Desc: Adafruit Analog Light Sensor, modified by Ron Chau. 1. Connect sensor output to Analog Pin 0 2. Connect 5v to VCC and GND to GND 3. Connect 3.3v to the AREF pin """ int led1 = 2; // LED connected to digital pin 2 int led2 = 3; // LED connected to digital pin 3 int led3 = 4; // LED connected to digital pin 4 int sensorPin = A0; // select the input pin for the potentiometer float rawRange = 1024; // 3.3v float logRange = 5.0; // 3.3v = 10^5 lux // Random value chosen to test light sensing feature. float lightLimit = 600; void setup() { analogReference(EXTERNAL); // Serial.begin(9600); Serial.println("Adafruit Analog Light Sensor Test"); //LEF pins pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); pinMode(led3, OUTPUT); } void loop() { // read the raw value from the sensor: int rawValue = analogRead(sensorPin); Serial.print("Raw = "); Serial.print(rawValue); Serial.print(" - Lux = "); Serial.println(RawToLux(rawValue)); // LEDS on if rawValue greater or equal. if(rawValue <= 400){ digitalWrite(led1, HIGH); // LED on digitalWrite(led2, HIGH); digitalWrite(led3, HIGH); } else{ digitalWrite(led1, LOW); // LEDs off digitalWrite(led2, LOW); digitalWrite(led3, LOW); } delay(1000); } float RawToLux(int raw) { float logLux = raw * logRange / rawRange; return pow(10, logLux); }```
39d695ec-9c3a-4cd2-a896-248c09201e04
{ "language": "Arduino" }
```arduino ``` Print all virtual data example
```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 sketch prints all virtual pin operations! * **************************************************************/ #define BLYNK_PRINT Serial #include <SPI.h> #include <Ethernet.h> #include <BlynkSimpleEthernet.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourAuthToken"; void setup() { Serial.begin(9600); // See the connection status in Serial Monitor Blynk.begin(auth); } // This is called for all virtual pins, that don't have BLYNK_WRITE handler BLYNK_WRITE_DEFAULT() { BLYNK_LOG("V%d input: ", request.pin); // Print all parameter values for (auto i = param.begin(); i < param.end(); ++i) { BLYNK_LOG("* %s", i.asString()); } } // This is called for all virtual pins, that don't have BLYNK_READ handler BLYNK_READ_DEFAULT() { // Generate random response int val = random(0, 100); BLYNK_LOG("V%d output: %d", request.pin, val); Blynk.virtualWrite(request.pin, val); } void loop() { Blynk.run(); } ```
9603150a-32fa-4a58-ac59-d6e663e9d82d
{ "language": "Arduino" }
```arduino ``` Add tests for web client
```arduino // Demo using DHCP and DNS to perform a web client request. // 2011-06-08 <[email protected]> http://opensource.org/licenses/mit-license.php #include <EtherCard.h> // ethernet interface mac address, must be unique on the LAN static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 }; byte Ethernet::buffer[600]; static uint32_t timer; const char website[] PROGMEM = "www.sweeparis.com"; // called when the client request is complete static void my_callback (byte status, word off, word len) { Serial.println(">>>"); Serial.print(off);Serial.print("/");Serial.print(len);Serial.print(">>>"); Ethernet::buffer[min(699, off + len)] = 0; Serial.print((const char*) Ethernet::buffer + off); Serial.println("..."); } void setup () { Serial.begin(57600); Serial.println(F("\n[webClient]")); if (ether.begin(sizeof Ethernet::buffer, mymac) == 0) Serial.println(F("Failed to access Ethernet controller")); if (!ether.dhcpSetup()) Serial.println(F("DHCP failed")); ether.printIp("IP: ", ether.myip); ether.printIp("GW: ", ether.gwip); ether.printIp("DNS: ", ether.dnsip); if (!ether.dnsLookup(website)) Serial.println("DNS failed"); ether.printIp("SRV: ", ether.hisip); } void loop () { ether.packetLoop(ether.packetReceive()); delay(100); if (millis() > timer) { timer = millis() + 10000; Serial.println(); Serial.print("<<< REQ "); ether.browseUrl(PSTR("/riot-server/"), "", website, my_callback); } } ```
4a5a511e-4c23-443c-915d-4015e649c917
{ "language": "Arduino" }
```arduino ``` Add example of setbaud and findbaud
```arduino /* * findBaudTest - Test all supported baud settings * * The progress and results are printed to Serial, so open the 'Serial * Montitor'. * * The progress and results will be easier to read if you disable the * debugging (comment out or delete the "#define DEBUG_HC05" line in * HC05.h. */ #include <Arduino.h> #include "HC05.h" #ifdef HC05_SOFTWARE_SERIAL #include <SoftwareSerial.h> HC05 btSerial = HC05(A2, A5, A3, A4); // cmd, state, rx, tx #else HC05 btSerial = HC05(3, 2); // cmd, state #endif void setup() { DEBUG_BEGIN(57600); Serial.begin(57600); btSerial.findBaud(); btSerial.setBaud(4800); Serial.println("---------- Starting test ----------"); } void loop() { int numTests = 0; int failed = 0; unsigned long rate = 0; unsigned long rates[] = {4800,9600,19200,38400,57600,115200}; for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { numTests++; Serial.print(rates[i]); btSerial.setBaud(rates[i]); rate = btSerial.findBaud(); if (rate != rates[i]) { Serial.print(" FAILED: found rate "); Serial.println(rate); failed++; } else { Serial.print("->"); Serial.print(rates[j]); btSerial.setBaud(rates[j]); rate = btSerial.findBaud(); if (rate != rates[j]) { Serial.print("FAILED: found rate "); Serial.println(rate); failed++; } else { Serial.println(" PASSED"); } } } } Serial.println("--------- Tests Complete ----------"); Serial.print("Results: "); Serial.print(failed); Serial.print(" of "); Serial.print(numTests); Serial.println(" tests failed."); while (true) { ; } } ```
66231d57-3082-4587-b813-42e1d18bc3c5
{ "language": "Arduino" }
```arduino ``` Add simple program that sets the first recived byte by BLE and write in the pot
```arduino /* Digital Potentiometer control over BLE MCP4110 digital Pots SPI interface */ // inslude the SPI library: #include <SPI.h> #include <SoftwareSerial.h> SoftwareSerial bleSerial(2, 3); // RX, TX // set pot select pin const int potSS = 10; //const int potWriteCmd = B00100011; const int potWriteCmd = B00010011; void setup() { // set output pins: pinMode(potSS, OUTPUT); // initialize SPI: SPI.begin(); //initialize serial port for logs Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } bleSerial.begin(9600); // digitalPotWrite(0); } void loop() { // //test // digitalPotWrite(pot1SS,36); // delay(100); // Wire.readByte(); if (bleSerial.available()) { int val = bleSerial.read(); Serial.write("value = "); Serial.print(val,DEC); digitalPotWrite(val); } if (Serial.available()) { bleSerial.write(Serial.read()); } } void digitalPotWrite(int value) { // put the SS pin to low in order to select the chip: digitalWrite(potSS, LOW); SPI.transfer(potWriteCmd); SPI.transfer(value); // put the SS pin to high for transfering the data digitalWrite(potSS, HIGH); } ```
48181020-ff8e-4afd-8f6d-12c77b1a51fe
{ "language": "Arduino" }
```arduino ``` Add GSM Serial for testing AT Command
```arduino #include <SoftwareSerial.h> SoftwareSerial SSerial(10, 11); void setup(void) { Serial.begin(9600); SSerial.begin(9600); } void loop(void) { if (Serial.available() > 0) { SSerial.write(Serial.read()); } if (SSerial.available() > 0) { Serial.write(SSerial.read()); } } ```
634562a9-f372-4799-b2fe-e460119001ca
{ "language": "Arduino" }
```arduino ``` Add sketch to verify Watchdog/RTC::since() behavior.
```arduino /** * @file CosaSince.ino * @version 1.0 * * @section License * Copyright (C) 2015, Mikael Patel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * @section Description * Verify Watchdog::since() and RTC::since() wrap-around behavior. * * This file is part of the Arduino Che Cosa project. */ #include "Cosa/RTC.hh" #include "Cosa/Trace.hh" #include "Cosa/Watchdog.hh" #include "Cosa/OutputPin.hh" #include "Cosa/IOStream/Driver/UART.hh" OutputPin led(Board::LED); // Start time in milli-seconds const uint32_t START = 0xfffff000UL; void setup() { uart.begin(9600); trace.begin(&uart, PSTR("CosaSince: started")); trace.flush(); // Start timers. Use RTC::delay() Watchdog::begin(); RTC::begin(); // Set timers to the start time Watchdog::millis(START); RTC::millis(START); } void loop() { led.on(); uint32_t rms = RTC::millis(); uint32_t wms = Watchdog::millis(); uint32_t wsd = Watchdog::since(START); uint32_t rsd = RTC::since(START); int32_t diff = wsd - rsd; trace << RTC::seconds() << ':' << rms << ':' << wms << ':' << rsd << ':' << wsd << ':' << diff << ':' << diff / Watchdog::ms_per_tick() << endl; delay(1000 - RTC::since(rms)); led.off(); delay(1000); } ```
2dd1d62e-1c8a-4f64-b6ca-7ae05809dd36
{ "language": "Arduino" }
```arduino ``` Add example of Iot device that posts to data.sparkfun.com
```arduino #include "DHT.h" #define DHTPIN 2 // what pin we're connected to // Uncomment whatever type you're using! #define DHTTYPE DHT11 // DHT 11 //#define DHTTYPE DHT22 // DHT 22 (AM2302) //#define DHTTYPE DHT21 // DHT 21 (AM2301) // Connect pin 1 (on the left) of the sensor to +5V // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1 // to 3.3V instead of 5V! // Connect pin 2 of the sensor to whatever your DHTPIN is // Connect pin 4 (on the right) of the sensor to GROUND // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor // Initialize DHT sensor for normal 16mhz Arduino DHT dht(DHTPIN, DHTTYPE); // Phant arduino lib // git clone https://github.com/sparkfun/phant-arduino ~/sketchbook/libraries/Phant #include <Phant.h> // Arduino example stream // http://data.sparkfun.com/streams/VGb2Y1jD4VIxjX3x196z // hostname, public key, private key Phant phant("data.sparkfun.com", "VGb2Y1jD4VIxjX3x196z", "9YBaDk6yeMtNErDNq4YM"); #include <EtherCard.h> byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 }; byte Ethernet::buffer[700]; Stash stash; const char website[] PROGMEM = "google.com"; void setup() { Serial.begin(9600); dht.begin(); if (ether.begin(sizeof Ethernet::buffer, mymac) == 0) Serial.println(F("Failed to access Ethernet controller")); if (!ether.dhcpSetup()) Serial.println(F("DHCP failed")); ether.printIp("IP: ", ether.myip); ether.printIp("GW: ", ether.gwip); ether.printIp("DNS: ", ether.dnsip); if (!ether.dnsLookup(website)) Serial.println(F("DNS failed")); Serial.println("Setup completed"); } void loop() { // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) float h = dht.readHumidity(); // Read temperature as Celsius float t = dht.readTemperature(); phant.add("humidity", h); phant.add("temperature", t); Serial.println("Sending data..."); byte sd = stash.create(); stash.println(phant.post()); stash.save(); ether.tcpSend(); // Wait a few seconds between measurements. delay(10000); } ```
cc6d61b6-e904-4dfe-b919-c3891cae7ea6
{ "language": "Arduino" }
```arduino ``` Test input values by displaying in the serial monitor
```arduino //Skript for testing the input-values of the arduino by displaying values in the serial monitor int delayTime = 4000; int buttonState = 0; int piezo = A0; int photo = A1; int poti = A2; int switchBtn = 11; int buttonBtn = 12; int extFlash = 8; int camTrigger = 9; int camFocus = 10; int piezoValue = 0; int photoValue = 0; int potiValue = 0; int btnState = 0; int switchState = 0; void setup() { Serial.begin(9600); pinMode(piezo, INPUT); pinMode(photo, INPUT); pinMode(poti, INPUT); pinMode(switchBtn, INPUT); pinMode(buttonBtn, INPUT); pinMode(extFlash, OUTPUT); pinMode(camTrigger, OUTPUT); pinMode(camFocus, OUTPUT); } void loop() { if(readSensors() == true) { takePicture(); } delay(delayTime); } int readSensors() { piezoValue = analogRead(piezo); photoValue = analogRead(photo); potiValue = analogRead(poti); btnState = digitalRead(buttonBtn); switchState = digitalRead(switchBtn); Serial.print("Piezo-Wert : ");Serial.println(piezoValue); Serial.print("Photo-Resistor : ");Serial.println(photoValue); Serial.print("Potentiometer : ");Serial.println(potiValue); Serial.print("Taster : ");Serial.println(btnState); Serial.print("Schalter : ");Serial.println(switchState); Serial.println(" "); return(true); } void takePicture() { // do stuff here } ```
e74fdd1b-a232-43f4-847f-fbb459adbaeb
{ "language": "Arduino" }
```arduino ``` Add a DMX send example
```arduino #include <TeensyDmx.h> #define DMX_REDE 2 byte DMXVal[] = {50}; // This isn't required for DMX sending, but the code currently requires it. struct RDMINIT rdmData { "TeensyDMX v0.1", "Teensyduino", 1, // Device ID "DMX Node", 1, // The DMX footprint 0, // The DMX startAddress - only used for RDM 0, // Additional commands length for RDM 0 // Definition of additional commands }; TeensyDmx Dmx(Serial1, &rdmData, DMX_REDE); void setup() { Dmx.setMode(TeensyDmx::DMX_OUT); } void loop() { Dmx.setChannels(0,DMXVal,1); Dmx.loop(); } ```
9e843633-4411-464f-a484-2a7de7bd9ea4
{ "language": "Arduino" }
```arduino ``` Add simple interrupt test script
```arduino /****************************************************************************************************************************\ * * Arduino interrupt tests, as simple and understandable as possible. * © Aapo Rista 2017, MIT license * Tested with Wemos ESP8266 D1 Mini PRO * https://www.wemos.cc/product/d1-mini-pro.html * \*************************************************************************************************************************/ // const byte interruptPin = 2; // D4 on Wemos ESP8266 const byte interruptPin = D4; // If the board is correctly set in Arduino IDE, you can use D1, D2 etc. directly volatile byte interruptCounter = 0; int numberOfInterrupts = 0; int state = 0; void setup() { Serial.begin(115200); Serial.println(); Serial.println("Start"); // pinMode(interruptPin, INPUT_PULLUP); // Only one interrupt type can be attached to a GPIO pin at a time // attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, FALLING); // attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, RISING); attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, CHANGE); } void handleInterrupt() { interruptCounter++; state = digitalRead(interruptPin); } void loop() { if(interruptCounter>0){ interruptCounter--; numberOfInterrupts++; Serial.print("Interrupt "); if (state == 1) { Serial.print(" RISING"); } else { Serial.print("FALLING"); } Serial.print(" at "); Serial.print(millis()); Serial.print(" ms uptime. Total: "); Serial.println(numberOfInterrupts); } } ```
09f9a9ff-7936-4dcb-8516-2b4d3afcd959
{ "language": "Arduino" }
```arduino ``` Add draw text with scale example.
```arduino #include "AL_ILI9341.h" #include "AL_Font.h" // Wiring #define TFT_PORT PORTF #define TFT_PIN PINF #define TFT_DDR DDRF #define TFT_RST A12 #define TFT_CS A11 #define TFT_RS A10 #define TFT_WR A9 #define TFT_RD A8 AL_ILI9341 tft( &TFT_PORT, &TFT_PIN, &TFT_DDR, TFT_RST, TFT_CS, TFT_RS, TFT_WR, TFT_RD); AL_RgbColor backColor{255, 255, 255}; AL_RgbColor text1Color{255, 0, 0}; AL_RgbColor text2Color{0, 255, 0}; AL_RgbColor text3Color{0, 0, 255}; AL_RgbColor text4Color{0, 255, 255}; AL_RgbColor text5Color{255, 255, 0}; void setup() { tft.setup(); tft.setOrientation(AL_SO_LANDSCAPE2); tft.fillRect(0, 0, tft.getWidth(), tft.getHeight(), backColor); tft.drawText(10, 10, text1Color, backColor, 1, "hello"); tft.drawText(10, 26, text2Color, backColor, 2, "hello"); tft.drawText(10, 58, text3Color, backColor, 3, "hello"); tft.drawText(10, 106, text4Color, backColor, 4, "hello"); tft.drawText(10, 170, text5Color, backColor, 5, "hello"); } void loop() { }```
c0bebe32-7173-4079-8bf7-ed3e1eaaf1bf
{ "language": "Arduino" }
```arduino ``` Add test sketch for SR-04 ultasound sensors
```arduino #include <NewPing.h> #define SONAR_NUM 4 // Number or sensors. #define MAX_DISTANCE 200 // Maximum distance (in cm) to ping. #define PING_INTERVAL 33 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo). unsigned long pingTimer[SONAR_NUM]; // Holds the times when the next ping should happen for each sensor. unsigned int cm[SONAR_NUM]; // Where the ping distances are stored. uint8_t currentSensor = 0; // Keeps track of which sensor is active. NewPing sonar[SONAR_NUM] = { // Sensor object array. NewPing(11, 12, MAX_DISTANCE), // Each sensor's trigger pin, echo pin, and max distance to ping. NewPing(9, 10, MAX_DISTANCE), NewPing(2, 3, MAX_DISTANCE), NewPing(5, 6, MAX_DISTANCE) }; void setup() { Serial.begin(115200); pingTimer[0] = millis() + 75; // First ping starts at 75ms, gives time for the Arduino to chill before starting. for (uint8_t i = 1; i < SONAR_NUM; i++) // Set the starting time for each sensor. pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL; } void loop() { for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors. if (millis() >= pingTimer[i]) { // Is it this sensor's time to ping? pingTimer[i] += PING_INTERVAL * SONAR_NUM; // Set next time this sensor will be pinged. if (i == 0 && currentSensor == SONAR_NUM - 1) oneSensorCycle(); // Sensor ping cycle complete, do something with the results. sonar[currentSensor].timer_stop(); // Make sure previous timer is canceled before starting a new ping (insurance). currentSensor = i; // Sensor being accessed. cm[currentSensor] = 0; // Make distance zero in case there's no ping echo for this sensor. sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo). } } // The rest of your code would go here. } void echoCheck() { // If ping received, set the sensor distance to array. if (sonar[currentSensor].check_timer()) cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM; } void oneSensorCycle() { // Sensor ping cycle complete, do something with the results. for (uint8_t i = 0; i < SONAR_NUM; i++) { Serial.print(i); Serial.print("="); Serial.print(cm[i]); Serial.print("cm "); } Serial.println(); } ```
008cb56a-1919-4af3-a492-fe5ca6f3e5d7
{ "language": "Arduino" }
```arduino ``` Add Arduino sketch for testing individual strips
```arduino // Program for testing a single strip of lights. // Cycles through each possible combination of pure colors: // #000000 #FF0000 #00FF00 #FFFF00 #0000FF #FF00FF #00FFFF #FFFFFF // For each color, lights up lights one at a time with a slight delay between // individual lights, then leaves the whole strip lit up for 2 seconds. #include <FAB_LED.h> const uint8_t numPixels = 20; apa106<D, 6> LEDstrip; rgb pixels[numPixels] = {}; void setup() { } void loop() { static int color; for (int i = 0; i < numPixels; ++i) { pixels[i].r = !!(color & 1) * 255; pixels[i].g = !!(color & 2) * 255; pixels[i].b = !!(color & 4) * 255; delay(100); LEDstrip.sendPixels(numPixels, pixels); } color = (color + 1) % 8; // Display the pixels on the LED strip. LEDstrip.sendPixels(numPixels, pixels); delay(2000); } ```
98a69a2b-9593-4436-8f4a-6a3d35bfdaf1
{ "language": "Arduino" }
```arduino ``` Add working code for the arduino uno
```arduino // VoteVisualization // // Author: [email protected] // Released under the GPLv3 license to match the rest of the AdaFruit NeoPixel library #include <Adafruit_NeoPixel.h> #include <avr/power.h> // Digital I/O Pin connected to Data In of the NeoPixel Ring #define PIN 13 // Number of NeoPixels #define NUMPIXELS 24 // Configuration of NeoPixels Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); // Constants const uint32_t RED = pixels.Color(255, 0, 0); const uint32_t GREEN = pixels.Color(0, 255, 0); const uint32_t BLUE = pixels.Color(0, 0, 255); const uint32_t OFF = pixels.Color(0, 0, 0); const int START_SEQUENCE_BLINK_DELAY = 200; void setup() { // Setup the serial connection Serial.begin(9600); // Initialize the NeoPixel library pixels.begin(); // Display the start sequence to show that the right code is loaded and that the arduino is ready to be used startSequence(); } void loop() { // Blocking call if (Serial.available() > 0) { // A value between 0 and 1 is expected on the serial line. // The value expresses the ratio of positive votes in relation to all votes. float ratio = Serial.parseFloat(); if(ratio < 0 || ratio > 1) return; int numberOfGreens = (ratio * 24)+0.5; lightFirstXInGreenRestInRed(numberOfGreens); } } void lightFirstXInGreenRestInRed(int numberOfGreens){ for(int i=0; i<numberOfGreens; i++){ pixels.setPixelColor(i, GREEN); } for(int i=0+numberOfGreens; i<NUMPIXELS; i++){ pixels.setPixelColor(i, RED); } pixels.show(); } void startSequence(){ for(int j=0; j<10; j++){ lightAllLeds(BLUE); delay(START_SEQUENCE_BLINK_DELAY); lightAllLeds(OFF); delay(START_SEQUENCE_BLINK_DELAY); } } void lightAllLeds(uint32_t color) { for(int i=0; i<NUMPIXELS; i++){ pixels.setPixelColor(i, color); } pixels.show(); } ```
4f6956b4-9ea4-4b85-9359-6b6cb396530b
{ "language": "Arduino" }
```arduino ``` Add the arduino sketch to test the rover movement.
```arduino /* * Author: Manuel Parra Z. * Date: 14/11/2015 * License: MIT License * Materials: * - Arduino Uno R3 * - DFRobot DF-MD V1.3 * - DFRobot Pirate 4WD * Description: * This sketch will use as a movement test, first the rover will go foward * on the track, then it will go reverse, then will turn to left and finally * will turn to right. This sketch will show you the if you connected the * engines and batteries properly. Don't forget to review the fritzing * electronic diagram in the document section of the project */ int M1 = 4; int E1 = 5; int E2 = 6; int M2 = 7; void setup() { Serial.begin(9600); pinMode(M1, OUTPUT); pinMode(E1, OUTPUT); pinMode(M2, OUTPUT); pinMode(E2, OUTPUT); Serial.println("Setup finished."); } void loop() { Serial.println("Foward for 3 seconds."); digitalWrite(M1, HIGH); digitalWrite(M2, HIGH); analogWrite(E1, 200); analogWrite(E2, 200); delay(3000); Serial.println("Reverse for 3 seconds."); digitalWrite(M1, LOW); digitalWrite(M2, LOW); analogWrite(E1, 200); analogWrite(E2, 200); delay(3000); Serial.println("Left for 3 seconds."); digitalWrite(M1, LOW); digitalWrite(M2, HIGH); analogWrite(E1, 200); analogWrite(E2, 200); delay(3000); Serial.println("Right for 3 seconds."); digitalWrite(M1, HIGH); digitalWrite(M2, LOW); analogWrite(E1, 200); analogWrite(E2, 200); delay(3000); } ```
72112356-2fd7-4fff-be1f-24841be887ce
{ "language": "Arduino" }
```arduino ``` Add example for pairing with AccelStepper library
```arduino /** * Author Teemu Mäntykallio * Initializes the library and turns the motor in alternating directions. */ #define EN_PIN 38 // Nano v3: 16 Mega: 38 //enable (CFG6) #define DIR_PIN 55 // 19 55 //direction #define STEP_PIN 54 // 18 54 //step #define CS_PIN 40 // 17 40 //chip select constexpr uint32_t steps_per_mm = 80; #include <TMC2130Stepper.h> TMC2130Stepper driver = TMC2130Stepper(EN_PIN, DIR_PIN, STEP_PIN, CS_PIN); #include <AccelStepper.h> AccelStepper stepper = AccelStepper(stepper.DRIVER, STEP_PIN, DIR_PIN); void setup() { Serial.begin(9600); while(!Serial); Serial.println("Start..."); pinMode(CS_PIN, OUTPUT); digitalWrite(CS_PIN, HIGH); driver.begin(); // Initiate pins and registeries driver.rms_current(600); // Set stepper current to 600mA. The command is the same as command TMC2130.setCurrent(600, 0.11, 0.5); driver.stealthChop(1); // Enable extremely quiet stepping driver.stealth_autoscale(1); driver.microsteps(16); stepper.setMaxSpeed(50*steps_per_mm); // 100mm/s @ 80 steps/mm stepper.setAcceleration(1000*steps_per_mm); // 2000mm/s^2 stepper.setEnablePin(EN_PIN); stepper.setPinsInverted(false, false, true); stepper.enableOutputs(); } void loop() { if (stepper.distanceToGo() == 0) { stepper.disableOutputs(); delay(100); stepper.move(100*steps_per_mm); // Move 100mm stepper.enableOutputs(); } stepper.run(); } ```
f1e83f76-c944-4526-b0de-49732eb2bae9
{ "language": "Arduino" }
```arduino ``` Add RedBearLab BLE Mini module
```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 Arduino + RedBearLab BLE Mini * to connect your project to Blynk. * * NOTE: BLE support is in beta! * **************************************************************/ //#define BLYNK_DEBUG #define BLYNK_PRINT Serial #define BLYNK_USE_DIRECT_CONNECT #include <BlynkSimpleSerialBLE.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourAuthToken"; #define SerialBLE Serial1 // Set Serial object void setup() { // This is for debug prints Serial.begin(9600); SerialBLE.begin(57600); // BLE Mini uses baud 57600 Blynk.begin(auth, SerialBLE); } void loop() { Blynk.run(); } ```
daba43a5-3f48-4dc3-8f57-608f2374e377
{ "language": "Arduino" }
```arduino ``` Add WiFiNINA, Arduino MKR WiFi 1010 support
```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 Follow us: http://www.fb.com/blynkapp http://twitter.com/blynk_app Blynk library is licensed under MIT license This example code is in public domain. ************************************************************* This example shows how to use Arduino MKR 1010 to connect your project to Blynk. Note: This requires WiFiNINA library from http://librarymanager/all#WiFiNINA Feel free to apply it to any other example. It's simple! *************************************************************/ /* Comment this out to disable prints and save space */ #define BLYNK_PRINT Serial #define BLYNK_DEBUG #include <SPI.h> #include <WiFiNINA.h> #include <BlynkSimpleWiFiNINA.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourAuthToken"; // Your WiFi credentials. // Set password to "" for open networks. char ssid[] = "YourNetworkName"; char pass[] = "YourPassword"; void setup() { // Debug console Serial.begin(9600); while (!Serial) {} Blynk.begin(auth, ssid, pass); // You can also specify server: //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80); //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080); } void loop() { Blynk.run(); } ```
77a96e8d-5ee1-4aab-a2dd-4b24742c834a
{ "language": "Arduino" }
```arduino ``` Add an example showing how to set the QoS value of a message to publish
```arduino /* MQTT with QoS example - connects to an MQTT server - publishes "hello world" to the topic "outTopic" with a variety of QoS values */ #include <ESP8266WiFi.h> #include <PubSubClient.h> const char *ssid = "xxxxxxxx"; // cannot be longer than 32 characters! const char *pass = "yyyyyyyy"; // // Update these with values suitable for your network. IPAddress server(172, 16, 0, 2); void callback(String topic, byte* payload, unsigned int length) { // handle message arrived } PubSubClient client(server); void setup() { // Setup console Serial.begin(115200); delay(10); Serial.println(); Serial.println(); client.set_callback(callback); WiFi.begin(ssid, pass); int retries = 0; while ((WiFi.status() != WL_CONNECTED) && (retries < 10)) { retries++; delay(500); Serial.print("."); } if (WiFi.status() == WL_CONNECTED) { Serial.println(""); Serial.println("WiFi connected"); } if (client.connect("arduinoClient")) { client.publish("outTopic", "hello world qos=0"); // Simple publish with qos=0 client.publish(MQTT::Publish("outTopic", "hello world qos=1") .set_qos(1, client.next_packet_id())); client.publish(MQTT::Publish("outTopic", "hello world qos=2") .set_qos(2, client.next_packet_id())); } } void loop() { client.loop(); } ```
6e5cb0e8-64d7-42f7-9aa7-310806ceb1a4
{ "language": "Arduino" }
```arduino ``` Add Arduino example that receives ESP predictions over serial.
```arduino // Arduino example that streams accelerometer data from an ADXL335 // (or other three-axis analog accelerometer) to the ESP system and // lights different LEDs depending on the predictions made by the // ESP system. Use with the user_accelerometer_gestures.cpp ESP example. // the accelerometer pins int zpin = A3; int ypin = A4; int xpin = A5; // the LED pins int redpin = 9; int greenpin = 10; int bluepin = 11; // These are only used if you're plugging the ADXL335 (on the // Adafruit breakout board) directly into the analog input pins // of your Arduino. See comment below. int vinpin = A0; int voutpin = A1; int gndpin = A2; void setup() { Serial.begin(115200); // Lower the serial timeout (from its default value of 1000 ms) // so that the call to Serial.parseInt() below doesn't pause for // too long and disrupt the sending of accelerometer data. Serial.setTimeout(2); // Uncomment the following lines if you're using an ADXL335 on an // Adafruit breakout board (https://www.adafruit.com/products/163) // and want to plug it directly into (and power it from) the analog // input pins of your Arduino board. // pinMode(vinpin, OUTPUT); digitalWrite(vinpin, HIGH); // pinMode(gndpin, OUTPUT); digitalWrite(gndpin, LOW); // pinMode(voutpin, INPUT); pinMode(xpin, INPUT); pinMode(ypin, INPUT); pinMode(zpin, INPUT); } void loop() { Serial.print(analogRead(xpin)); Serial.print("\t"); Serial.print(analogRead(ypin)); Serial.print("\t"); Serial.print(analogRead(zpin)); Serial.println(); delay(10); // Check for a valid prediction. int val = Serial.parseInt(); if (val != 0) { // Turn off all the LEDs. analogWrite(redpin, 0); analogWrite(greenpin, 0); analogWrite(bluepin, 0); // Turn on the LED corresponding to the prediction. if (val == 1) analogWrite(redpin, 255); if (val == 2) analogWrite(greenpin, 255); if (val == 3) analogWrite(bluepin, 255); } } ```
67883032-bbda-4c38-9648-ffc9b53d0017
{ "language": "Arduino" }
```arduino ``` Add demo on new functionality
```arduino /* * IRremote: IRInvertModulate - demonstrates the ability enable/disable * IR signal modulation and inversion. * An IR LED must be connected to Arduino PWM pin 3. * To view the results, attach an Oscilloscope or Signal Analyser across the * legs of the IR LED. * Version 0.1 November, 2013 * Copyright 2013 Aaron Snoswell * http://elucidatedbinary.com */ #include <IRremote.h> IRsend irsend; void setup() { Serial.begin(9600); Serial.println("Welcome, visitor"); Serial.println("Press 'm' to toggle IR modulation"); Serial.println("Press 'i' to toggle IR inversion"); } bool modulate = true; bool invert = false; void loop() { if (!Serial.available()) { // Send some random data irsend.sendNEC(0xa90, 12); } else { char c; do { c = Serial.read(); } while(Serial.available()); if(c == 'm') { modulate = !modulate; if(modulate) Serial.println("Enabling Modulation"); else Serial.println("Disabling Modulation"); irsend.enableIRModulation(modulate); } else if(c == 'i') { invert = !invert; if(invert) Serial.println("Enabling Invert"); else Serial.println("Disabling Invert"); irsend.enableIRInvert(invert); } else { Serial.println("Unknown Command"); } } delay(300); } ```
5ff94cf2-6fa6-4390-8c10-635e1bc8a99e
{ "language": "Arduino" }
```arduino ``` Bring up verification of GroveMoisture
```arduino int sensorPin = A1; // select the input pin for the potentiometer float sensorValue[0]; float get_sensor_data_moisture(){ // read the value from the sensor: return analogRead(sensorPin); } void setup() { // declare the ledPin as an OUTPUT: Serial.begin(115200); } void loop() { sensorValue[0]=get_sensor_data_moisture(); Serial.print("sensor = " ); Serial.println(sensorValue[0]); delay(1000); } ```
2d9f91ff-b801-4a3c-8aa2-23468b8729b6
{ "language": "Arduino" }
```arduino ``` Add example sketch for testing out "will" messages
```arduino /* MQTT "will" message example - connects to an MQTT server with a will message - publishes a message - waits a little bit - disconnects the socket *without* sending a disconnect packet You should see the will message published when we disconnect */ #include <ESP8266WiFi.h> #include <PubSubClient.h> const char *ssid = "xxxxxxxx"; // cannot be longer than 32 characters! const char *pass = "yyyyyyyy"; // // Update these with values suitable for your network. IPAddress server(172, 16, 0, 2); WiFiClient wclient; PubSubClient client(wclient, server); void setup() { // Setup console Serial.begin(115200); delay(10); Serial.println(); Serial.println(); } void loop() { delay(1000); if (WiFi.status() != WL_CONNECTED) { Serial.print("Connecting to "); Serial.print(ssid); Serial.println("..."); WiFi.begin(ssid, pass); if (WiFi.waitForConnectResult() != WL_CONNECTED) return; Serial.println("WiFi connected"); } if (WiFi.status() == WL_CONNECTED) { MQTT::Connect con("arduinoClient"); con.set_will("test", "I am down."); // Or to set a binary message: // char msg[4] = { 0xde, 0xad, 0xbe, 0xef }; // con.set_will("test", msg, 4); if (client.connect(con)) { client.publish("test", "I am up!"); delay(1000); wclient.stop(); } else Serial.println("MQTT connection failed."); delay(10000); } } ```
3aa6f66e-8d90-4f41-8f68-95d4652ea432
{ "language": "Arduino" }
```arduino ``` Test code for the line follow
```arduino #define FAR_LEFT A0 #define LEFT A1 #define CENTER_LEFT A2 #define CENTER_RIGHT A3 #define RIGHT A4 #define FAR_RIGHT A5 #define WB_THRESHOLD 400 #define IR_DELAY 140 void setup() { Serial.begin(9600); pinMode(FAR_LEFT, INPUT); pinMode(LEFT, INPUT); pinMode(CENTER_LEFT, INPUT); pinMode(CENTER_RIGHT, INPUT); pinMode(RIGHT, INPUT); pinMode(FAR_RIGHT, INPUT); pinMode(LED_BUILTIN, OUTPUT); } boolean toDigital(uint8_t pin){ int reading = analogRead(pin); delayMicroseconds(IR_DELAY); // Serial.println(reading); return reading > WB_THRESHOLD; } void print_digital_readings(){ boolean far_left = toDigital(FAR_LEFT); boolean left = toDigital(LEFT); boolean center_left = toDigital(CENTER_LEFT); boolean center_right = toDigital(CENTER_RIGHT); boolean right = toDigital(RIGHT); boolean far_right = toDigital(FAR_RIGHT); Serial.print(far_left); Serial.print("\t"); Serial.print(left); Serial.print("\t"); Serial.print(center_left); Serial.print("\t"); Serial.print(center_right); Serial.print("\t"); Serial.print(right); Serial.print("\t"); Serial.println(far_right); } void print_analog_readings(){ int far_left = analogRead(FAR_LEFT); int left = analogRead(LEFT); int center_left = analogRead(CENTER_LEFT); int center_right = analogRead(CENTER_RIGHT); int right = analogRead(RIGHT); int far_right = analogRead(FAR_RIGHT); Serial.print(far_left); Serial.print("\t"); Serial.print(left); Serial.print("\t"); Serial.print(center_left); Serial.print("\t"); Serial.print(center_right); Serial.print("\t"); Serial.print(right); Serial.print("\t"); Serial.println(far_right); } void loop(){ print_analog_readings(); //print_digital_readings(); delay(20); } ```
26589647-d796-4200-b0e7-c9cd476b1bbb
{ "language": "Arduino" }
```arduino ``` Add blink file too for ease of access
```arduino /* Blink Turns on an LED on for one second, then off for one second, repeatedly. Most Arduinos have an on-board LED you can control. On the Uno and Leonardo, it is attached to digital pin 13. If you're unsure what pin the on-board LED is connected to on your Arduino model, check the documentation at http://arduino.cc This example code is in the public domain. modified 8 May 2014 by Scott Fitzgerald */ // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin 13 as an output. pinMode(13, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(13, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } ```
83a917ac-299e-4a26-83fa-de8c3d9094fa
{ "language": "Arduino" }
```arduino ``` Add arduino stepper motor control
```arduino /* Stepper Motor Control */ #include <Stepper.h> const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution // for your motor // initialize the stepper library on pins 8 through 11: Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11); int stepCount = 0; // number of steps the motor has taken int stepValue = 0; // current step number the motor is on void setup() { // initialize the serial port: Serial.begin(9600); myStepper.setSpeed(200); } void loop() { // step one step: myStepper.step(1); //Serial.print("steps:"); Serial.println(stepValue); //Serial.print("degrees: "); //Serial.println(stepCount*1.8); stepCount++; stepValue = stepCount + 1; if (stepValue > 200) { stepValue = stepValue - 200; } delay(100); } ```
a821a335-14da-4e26-af14-494b32d3dbc2
{ "language": "Arduino" }
```arduino ``` Add super simple arduino servo-based cutdown program.
```arduino #include <Servo.h> Servo myservo; int pos = 0; void setup() { myservo.attach(9); myservo.write(45); // Start out in a good position delay(5000); // Wait as long as you like. (milliseconds) } void loop() { myservo.write(130) // End in a release position while(true); // Do nothing, forever. } ```
79cdebf2-0ccc-468c-bd08-f53b023711ce
{ "language": "Arduino" }
```arduino ``` Add simple Arduino test program
```arduino void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); Keyboard.begin(); //setup buttons pinMode(2, INPUT_PULLUP); //Button 1 pinMode(3, INPUT_PULLUP); //Button 2 pinMode(4, INPUT_PULLUP); //Button 3 pinMode(5, INPUT_PULLUP); //Button 4 //setup mainboard connection pinMode(6, OUTPUT); //Reset pin digitalWrite(6, LOW); //active high pulse pinMode(7, OUTPUT); //Power on pin digitalWrite(7, LOW); //active high pulse //setup coin detector pinMode(8, INPUT_PULLUP); //Coin 1 pinMode(9, INPUT_PULLUP); //Coin 2 pinMode(10, INPUT_PULLUP); //Coin 3 pinMode(11, INPUT_PULLUP); //Reject button pinMode(12, OUTPUT); //Accept all coins digitalWrite(12, LOW); } void loop() { // read the input pin: int buttonState2 = digitalRead(2); int buttonState3 = digitalRead(3); int buttonState4 = digitalRead(4); int buttonState5 = digitalRead(5); int buttonState8 = digitalRead(8); int buttonState9 = digitalRead(9); int buttonState10 = digitalRead(10); int buttonState11 = digitalRead(11); // print out the state of the buttons: Serial.print(buttonState2); Serial.print(buttonState3); Serial.print(buttonState4); Serial.print(buttonState5); Serial.print(buttonState8); Serial.print(buttonState9); Serial.print(buttonState10); Serial.print(buttonState11); Serial.print('\n'); delay(25); // delay in between reads for stability if(buttonState2 == LOW) { Keyboard.write('A'); digitalWrite(6, HIGH); //push reset } else { digitalWrite(6, LOW); } if(buttonState3 == LOW) { Keyboard.write('B'); digitalWrite(7, HIGH); //push power } else { digitalWrite(7, LOW); } if(buttonState4 == LOW) { Keyboard.write('C'); } if(buttonState5 == LOW) { Keyboard.write('D'); } if(buttonState8 == LOW) { Keyboard.write('1'); } if(buttonState9 == LOW) { Keyboard.write('2'); } if(buttonState10 == LOW) { Keyboard.write('3'); } } ```
5db0abc9-f791-463c-90aa-97ed0e2b082f
{ "language": "Arduino" }
```arduino ``` Add a tool for auto calibration of watchdog based clock.
```arduino /** * @file CosaAutoCalibration.ino * @version 1.0 * * @section License * Copyright (C) 2015, Mikael Patel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * @section Description * Calibrate Watchdog clock with RTC clock as reference. Automatically * adjust Watchdog clock to RTC clock tick. * * This file is part of the Arduino Che Cosa project. */ #include "Cosa/RTC.hh" #include "Cosa/Watchdog.hh" #include "Cosa/Trace.hh" #include "Cosa/IOStream/Driver/UART.hh" RTC::Clock clock; Watchdog::Clock bark; void setup() { // Start trace output stream on the serial port uart.begin(57600); trace.begin(&uart, PSTR("CosaAutoCalibration: started")); // Start the watchdog and internal real-time clock Watchdog::begin(); RTC::begin(); // Synchronized clocks uint32_t now = clock.await(); delay(500); bark.time(now + 1); } void loop() { static int32_t cycle = 1; // Wait for clock update uint32_t now = clock.await(); // Calculate error and possible adjustment int32_t diff = bark.time() - now; int32_t err = (1000 * diff) / cycle; if (err != 0) { bark.adjust(err / 2); trace << endl << PSTR("calibration=") << bark.calibration() << endl; cycle = 1; clock.time(0); now = clock.await(); delay(500); bark.time(now + 1); } else { trace << '.'; cycle += 1; } } ```
85bcfccf-19d3-468f-8a6d-7d695fbc56b0
{ "language": "Arduino" }
```arduino ``` Add TFmini plus (lidar) test code
```arduino // set this to the hardware serial port you wish to use #define HWSERIAL Serial1 byte byteArray [9]; // Byte0 Byte 1 Byte2 Byte3 Byte4 Byte5 Byte6 Byte7 Byte8 // 0x89 0x89 Dist_L Dist_H Strength_L Strength_H Temp_L Temp_H Checksum // byte2 is distance, overflows into byte3 byte configOutput [5] = {0x5A, 0x05, 0x07, 0x01, 0x11}; // write this array to HWSERIAL to enable output byte configUART [5] = {0x5A, 0x05, 0x0A, 0x00, 0x11}; // write this array to HWSERIAL to set sensor to UART mode // more config commands on datasheet https://acroname.com/sites/default/files/assets/sj-gu-tfmini_plus-01-a04-datasheet_en.pdf void setup() { Serial.begin(115200); HWSERIAL.begin(115200);// default baud rate HWSERIAL.write(configUART, 5); // set sensor to UART mode HWSERIAL.write(configOutput, 5); // enable output } void loop() { if (HWSERIAL.available() > 0) { HWSERIAL.readBytes(byteArray, 9); // write output of read to an array of length 9 for (int i =0;i<9;i++){ Serial.println(byteArray[i]); } } } ```
8346f54a-9c04-47ce-9d5d-46515dd38bc7
{ "language": "Arduino" }
```arduino ``` Test for motor using enable pins and buttons operation.
```arduino #include <Stepper.h> #define P1 P4_5 #define P2 P1_1 const int stepsPerRevolution = 200; Stepper myStepper(stepsPerRevolution, 12,13,5,9); short forward; short backward; void setup() { // set the speed at 60 rpm: myStepper.setSpeed(60); // initialize the serial port: Serial.begin(9600); // Enable pin pull-up for the buttons pinMode(P4_5, INPUT_PULLUP); pinMode(P1_1, INPUT_PULLUP); // Set modes for enable pins pinMode(18, OUTPUT); pinMode(19, OUTPUT); } void loop() { // Read button pins forward = digitalRead(P1); backward = digitalRead(P2); Serial.print(forward); // Enable or disable motor if (forward == 0 || backward == 0) { digitalWrite(18, HIGH); digitalWrite(19, HIGH); } else { digitalWrite(18, LOW); digitalWrite(19, LOW); } // Turn motor if a button is pressed if (forward == 0) { myStepper.step(1); } if (backward == 0) { myStepper.step(-1); } // Delay before next loop. Determines how fast the motor turns delay(4); } ```
c34bb8dc-302f-4425-a036-b3a281d7d5a6
{ "language": "Arduino" }
```arduino ``` Add canbus FD send example
```arduino // demo: CAN-BUS Shield, send data // [email protected] #include <SPI.h> #include "mcp2518fd_can.h" /*SAMD core*/ #ifdef ARDUINO_SAMD_VARIANT_COMPLIANCE #define SERIAL SerialUSB #else #define SERIAL Serial #endif #define CAN_2518FD // the cs pin of the version after v1.1 is default to D9 // v0.9b and v1.0 is default D10 const int SPI_CS_PIN = BCM8; #ifdef CAN_2518FD mcp2518fd CAN(SPI_CS_PIN); // Set CS pin #endif void setup() { SERIAL.begin(115200); while(!Serial){}; CAN.setMode(0); while (0 != CAN.begin((byte)CAN_500K_1M)) { // init can bus : baudrate = 500k SERIAL.println("CAN BUS Shield init fail"); SERIAL.println(" Init CAN BUS Shield again"); delay(100); } byte mode = CAN.getMode(); SERIAL.printf("CAN BUS get mode = %d\n\r",mode); SERIAL.println("CAN BUS Shield init ok!"); } unsigned char stmp[64] = {0}; void loop() { // send data: id = 0x00, standrad frame, data len = 8, stmp: data buf stmp[63] = stmp[63] + 1; if (stmp[63] == 100) { stmp[63] = 0; stmp[63] = stmp[63] + 1; if (stmp[6] == 100) { stmp[6] = 0; stmp[5] = stmp[6] + 1; } } CAN.sendMsgBuf(0x00, 0, 15, stmp); delay(100); // send data per 100ms SERIAL.println("CAN BUS sendMsgBuf ok!"); } // END FILE ```
d182e533-0b37-4d91-89a7-3bd66fc394cf
{ "language": "Arduino" }
```arduino ``` Add ECDSA test for Arduino
```arduino #include <uECC.h> #include <j0g.h> #include <js0n.h> #include <lwm.h> #include <bitlash.h> #include <GS.h> #include <SPI.h> #include <Wire.h> #include <Scout.h> #include <Shell.h> #include <uECC.h> extern "C" { static int RNG(uint8_t *p_dest, unsigned p_size) { while(p_size) { long v = random(); unsigned l_amount = min(p_size, sizeof(long)); memcpy(p_dest, &v, l_amount); p_size -= l_amount; p_dest += l_amount; } return 1; } void px(uint8_t *v, uint8_t num) { uint8_t i; for(i=0; i<num; ++i) { Serial.print(v[i]); Serial.print(" "); } Serial.println(); } } void setup() { Scout.setup(); uint8_t l_private[uECC_BYTES]; uint8_t l_public[uECC_BYTES * 2]; uint8_t l_hash[uECC_BYTES]; uint8_t l_sig[uECC_BYTES*2]; Serial.print("Testing ECDSA\n"); uECC_set_rng(&RNG); for(;;) { unsigned long a = millis(); if(!uECC_make_key(l_public, l_private)) { Serial.println("uECC_make_key() failed"); continue; } unsigned long b = millis(); Serial.print("Made key 1 in "); Serial.println(b-a); memcpy(l_hash, l_public, uECC_BYTES); a = millis(); if(!uECC_sign(l_private, l_hash, l_sig)) { Serial.println("uECC_sign() failed\n"); continue; } b = millis(); Serial.print("ECDSA sign in "); Serial.println(b-a); a = millis(); if(!uECC_verify(l_public, l_hash, l_sig)) { Serial.println("uECC_verify() failed\n"); continue; } b = millis(); Serial.print("ECDSA verify in "); Serial.println(b-a); } } void loop() { // put your main code here, to run repeatedly: } ```
4ba9e819-956b-4315-b741-802c2ba552c8
{ "language": "Arduino" }
```arduino ``` Add sketch for reading button press
```arduino int BUTTON_PIN = 2; void setup() { pinMode(BUTTON_PIN, INPUT); Serial.begin(9600); } void loop() { //Serial.println("Hello computer!"); //Serial.print("This line will mash together with the next."); int buttonPressed = digitalRead(BUTTON_PIN); if(buttonPressed == 1) { Serial.println("I pressed the button, and the button is:"); Serial.println(buttonPressed); } } ```
3dde5267-8e6c-4a91-806d-659615b9289d
{ "language": "Arduino" }
```arduino ``` Add sketch that includes all LCD interface implementations and adapters.
```arduino /** * @file CosaLCDverify.ino * @version 1.0 * * @section License * Copyright (C) 2015, Mikael Patel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * @section Description * Verify build of all implementations of LCD and adapters. * * This file is part of the Arduino Che Cosa project. */ #include <HD44780.h> #include <PCF8574.h> #include <MJKDZ_LCD_Module.h> #include <GY_IICLCD.h> #include <DFRobot_IIC_LCD_Module.h> #include <SainSmart_LCD2004.h> #include <MCP23008.h> #include <Adafruit_I2C_LCD_Backpack.h> #include <ERM1602_5.h> #include <Canvas.h> #include <PCD8544.h> #include <ST7565.h> #include <VLCD.h> ```
4109a968-b55c-4a85-be2d-05df1be0adf3
{ "language": "Arduino" }
```arduino ``` Add firmware for LightBlueBean Token
```arduino // Token's firmware working copy // Code based on RFDUINO hardware, uses C char arrays #include <ArduinoJson.h> //Test JSON strings char OFF[]= "{\"device\":\"LED\",\"event\":\"off\"}"; char GREEN[] = "{\"device\":\"LED\",\"event\":\"on\",\"color\":\"green\"}"; char RED[] = "{\"device\":\"LED\",\"event\":\"on\",\"color\":\"red\"}"; char BLUE[] = "{\"device\":\"LED\",\"event\":\"on\",\"color\":\"blue\"}"; char WHITE[] = "{\"device\":\"LED\",\"event\":\"on\",\"color\":\"white\"}"; void setup() { //Serial.begin(9600); //Streams debug messagges over the serial port DEFAULT: OFF // Test LED on startup parseJSON(GREEN); delay(300); parseJSON(RED); delay(300); parseJSON(BLUE); delay(300); parseJSON(WHITE); delay(300); parseJSON(OFF); delay(300); //Initialise bluetooth } void loop() { } //Parses JSON messages void parseJSON(char *payload) { char sel; // char json[200]; // payload.toCharArray(json, 50); StaticJsonBuffer<200> jsonBuffer; JsonObject& root = jsonBuffer.parseObject(payload); // Serial.print("DEBUG: "); Serial.println(json); if (!root.success()) { Serial.println("parseObject() failed"); return; } const char* device = root["device"]; const char* event = root["event"]; const char* color = root["color"]; if(strcmp(device, "LED") == 0) { if(strcmp(event, "on") == 0) { sel = color[0]; ledON(sel); } if (strcmp(event, "off") == 0) { ledOFF(); } } } // Turns the LED off void ledOFF(){ Bean.setLed(0, 0, 0); } // Turns on the LED on a specific color: r=red, g=gree, osv.. void ledON(char sel){ switch(sel) { case 'r': { Bean.setLed(255, 0, 0); Serial.println("DEBUG: LED RED ON"); break; } case 'g': { Bean.setLed(0, 255, 0); Serial.println("DEBUG: LED GREEN ON"); break; } case 'b': { Bean.setLed(0, 0, 255); Serial.println("DEBUG: LED BLUE ON"); break; } case 'w': { Bean.setLed(255, 255, 255); Serial.println("DEBUG: LED WITHE ON"); break; } }} ```
90522359-e46e-40fe-864a-91262fcd772b
{ "language": "Arduino" }
```arduino ``` Add new sketch for ESP8266
```arduino /* * Blink for esp8266 */ #define ESP8266_LED 2 void setup() { // put your setup code here, to run once: pinMode(ESP8266_LED, OUTPUT); } void loop() { // put your main code here, to run repeatedly: digitalWrite(ESP8266_LED, HIGH); delay(1000); digitalWrite(ESP8266_LED, LOW); delay(1000); } ```
e8baf89b-e421-4a14-be66-7e3c6ac0aafc
{ "language": "Arduino" }
```arduino ``` Add example to help find suitable contrast value.
```arduino /** Contrast Helper * * Loops through a range of contrast values and prints each one. * * To set the contrast in your sketch, simply put lcd.setContrast(xx); * after your lcd.begin(). * * Experimentally determined, contrast values around 65-70 tend to * work reasonably well on most displays. The best contrast value * for each display is specific to that particular display due to * manufacturing tolerances and so forth. * */ #include <SPI.h> #include "PCD8544_Simple.h" PCD8544_Simple lcd; const uint8_t contrastMin = 40; const uint8_t contrastMax = 80; static uint8_t contrastDirection = 1; static uint8_t contrast = (contrastMax-contrastMin)/2+contrastMin; void setup() { lcd.begin(); } void loop() { if(contrastDirection) { if(contrast++ > contrastMax) { contrastDirection = 0; } } else { if(contrast-- < contrastMin) { contrastDirection = 1; } } lcd.setContrast(contrast); lcd.print("lcd.setContrast("); lcd.print(contrast); lcd.println(");"); delay(500); }```
6d486c55-4386-4f54-9705-6c1ea6ff186c
{ "language": "Arduino" }
```arduino ``` Add Arduino program to generate camera and light trigger.
```arduino // // Generate a 9Hz square signal to trigger camera and lightning // // Arduino setup void setup() { // Output signal pinMode( 13, OUTPUT ); } // Main loop void loop() { // High state (11ms) digitalWrite( 13, HIGH ); delay( 11 ); // Low state (100ms) digitalWrite( 13, LOW ); delay( 100 ); } ```
a246c222-24a1-4dbf-8bab-1cc8e6d8815b
{ "language": "Arduino" }
```arduino ``` Add test sketch which simply runs each motor separately, without input from Android
```arduino #include "DualVNH5019MotorShield.h" DualVNH5019MotorShield md; void stopIfFault() { if (md.getM1Fault()) { Serial.println("M1 fault"); while(1); } if (md.getM2Fault()) { Serial.println("M2 fault"); while(1); } } void setup() { Serial.begin(19200); Serial.println("Dual VNH5019 Motor Shield"); md.init(); } void loop() { for (int i = 0; i <= 400; i++) { md.setM1Speed(i); stopIfFault(); if (i%200 == 100) { Serial.print("M1 current: "); Serial.println(md.getM1CurrentMilliamps()); } delay(2); } for (int i = 400; i >= -400; i--) { md.setM1Speed(i); stopIfFault(); if (i%200 == 100) { Serial.print("M1 current: "); Serial.println(md.getM1CurrentMilliamps()); } delay(2); } for (int i = -400; i <= 0; i++) { md.setM1Speed(i); stopIfFault(); if (i%200 == 100) { Serial.print("M1 current: "); Serial.println(md.getM1CurrentMilliamps()); } delay(2); } for (int i = 0; i <= 400; i++) { md.setM2Speed(i); stopIfFault(); if (i%200 == 100) { Serial.print("M2 current: "); Serial.println(md.getM2CurrentMilliamps()); } delay(2); } for (int i = 400; i >= -400; i--) { md.setM2Speed(i); stopIfFault(); if (i%200 == 100) { Serial.print("M2 current: "); Serial.println(md.getM2CurrentMilliamps()); } delay(2); } for (int i = -400; i <= 0; i++) { md.setM2Speed(i); stopIfFault(); if (i%200 == 100) { Serial.print("M2 current: "); Serial.println(md.getM2CurrentMilliamps()); } delay(2); } } ```
ec5e30c2-5f03-4f9e-a654-85a8c85b5aaa
{ "language": "Arduino" }
```arduino ``` Read GPS data from sensor and write it to the serial port
```arduino #include <SoftwareSerial.h> SoftwareSerial SoftSerial(2, 3); char buffer[265]; int count=0; void setup() { SoftSerial.begin(9600); Serial.begin(9600); } void loop() { if (SoftSerial.available()) { while(SoftSerial.available()) { buffer[count++]=SoftSerial.read(); if(count == 265)break; } String value = ""; if(String(char(buffer[0])) + char(buffer[1]) + char(buffer[2]) + char(buffer[3]) + char(buffer[4]) + char(buffer[5]) == "$GPGGA"){ boolean isEnd = false; int commaCount = 0; for(int i = 6; isEnd == false; i++){ if(buffer[i] == 44) commaCount++; if(commaCount == 14) isEnd = true; if(isEnd == true){ i -= 6; for(int x = 0; x <= i; x++){ char current = char(buffer[x]); value += current; } Serial.println(value); Serial.println(getValue(value,',',1)); Serial.println(getValue(value,',',2)); Serial.println(getValue(value,',',4)); } } } delay(1000); clearBufferArray(); count = 0; } } void clearBufferArray() { for (int i=0; i<count;i++) buffer[i]=NULL; } String getValue(String data, char separator, int index) { int found = 0; int strIndex[] = {0, -1}; int maxIndex = data.length()-1; for(int i=0; i<=maxIndex && found<=index; i++){ if(data.charAt(i)==separator || i==maxIndex){ found++; strIndex[0] = strIndex[1]+1; strIndex[1] = (i == maxIndex) ? i+1 : i; } } return found>index ? data.substring(strIndex[0], strIndex[1]) : ""; } ```
80e7bcb5-3122-4d7f-9b2e-a3b3fb66a02e
{ "language": "Arduino" }
```arduino ``` Add source code for Jarbas
```arduino #include <ESP8266HTTPClient.h> #include <ESP8266WiFiMulti.h> #define RELAY D1 const int HTTPS_PORT = 443; const char* WIFI = "WIFI"; const char* PASSWORD = "PASSWORD"; const char* HOST = "hooks.slack.com"; const char* URL = "URL"; String PAYLOAD = String("{\"text\": \"@here Café quentinho na cafeteira!\", \"link_names\": 1}"); ESP8266WiFiMulti wifi; bool turnOff = false; bool coffeeIsReady = false; void prepareCoffee() { delay(9 * 60 * 1000); // Wait 9 minutes. coffeeIsReady = true; } void notifySlack() { HTTPClient client; client.begin(HOST, HTTPS_PORT, URL, String("AC:95:5A:58:B8:4E:0B:CD:B3:97:D2:88:68:F5:CA:C1:0A:81:E3:6E")); client.addHeader("Content-Type", "application/x-www-form-urlencoded"); client.POST(PAYLOAD); client.end(); } void waitAndTurnOffCoffeeMachine() { delay(10 * 60 * 1000); // Wait 10 minutes. digitalWrite(RELAY, LOW); // Turn off. turnOff = true; } void setup() { wifi.addAP(WIFI, PASSWORD); pinMode(RELAY, OUTPUT); digitalWrite(RELAY, HIGH); } void loop() { if (!turnOff && !coffeeIsReady) prepareCoffee(); if (!turnOff && coffeeIsReady && wifi.run() == WL_CONNECTED) { notifySlack(); waitAndTurnOffCoffeeMachine(); } delay(1000); } ```
3d498926-34ac-40a6-9e5b-27a8c8b01b60
{ "language": "Arduino" }
```arduino ``` Add example to read A0
```arduino /* * Simple demonstration of AsyncDelay to read the A0 analogue input * every 50 ms. */ #include <AsyncDelay.h> AsyncDelay samplingInterval; void setup(void) { Serial.begin(115200); samplingInterval.start(50, AsyncDelay::MILLIS); } void loop(void) { if (samplingInterval.isExpired()) { uint16_t count = analogRead(A0); samplingInterval.repeat(); Serial.print(count); Serial.print('\n'); } } ```
a3909cdc-5243-4499-aae9-3dcb3f91a24d
{ "language": "Arduino" }
```arduino ``` Add simple sketch to test Ultrasonic sensor
```arduino /* Test Ultrasonic sensor readings Created 2 7 2014 Modified 2 7 2014 */ // Ultrasonic sensor settings const byte ULTRASONIC_PIN = A6; void setup() { Serial.begin(9600); } void loop() { Serial.println(analogRead(ULTRASONIC_PIN)); delay(1000); }```
3a7e9dbd-69b6-4bf0-8956-5cd5c05123a4
{ "language": "Arduino" }
```arduino ``` Add Simblee BLE example
```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 Simblee BLE * to connect your project to Blynk. * * NOTE: BLE support is in beta! * **************************************************************/ //#define BLYNK_DEBUG #define BLYNK_PRINT Serial //#define BLYNK_USE_DIRECT_CONNECT #include <BlynkSimpleSimbleeBLE.h> #include <SimbleeBLE.h> char auth[] = "YourAuthToken"; void setup() { Serial.begin(9600); SimbleeBLE.deviceName = "Simblee"; SimbleeBLE.advertisementInterval = MILLISECONDS(300); SimbleeBLE.txPowerLevel = -20; // (-20dbM to +4 dBm) // start the BLE stack SimbleeBLE.begin(); Blynk.begin(auth); Serial.println("Bluetooth device active, waiting for connections..."); } void loop() { Blynk.run(); } ```
26f53a32-ff16-4490-9941-a251d71ccfa8
{ "language": "Arduino" }
```arduino ``` Add example of a custom function in serial
```arduino #include "VdlkinoSerial.h" VdlkinoSerial vdlkino(14, 6, &Serial); uint16_t get_analog_byte(void *block) { VdlkinoBlock *vblock = (VdlkinoBlock*) block; return map(analogRead(vblock->pin), 0, 1023, 0, 255); } void setup() { Serial.begin(9600); vdlkino.operations[8] = &get_analog_byte; } void loop() { vdlkino.run(); } ```
3ad749f3-5276-474f-9b0a-de2d47d217b1
{ "language": "Arduino" }
```arduino ``` Add a simple example sketch with many explanatory comments
```arduino /* NeoPixel Ring simple sketch (c) 2013 Shae Erisson released under the GPLv3 license to match the rest of the AdaFruit NeoPixel library */ #include <Adafruit_NeoPixel.h> #ifdef __AVR_ATtiny85__ // Trinket, Gemma, etc. #include <avr/power.h> #endif // Which pin on the FLORA is connected to the NeoPixel ring? #define PIN 6 // We're using only one ring with 16 NeoPixel #define NUMPIXELS 16 // When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals. Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); int delayval = 500; // delay for half a second void setup() { #ifdef __AVR_ATtiny85__ // Trinket, Gemma, etc. if(F_CPU == 16000000) clock_prescale_set(clock_div_1); // Seed random number generator from an unused analog input: randomSeed(analogRead(2)); #else randomSeed(analogRead(A0)); #endif pixels.begin(); // This initializes the NeoPixel library. } void loop() { // for one ring of 16, the first NeoPixel is 0, second is 1, all the way up to 15 for(int i=0;i<NUMPIXELS;i++){ // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255 pixels.setPixelColor(i,pixels.Color(0,150,0)); // we choose green pixels.show(); // this sends the value once the color has been set delay(delayval); } } ```
4c4578c5-cdc0-49e0-aab0-c206ef378fe2
{ "language": "Arduino" }
```arduino ``` Add comment to improve code readability
```arduino #include <HID.h> #include <Keyboard.h> // Init function void setup() { // Start Keyboard and Mouse Keyboard.begin(); // Start Payload // press Windows+X Keyboard.press(KEY_LEFT_GUI); delay(1000); Keyboard.press('x'); Keyboard.releaseAll(); delay(500); // launch Command Prompt (Admin) typeKey('a'); delay(3000); // klik "Yes" typeKey(KEY_LEFT_ARROW); typeKey(KEY_RETURN); delay(1000); // add user Keyboard.println("net user /add Arduino 123456"); typeKey(KEY_RETURN); delay(100); // make that user become admin Keyboard.print("net localgroup administrators Arduino /add"); typeKey(KEY_RETURN); delay(100); Keyboard.print("exit"); typeKey(KEY_RETURN); // End Payload // Stop Keyboard and Mouse Keyboard.end(); } // Unused void loop() {} // Utility function void typeKey(int key){ Keyboard.press(key); delay(500); Keyboard.release(key); } ```
ce9c35ef-5b2d-4072-adab-934acf7db56a
{ "language": "Arduino" }
```arduino ``` Add sketch that test ultrasonic readings on sensor platform
```arduino /* Test Ultrasonic sensor readings on sensor platform This sketch is designed to test the accuracy of the Ultrasonic sensor with the battery pack and circuit of the sensor platform. This sketch takes 5 readings and averages them to help verify similar calculations used in BridgeSensorGSM sketch. The results are written to the SD card Created 10 7 2014 Modified 10 7 2014 */ #include <LowPower.h> #include <ARTF_SDCard.h> // ARTF SDCard Dependency #include <SdFat.h> #include <String.h> // Ultrasonic Settings const byte ULTRASONIC_PIN = A6; const int DISTANCE_INCREMENT = 5; const int NUM_READINGS = 5; // SD Card Settings const byte SD_CS_PIN = 10; #define OUTPUT_FILENAME "ultra.txt" ARTF_SDCard sd(SD_CS_PIN); void setup() { Serial.begin(9600); pinMode(SD_CS_PIN, OUTPUT); } int count = 1; void loop() { LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF); String output = ""; output += "Trial " + String(count) + "\n"; output += "-------------------\n"; // Take X readings int distanceReadings[NUM_READINGS]; for (int i = 0; i < NUM_READINGS; ++i) { int reading = analogRead(ULTRASONIC_PIN); distanceReadings[i] = reading * DISTANCE_INCREMENT; output += String(i) + ". Analog:" + String(reading) + "; Calculated:" + String(distanceReadings[i]) + "\n"; delay(300); } // Average the readings double sumDistance = 0.0; for (int i = 0; i < NUM_READINGS; ++i) { sumDistance += distanceReadings[i]; } double avgDistance = sumDistance / NUM_READINGS; // Rounded measurements int roundedDistance = round(avgDistance); output += "Rounded:" + String(roundedDistance) + "\n\n"; sd.begin(); sd.writeFile(OUTPUT_FILENAME, output); delay(500); count += 1; }```
b7340c93-0c30-4fdb-aaa9-318f5041b7bb
{ "language": "Arduino" }
```arduino ``` Add initial robot motor body code
```arduino /* This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2 It won't work with v1.x motor shields! Only for the v2's with built in PWM control For use with the Adafruit Motor Shield v2 ----> http://www.adafruit.com/products/1438 */ #include <Wire.h> #include <Adafruit_MotorShield.h> #include "utility/Adafruit_MS_PWMServoDriver.h" Adafruit_MotorShield AFMSbot(0x60); // Default address, no jumpers Adafruit_MotorShield AFMStop(0x61); // Rightmost jumper closed Adafruit_DCMotor *motorMiddleLeft = AFMStop.getMotor(2); //Backwards Adafruit_DCMotor *motorFrontLeft = AFMStop.getMotor(3); // Forwards Adafruit_DCMotor *motorBackLeft = AFMStop.getMotor(1); // Backwards Adafruit_DCMotor *motorBackRight = AFMSbot.getMotor(2); // Backwards Adafruit_DCMotor *motorFrontRight = AFMSbot.getMotor(3); // Backwards Adafruit_DCMotor *motorMiddleRight = AFMSbot.getMotor(4); // Backwards void setup() { while (!Serial); Serial.begin(9600); // set up Serial library at 9600 bps Serial.println("MMMMotor party!"); AFMSbot.begin(); // Start the bottom shield AFMStop.begin(); // Start the top shield // turn on the DC motor motorMiddleLeft->setSpeed(100); motorMiddleLeft->run(BACKWARD); motorFrontLeft->setSpeed(100); motorFrontLeft->run(FORWARD); motorBackLeft->setSpeed(100); motorBackLeft->run(BACKWARD); motorBackRight->setSpeed(100); motorBackRight->run(BACKWARD); motorFrontRight->setSpeed(100); motorFrontRight->run(BACKWARD); motorMiddleRight->setSpeed(100); motorMiddleRight->run(BACKWARD); } void loop() { } ```
f570b414-91d1-4a22-b144-ca8ba27eb99b
{ "language": "Arduino" }
```arduino ``` Add Arduino sketch to test encoders and leds
```arduino // Total number of input channels supported by the hardware const uint8_t numChannels = 5; const uint8_t ledPins[] = {2, 4, 7, 8, 12}; const uint8_t encoderPins[] = {5, 6, 9, 10, 11}; unsigned long currentEncoderValues[] = {0, 0, 0, 0, 0}; unsigned long previousEncoderValues[] = {0, 0, 0, 0, 0}; const unsigned long encoderValueThreshold = 2048; // Number of active parameters in the sketch const uint8_t numParams = 4; /* * Tests the LEDs and encoders. * If the encoder value is over a given threshold, the corresponding LED is lit. */ void setup() { Serial.begin(57600); for (uint8_t i = 0; i < numChannels; i++) { pinMode(ledPins[i], OUTPUT); pinMode(encoderPins[i], INPUT); } } void loop() { for (uint8_t i = 0; i < numParams; i++) { previousEncoderValues[i] = currentEncoderValues[i]; currentEncoderValues[i] = pulseIn(encoderPins[i], HIGH); Serial.print(currentEncoderValues[i]); if (i < numParams - 1) { Serial.print(" "); } if (currentEncoderValues[i] > encoderValueThreshold) { digitalWrite(ledPins[i], HIGH); } else { digitalWrite(ledPins[i], LOW); } } Serial.println(); }```
26bbb0b0-6586-4a20-8283-388bc758cbfc
{ "language": "Arduino" }
```arduino ``` Test for accelerometer on sensorboard.
```arduino /* ADXL362_SimpleRead.ino - Simple XYZ axis reading example for Analog Devices ADXL362 - Micropower 3-axis accelerometer go to http://www.analog.com/ADXL362 for datasheet License: CC BY-SA 3.0: Creative Commons Share-alike 3.0. Feel free to use and abuse this code however you'd like. If you find it useful please attribute, and SHARE-ALIKE! Created June 2012 by Anne Mahaffey - hosted on http://annem.github.com/ADXL362 Modified May 2013 by Jonathan Ruiz de Garibay Connect SCLK, MISO, MOSI, and CSB of ADXL362 to SCLK, MISO, MOSI, and DP 10 of Arduino (check http://arduino.cc/en/Reference/SPI for details) */ #include <SPI.h> #include <ADXL362.h> ADXL362 xl; int16_t temp; int16_t XValue, YValue, ZValue, Temperature; void setup(){ Serial.begin(9600); xl.begin(10); // Setup SPI protocol, issue device soft reset xl.beginMeasure(); // Switch ADXL362 to measure mode Serial.println("Start Demo: Simple Read"); } void loop(){ // read all three axis in burst to ensure all measurements correspond to same sample time xl.readXYZTData(XValue, YValue, ZValue, Temperature); Serial.print("XVALUE="); Serial.print(XValue); Serial.print("\tYVALUE="); Serial.print(YValue); Serial.print("\tZVALUE="); Serial.print(ZValue); Serial.print("\tTEMPERATURE="); Serial.println(Temperature); delay(100); // Arbitrary delay to make serial monitor easier to observe } ```
c3a51de5-640c-48e9-afaf-a507d14489e1
{ "language": "Arduino" }
```arduino ``` Add project resources for Mote
```arduino #include <SoftwareSerial.h> // software serial #2: RX = digital pin 8, TX = digital pin 9 // on the Mega, use other pins instead, since 8 and 9 don't work on the Mega SoftwareSerial portTwo(8, 9); void setup() { pinMode(LED_BUILTIN, OUTPUT); // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } // Start each software serial portm portTwo.begin(9600); digitalWrite(LED_BUILTIN, LOW); } void loop() { // Now listen on the second port portTwo.listen(); // while there is data coming in, read it // and send to the hardware serial port: Serial.println("Data from port two:"); while (portTwo.available() > 0) { char inByte = portTwo.read(); delay(500); Serial.write(inByte); } } ```
1eda6412-efe9-48bb-a11f-a1af4fea1739
{ "language": "Arduino" }
```arduino ``` Add a file to control sabertooth board
```arduino // Software Serial Sample // Copyright (c) 2012 Dimension Engineering LLC // See license.txt for license details. #include <SoftwareSerial.h> #include <SabertoothSimplified.h> SoftwareSerial SWSerial(NOT_A_PIN, 11); // RX on no pin (unused), TX on pin 11 (to S1). SabertoothSimplified ST(SWSerial); // Use SWSerial as the serial port. void setup() { SWSerial.begin(9600); } void loop() { int power; // Ramp from -127 to 127 (full reverse to full forward), waiting 20 ms (1/50th of a second) per value. for (power = -127; power <= 127; power ++) { ST.motor(1, power); delay(20); } // Now go back the way we came. for (power = 127; power >= -127; power --) { ST.motor(1, power); delay(20); } } ```
251a3084-824d-40e3-82fc-24a5fb49a444
{ "language": "Arduino" }
```arduino ``` Add temp sensor example sketch
```arduino // TimerOne library: https://code.google.com/p/arduino-timerone/ #include <TimerOne.h> #include <SPI.h> #include <BLEPeripheral.h> // define pins (varies per shield/board) #define BLE_REQ 10 #define BLE_RDY 2 #define BLE_RST 9 BLEPeripheral blePeripheral = BLEPeripheral(BLE_REQ, BLE_RDY, BLE_RST); BLEService tempService = BLEService("CCC0"); BLEIntCharacteristic tempCharacteristic = BLEIntCharacteristic("CCC1", BLERead | BLENotify); BLEDescriptor tempDescriptor = BLEDescriptor("2901", "Celsius"); volatile bool readTemperature = false; void setup() { Serial.begin(115200); #if defined (__AVR_ATmega32U4__) //Wait until the serial port is available (useful only for the Leonardo) //As the Leonardo board is not reseted every time you open the Serial Monitor while(!Serial) {} delay(5000); //5 seconds delay for enabling to see the start up comments on the serial board #endif blePeripheral.setLocalName("Temperature"); blePeripheral.setAdvertisedServiceUuid(tempService.uuid()); blePeripheral.addAttribute(tempService); blePeripheral.addAttribute(tempCharacteristic); blePeripheral.addAttribute(tempDescriptor); blePeripheral.setEventHandler(BLEConnected, blePeripheralConnectHandler); blePeripheral.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler); blePeripheral.begin(); Timer1.initialize(1 * 1000000); // in milliseconds Timer1.attachInterrupt(timerHandler); } void loop() { blePeripheral.poll(); if (readTemperature) { setTempCharacteristicValue(); readTemperature = false; } } void timerHandler() { readTemperature = true; } void setTempCharacteristicValue() { int temp = readTempC(); tempCharacteristic.setValue(temp); Serial.println(temp); } int readTempC() { // Stubbing out for demo with random value generator // Replace with actual sensor reading code return random(100); } void blePeripheralConnectHandler(BLECentral& central) { Serial.print(F("Connected event, central: ")); Serial.println(central.address()); } void blePeripheralDisconnectHandler(BLECentral& central) { Serial.print(F("Disconnected event, central: ")); Serial.println(central.address()); } ```
467674e1-e8a0-411c-8b89-aeb4e1818a42
{ "language": "Arduino" }
```arduino ``` Test script for flashing LEDs on same port using AIO and DIO
```arduino /** * Use the schedule class to have two different LEDs on one JeeNode * port flash at different rates. One LED is on DIO and the other * AIO. * * This is a straight-forward modification of the sched_blinks.ino * sketch. * * Based largely on jcw's "schedule" and "blink_ports" sketches * * Changes: * - remove BlinkPlug specifics but use the same techniques. The * LEDs are wired between DIO/AIO and GND rather than VCC and * DIO/AIO as in the BlinkPlug code. * * Original "blink_ports" sketch: * 2009-02-13 <[email protected]> http://opensource.org/licenses/mit-license.php * Original "schedule" sketch: * 2010-10-18 <[email protected]> http://opensource.org/licenses/mit-license.php * Modifications * 2015-08-14 <[email protected]> http://opensource.org/licenses/mit-license.php */ #include <JeeLib.h> Port one (4); // Connect a series resistor (470 or 1k ohm) to two leds. Connect one // to pins 2 (DIO) and 3 (GND) on Jeenode port 4 and the other to pins // 5 (AIO) and 3 (GND). enum { TASK1, TASK2, TASK_LIMIT }; static word schedBuf[TASK_LIMIT]; Scheduler scheduler (schedBuf, TASK_LIMIT); byte led1, led2; // this has to be added since we're using the watchdog for low-power waiting ISR(WDT_vect) { Sleepy::watchdogEvent(); } void setup () { Serial.begin(57600); Serial.println("\n[schedule]"); Serial.flush(); // turn the radio off completely rf12_initialize(17, RF12_868MHZ); rf12_sleep(RF12_SLEEP); one.mode(OUTPUT); one.mode2(OUTPUT); led1 = 0; led2 = 0; // start both tasks 1.5 seconds from now scheduler.timer(TASK1, 15); scheduler.timer(TASK2, 15); } void loop () { switch (scheduler.pollWaiting()) { // LED 1 blinks .1 second every second case TASK1: led1 = !led1; if (led1) { one.digiWrite(1); scheduler.timer(TASK1, 1); } else { one.digiWrite(0); scheduler.timer(TASK1, 8); } break; // LED 2 blinks .5 second every second case TASK2: led2 = !led2; if (led2) { one.digiWrite2(1); scheduler.timer(TASK2, 1); } else { one.digiWrite2(0); scheduler.timer(TASK2, 3); } break; } } ```
404e3ff0-6922-4362-ac9d-bdd665ed9174
{ "language": "Arduino" }
```arduino ``` Add example demonstrating the simple `read()` command and SoftWire
```arduino // This example demonstrates how to use the HIH61xx class with the SoftWire library. SoftWire is a software I2C // implementation which enables any two unused pins to be used as a I2C bus. A blocking read is made to the // HIH61xx device. See HIH61xx_SoftWire_demo for a more sophisticated example which allows other tasks to run // whilst the HIH61xx takes its measurements. #include <SoftWire.h> #include <HIH61xx.h> #include <AsyncDelay.h> // Create an instance of the SoftWire class called "sw". In this example it uses the same pins as the hardware I2C // bus. Pass the pin numbers to use different pins. SoftWire sw(SDA, SCL); // The "hih" object must be created with a reference to the SoftWire "sw" object which represents the I2C bus it is // using. Note that the class for the SoftWire object must be included in the templated class name. HIH61xx<SoftWire> hih(sw); AsyncDelay samplingInterval; // SoftWire requires that the programmer declares the buffers used. This allows the amount of memory used to be set // according to need. For the HIH61xx only a very small RX buffer is needed. uint8_t i2cRxBuffer[4]; uint8_t i2cTxBuffer[32]; void setup(void) { #if F_CPU >= 12000000UL Serial.begin(115200); #else Serial.begin(9600); #endif // The pin numbers for SDA/SCL can be overridden at runtime. // sw.setSda(sdaPin); // sw.setScl(sclPin); sw.setRxBuffer(i2cRxBuffer, sizeof(i2cRxBuffer)); //sw.setTxBuffer(i2cTxBuffer, sizeof(i2cTxBuffer)); // HIH61xx doesn't need a TX buffer at all but other I2C devices probably will. //sw.setTxBuffer(i2cTxBuffer, sizeof(i2cTxBuffer)); sw.setTxBuffer(NULL, 0); sw.begin(); // Sets up pin mode for SDA and SCL hih.initialise(); samplingInterval.start(3000, AsyncDelay::MILLIS); } void loop(void) { // Instruct the HIH61xx to take a measurement. This blocks until the measurement is ready. hih.read(); // Fetch and print the results Serial.print("Relative humidity: "); Serial.print(hih.getRelHumidity() / 100.0); Serial.println(" %"); Serial.print("Ambient temperature: "); Serial.print(hih.getAmbientTemp() / 100.0); Serial.println(" deg C"); Serial.print("Status: "); Serial.println(hih.getStatus()); // Wait a second delay(1000); }```
d9af7fbf-8e65-48f7-870d-184ef4ed0c48
{ "language": "Arduino" }
```arduino ``` Test for checking the processing code
```arduino /* * User testing for the arduino * Two kinds of messages can be send to the arduino: * - 0-255 * - S,1,# * c rrrgggbbb * - L,1,C#########\n */ void setup() { // put your setup code here, to run once: Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: } // Serial event gets called when anything in the serial happens. void serialEvent() { String s = ""; while(Serial.available()) { char c = (char)Serial.read(); s += c; if (c == '\n') { Serial.print(s); } } } ```
398d8810-b1fc-4932-91bc-82a0f0a854ba
{ "language": "Arduino" }
```arduino ``` Implement IMU unit on Curie
```arduino #include "CurieIMU.h" void setup() { Serial.begin(9600); // Initialize internal IMU CurieIMU.begin(); // Set accelerometer range to 2G CurieIMU.setAccelerometerRange(2); } void loop() { float ax, ay, az; CurieIMU.readAccelerometerScaled(ax, ay, az); Serial.print("Value ax:"); Serial.print(ax); Serial.print(" / ay:"); Serial.print(ay); Serial.print(" / az:"); Serial.println(az); delay(100); } ```
0d632e16-4a28-44ec-9653-901f3fbe93f7
{ "language": "Arduino" }
```arduino ``` Add LED widget setColor example
```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. * ************************************************************** * Blynk using a LED widget on your phone! * * App project setup: * LED widget on V1 * * WARNING : * For this example you'll need SimpleTimer library: * https://github.com/jfturcot/SimpleTimer * Visit this page for more information: * http://playground.arduino.cc/Code/SimpleTimer * **************************************************************/ #define BLYNK_PRINT Serial // Comment this out to disable prints and save space #include <SPI.h> #include <Ethernet.h> #include <BlynkSimpleEthernet.h> #include <SimpleTimer.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourAuthToken"; WidgetLED led1(V1); SimpleTimer timer; #define BLYNK_GREEN "#23C48E" #define BLYNK_BLUE "#04C0F8" #define BLYNK_YELLOW "#ED9D00" #define BLYNK_RED "#D3435C" #define BLYNK_DARK_BLUE "#5F7CD8" void setup() { Serial.begin(9600); // See the connection status in Serial Monitor Blynk.begin(auth); timer.setInterval(1000L, blinkLedWidget); } // V1 LED Widget is blinking void blinkLedWidget() { if (led1.getValue()) { led1.setColor(BLYNK_RED); Serial.println("LED on V1: red"); } else { led1.setColor(BLYNK_GREEN); Serial.println("LED on V1: green"); } } void loop() { Blynk.run(); timer.run(); } ```
84d6aabb-2965-4544-9b8d-fe8156299470
{ "language": "Arduino" }
```arduino ``` Add SPI EEPROM 25LC040 example.
```arduino #include "mbed.h" // use fully qualified class name to resolve ambiguities with // Arduino's own global "SPI" object mbed::SPI spi(SPI_MOSI, SPI_MISO, SPI_SCK); DigitalOut cs(D10); RawSerial pc(USBTX, USBRX); static const uint8_t READ = 0x03; // read data from memory array static const uint8_t WRITE = 0x02; // write data to memory array static const uint8_t WRDI = 0x04; // disable write operations static const uint8_t WREN = 0x06; // enable write operations static const uint8_t RDSR = 0x05; // read STATUS register static const uint8_t WRSR = 0x01; // write STATUS register uint16_t address = 0; // 0..511 void setup() { // Chip must be deselected cs = 1; // Setup the spi for 8 bit data, high steady state clock, second // edge capture, with a 1MHz clock rate spi.format(8, 0); spi.set_default_write_value(0); } void loop() { const char tx_buffer[16] = "0123456789ABCDEF"; char rx_buffer[16]; pc.printf("write @0x%03x: %.16s\r\n", address, tx_buffer); cs = 0; wait_ms(1); spi.write(WREN); spi.write(0); wait_ms(1); cs = 1; wait_ms(1); cs = 0; wait_ms(1); spi.write(WRITE | ((address & 0x100) >> 5)); spi.write(address & 0xff); spi.write(tx_buffer, sizeof tx_buffer, 0, 0); wait_ms(1); cs = 1; wait_ms(1); cs = 0; wait_ms(1); spi.write(READ | ((address & 0x100) >> 5)); spi.write(address & 0xff); spi.write(0, 0, rx_buffer, sizeof rx_buffer); wait_ms(1); cs = 1; pc.printf("read @0x%03x: %.16s\r\n", address, rx_buffer); address += 16; address %= 512; wait(1); } #ifndef ARDUINO int main() { setup(); for (;;) { loop(); } } #endif ```
be8efdf0-4d03-41cf-8135-4a0cfd858a01
{ "language": "Arduino" }
```arduino ``` Add example showing one-shot usage
```arduino #include <AsyncDelay.h> AsyncDelay oneShot; bool messagePrinted = false; void setup(void) { Serial.begin(9600); Serial.println("Starting one-shot timer"); oneShot.start(5000, AsyncDelay::MILLIS); } void loop(void) { if (!messagePrinted && oneShot.isExpired()) { Serial.print("The timer was started "); Serial.print(oneShot.getDelay()); if (oneShot.getUnit() == AsyncDelay::MILLIS) Serial.println(" ms ago"); else Serial.println(" us ago"); messagePrinted = true; // Print the message just once oneShot = AsyncDelay(); } } ```
23b02c95-2eb5-4907-929c-72d442c0b62b
{ "language": "Arduino" }
```arduino ``` Add arduino Lidar and servo sweeping code
```arduino #include <I2C.h> #include <Servo.h> #define LIDARLite_ADDRESS 0x62 // Default I2C Address of LIDAR-Lite. #define RegisterMeasure 0x00 // Register to write to initiate ranging. #define MeasureValue 0x04 // Value to initiate ranging. #define RegisterHighLowB 0x8f // Register to get both High and Low bytes in 1 call. Servo myservo; int pos = 0; int range = 0; int STARTANGLE = 45; int ENDANGLE = 135; void setup() { Serial.begin(9600); //Opens serial connection at 9600bps. I2c.begin(); // Opens & joins the irc bus as master delay(100); // Waits to make sure everything is powered up before sending or receiving data I2c.timeOut(50); // Sets a timeout to ensure no locking up of sketch if I2C communication fails myservo.attach(13); } int getLidarRange(){ // Write 0x04 to register 0x00 uint8_t nackack = 100; // Setup variable to hold ACK/NACK resopnses while (nackack != 0) { // While NACK keep going (i.e. continue polling until sucess message (ACK) is received ) nackack = I2c.write(LIDARLite_ADDRESS, RegisterMeasure, MeasureValue); // Write 0x04 to 0x00 delay(1); // Wait 1 ms to prevent overpolling } byte distanceArray[2]; // array to store distance bytes from read function // Read 2byte distance from register 0x8f nackack = 100; // Setup variable to hold ACK/NACK resopnses while (nackack != 0) { // While NACK keep going (i.e. continue polling until sucess message (ACK) is received ) nackack = I2c.read(LIDARLite_ADDRESS, RegisterHighLowB, 2, distanceArray); // Read 2 Bytes from LIDAR-Lite Address and store in array delay(1); // Wait 1 ms to prevent overpolling } int distance = (distanceArray[0] << 8) + distanceArray[1]; // Shift high byte [0] 8 to the left and add low byte [1] to create 16-bit int return distance; } void spinAndScan(int pos){ // move servo to position myservo.write(pos); //scan and print distance range = getLidarRange(); Serial.print("range: "); Serial.print(range); Serial.print(" pos: "); Serial.println(pos - 90); } void loop() { for(pos = STARTANGLE; pos < ENDANGLE; pos += 1){ spinAndScan(pos); } for(pos = ENDANGLE; pos>=STARTANGLE; pos-=1){ spinAndScan(pos); } } ```
db0e5e75-865c-4e53-8529-094cbbaa2ca1
{ "language": "Arduino" }
```arduino ``` Add blink test for Attiny85
```arduino /* Blink Turns on an LED on for one second, then off for one second, repeatedly. This example code is in the public domain. */ // Pin 13 has an LED connected on most Arduino boards. // give it a name: int led = 3; int led2 = 4; // the setup routine runs once when you press reset: void setup() { // initialize the digital pin as an output. pinMode(led, OUTPUT); pinMode(led2, OUTPUT); } // the loop routine runs over and over again forever: void loop() { digitalWrite(led, HIGH); digitalWrite(led2, LOW); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(led, LOW); digitalWrite(led2, HIGH); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } ```
2b19c753-32b5-4a6a-af66-dab2d01d82cd
{ "language": "Arduino" }
```arduino ``` Add simple demo stuff for 2x2x2 cube
```arduino #define REP(x,n) for(int x=0;x<n;x++) #define ALL REP(i,2) REP(j,2) REP(k,2) const int DELAY = 10; int cube[2][2][2]; int cols[2][2] = {{8, 9}, {10, 11}}; int rows[2] = {6, 7}; void clear() { ALL cube[i][j][k] = 0; } void setup() { REP(i,2) pinMode(rows[i], OUTPUT); REP(i,2) REP(j,2) pinMode(cols[i][j], OUTPUT); } void randomIn(int time) { int count = 8; while(count > 0){ int x = random(2); int y = random(2); int z = random(2); if(cube[y][x][z]==0){ cube[y][x][z]=1; count--; show(time); } } } void layerSpiral(int i, int time) { REP(j,2) { cube[i][0][j] = 1; show(time); clear(); } REP(j,2) { cube[i][1][1-j] = 1; show(time); clear(); } } void layer(int i, int time) { REP(j,2) REP(k,2) cube[i][j][k] = 1; show(time); clear(); } void loop() { const int t = 100; REP(x,4) REP(l,2){ layer(l, 500); } REP(x,3) ALL { cube[i][j][k] = 1; show(t); clear(); } REP(x,3){ randomIn(t); clear(); } REP(i,3){ REP(l,2){ REP(x,3) layerSpiral(l, t); } } } void show(int time){ REP(t,time/DELAY/2){ REP(i,2){ digitalWrite(rows[i], LOW); REP(j,2) REP(k,2){ digitalWrite(cols[j][k], cube[i][j][k] ? HIGH : LOW); } delay(DELAY); digitalWrite(rows[i], HIGH); } } } ```
45a8365a-7809-499d-9780-05334d6bb4a9
{ "language": "Arduino" }
```arduino ``` Add simple teensy throughput program
```arduino //#define USE_BINARY const int sampleRate = 8000; const long serialRate = 2000000; const int NWORDS = 20; const int WSIZE = sizeof(uint16_t); const int NBYTES = NWORDS * WSIZE; volatile bool pushData = false; typedef union { uint16_t words[NWORDS]; uint8_t bytes[NBYTES]; } MODEL; MODEL m; IntervalTimer myTimer; void setup(void) { for (int i = 0; i < NWORDS; i++) m.words[i] = i+1000; pinMode(LED_BUILTIN, OUTPUT); SerialUSB.begin(serialRate); myTimer.begin(blinkLED, 1000000 / sampleRate); } void blinkLED(void) { pushData = true; } void loop(void) { static int counter = 0; bool state = (counter++ >> 12) % 2; digitalWrite(LED_BUILTIN, state ? HIGH : LOW); if (pushData) { pushData = false; #ifdef USE_BINARY SerialUSB.write(m.bytes, NBYTES); #else for (int i = 0; i < NWORDS; i++) { if (i!=0) SerialUSB.print('\t'); SerialUSB.print(m.words[i], DEC); } #endif SerialUSB.write('\n'); } } ```
84b06646-65ea-4de7-a675-17272e4a8383
{ "language": "Arduino" }
```arduino ``` Add next Arduino example - blinky with Timer1 COMPA.
```arduino /** * Copyright (c) 2019, Łukasz Marcin Podkalicki <[email protected]> * ArduinoUno/003 * Blinky with Timer1 COMPA. */ #define LED_PIN (13) void setup() { pinMode(LED_PIN, OUTPUT); // set LED pin as output TCCR1A = 0; // clear register TCCR1B = _BV(WGM12); // set Timer1 to CTC mode TCCR1B |= _BV(CS12)|_BV(CS10); // set Timer1 prescaler to 1024 TIMSK1 |= _BV(OCIE1A); // enable Timer1 COMPA interrupt OCR1A = 7812; // set value for Fx=1Hz, OCRnx = (16Mhz/(Fx * 2 * 1024) + 1) interrupts(); // enable global interrupts } void loop() { // do nothing } ISR(TIMER1_COMPA_vect) { digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle LED pin } ```
35e2825b-51b3-4e4b-b9a5-f48ec2842a9d
{ "language": "Arduino" }
```arduino ``` Add first Arduino example - blinky with delay function.
```arduino /** * Copyright (c) 2019, Łukasz Marcin Podkalicki <[email protected]> * ArduinoUno/001 * Blinky with delay function. */ #define LED_PIN (13) void setup() { pinMode(LED_PIN, OUTPUT); } void loop() { digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle LED pin delay(500); // wait 0.5s } ```
073a0e95-f9d6-4b65-aa42-40e62ea2d13c
{ "language": "Arduino" }
```arduino ``` Add code to read temperature and light to display on a LCD
```arduino /* * Read temperature and light and display on the LCD * * For: Arduino Uno R3 * * Parts: * 1x LCD (16x2 characters) * 1x 10 kΩ variable resistor * 1x 10 KΩ resistor * 1x 220 Ω resitor * 1x Photocell * 1x TMP36 temperature sensor */ #include <LiquidCrystal.h> int temperaturePin = 0; int lightPin = 1; LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { // Set columns and rows to use lcd.begin(16, 2); // Start on the first row lcd.print("Temp : C"); } void loop() { int temperatureReading = analogRead(temperaturePin); float temperatureInVolts = (temperatureReading / 1024.0) * 5.0; float temperatureInCelcius = (temperatureInVolts - 0.5) * 100; // Jump 6 columns lcd.setCursor(6, 0); lcd.print(temperatureInCelcius); int lightReading = analogRead(lightPin); // Jump to the next row lcd.setCursor(0, 1); lcd.print("Light: "); lcd.setCursor(6, 1); lcd.print(lightReading); delay(1000); } ```
274ba055-f22a-4c69-9c4c-e311a149ed88
{ "language": "Arduino" }
```arduino ``` Add test sketch for moisture sensor and sd card on kit
```arduino /* Test Moisture sensor readings on sensor platform This sketch is designed to test the accuracy of the Moisture sensor with the battery pack and circuit of the sensor platform. This sketch takes 5 readings and averages them to help verify similar calculations used in MoistureSensorGSM sketch. The results are written to the SD card Created 10 7 2014 Modified 10 7 2014 */ #include <LowPower.h> #include <ARTF_SDCard.h> // ARTF SDCard Dependency #include <SdFat.h> #include <String.h> // Moisture sensor settings const byte MOISTURE_PIN = A6; const byte MOSFET_MS_PIN = 5; const int NUM_READINGS = 5; const int MOISTURE_MAX_READING = 600; // SD Card Settings const byte SD_CS_PIN = 10; #define OUTPUT_FILENAME "ultra.txt" ARTF_SDCard sd(SD_CS_PIN); void setup() { Serial.begin(9600); pinMode(SD_CS_PIN, OUTPUT); } int count = 1; void loop() { LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF); String output = ""; output += "Trial " + String(count) + "\n"; output += "-------------------\n"; digitalWrite(MOSFET_MS_PIN, HIGH); delay(3000); // Take X readings int moistureReadings[NUM_READINGS]; for (int i = 0; i < NUM_READINGS; ++i) { int reading = analogRead(MOISTURE_PIN); moistureReadings[i] = (double)reading / (double)MOISTURE_MAX_READING; output += String(i) + ". Analog:" + String(reading) + "; Calculated:" + String(moistureReadings[i]) + "\n"; delay(300); } digitalWrite(MOSFET_MS_PIN, LOW); delay(500); // Average the readings double sumMoisture = 0.0; for (int i = 0; i < NUM_READINGS; ++i) { sumMoisture += moistureReadings[i]; } double avgMoisture = sumMoisture / NUM_READINGS; // Rounded measurements int roundedMoisture = round(avgMoisture * 100); output += "Rounded:" + String(roundedMoisture) + "\n\n"; sd.begin(); sd.writeFile(OUTPUT_FILENAME, output); delay(500); count += 1; }```
23707c81-975a-4545-9b9c-5bbc452761ee
{ "language": "Arduino" }
```arduino ``` Add pseudoRandom Demo for Science Museum project
```arduino /* * pseudoRandom Demonstration sketch * Author: Darrell Little * Date: 04/29/2017 * This code is in the public domain */ // Array to hold the pin numbers with LED connected int ledPin[] = {11,10,9,6}; // Variable to set the delay time to blink int waitTime = 1000; // Variable to hold the random LED pin to blink int randomLED; void setup() { // put your setup code here, to run once: // Use reading on Analog pin 0 for a randon seed randomSeed(analogRead(0)); // Initialize each pin in array to Output and Low (off) for (int x=0; x<4; x++) { pinMode(ledPin[x], OUTPUT); digitalWrite(ledPin[x], LOW); } } void loop() { // put your main code here, to run repeatedly: // Randomly select a LED pin number randomLED = random(0,4); // Turn LED on digitalWrite(ledPin[randomLED], HIGH); delay(waitTime); // Turn LED off digitalWrite(ledPin[randomLED], LOW); delay(waitTime); } ```
15f2f42e-6140-4de5-baea-7593057425c5
{ "language": "Arduino" }
```arduino ``` Add original code for writing to SD card.
```arduino #include <SD.h> #include <SPI.h> void setup() { //this is needed for the duemilanove and uno without ethernet shield const int sdCardPin = 10; int loopCount = 0; //for testing. delete before launches. Serial.begin(9600); delay(1000); pinMode(10,OUTPUT); if (!SD.begin(sdCardPin)) { Serial.println("Card failed, or not present"); // don't do anything more: return; } Serial.println("card initialized."); } void loop() { sdWrite("none"); } /* Filename MUST be <=8 characters (not including the file extension) or the file will not be created */ bool sdWrite(String data) { File dataFile = SD.open("alex.txt", FILE_WRITE); // if the file is available, write to it: if (dataFile) { dataFile.println(data); dataFile.close(); // print to the serial port too: Serial.println(data); } // if the file isn't open, pop up an error: else { Serial.println("error opening file"); dataFile.close(); } } ```
9c80aa3e-6806-4049-a377-32f529faacf7
{ "language": "Arduino" }
```arduino ``` Add script to read HX711 and load cell
```arduino /* Inspired from code HX711 demo from Nathan Seidle, SparkFun Electronics This example code uses bogde's excellent library: https://github.com/bogde/HX711 bogde's library is released under a GNU GENERAL PUBLIC LICENSE The HX711 does one thing well: read load cells. T Arduino pin (Nano) 2 -> HX711 CLK 3 -> HX711 DAT 3V3 -> HX711 VCC GND -> HX711 GND 5V -> Radio VCC 4 -> Radio GND RX -> Radio TX TX -> Radio RX The HX711 board can be powered from 2.7V to 5V so the Arduino 5V power should be fine. */ #include "HX711.h" #define calibration_factor -7050.0 //This value is obtained using the SparkFun_HX711_Calibration sketch #define DOUT 3 #define CLK 2 #define GND 4 HX711 scale(DOUT, CLK); void setup() { pinMode(GND, OUTPUT); Serial.begin(57600); Serial.println("HX711 scale demo"); // Result of calibration scale.set_offset(8177300); scale.set_scale(-146.7); //Read the raw value Serial.println("Readings:"); } void loop() { digitalWrite(GND, LOW); Serial.print("Reading: "); Serial.print(scale.read_average(), 1); //raw value Serial.print(" "); Serial.print(scale.get_units(), 1); //scaled and offset after calibration Serial.print(" g"); Serial.println(); } ```
2df82691-69a6-4044-a58c-a15c7e232c18
{ "language": "Arduino" }
```arduino ``` Add early version of ship station demonstration software for OSU Expo
```arduino #include <AccelStepper.h> #include <MultiStepper.h> #include <math.h> /* Written for ST6600 stepper driver * PUL+ 5v * PUL- Arduino pin 9/11 * DIR+ 5v * DIR- Arduino pin 8/10 * DC+ 24v power supply * DC- Gnd on power supply & Gnd on Arduino */ // Each step is 0.12 degrees, or 0.002094395 radians #define STEPANGLE 0.002094395 #define PI 3.1415926535897932384626433832795 AccelStepper xAxis(1,8,9); AccelStepper yAxis(1,10,11); MultiStepper steppers; long positions[2]; // x, y float angle = 0; // Radians, used to find x,y on a circle long centerX = 0; // May be useful later long centerY = 0; long radius = 100; void setup() { // Initialize pins pinMode(8, OUTPUT); // x direction pin pinMode(9, OUTPUT); // x step pin pinMode(10, OUTPUT); // y direction pin pinMode(11, OUTPUT); // y step pin Serial.begin(115200); // Adjust these values after seeing it in action. xAxis.setMaxSpeed(300); xAxis.setAcceleration(100); yAxis.setMaxSpeed(300); yAxis.setAcceleration(100); // Add individual steppers to the multistepper object steppers.addStepper(xAxis); steppers.addStepper(yAxis); } void updatePos(float degs) { // Moves to a point on a circle, based on radius and angle // Blocks until finished float rads = degs * PI / 180; positions[0] = radius*cos(rads)+centerX; // x positions[1] = radius*sin(rads)+centerY; // y Serial.print("Deg = "); Serial.print(degs); Serial.print(", "); Serial.print(positions[0]); Serial.print(", "); Serial.print(positions[1]); Serial.println("."); steppers.moveTo(positions); steppers.runSpeedToPosition(); } void loop() { // Spiral outwards for(int degs=0; degs<360; degs++){ updatePos(degs); radius += 10; } // Spiral inwards for(int degs=360; degs>0; degs--){ updatePos(degs); radius -= 10; } } ```
a3f80522-7585-4f7c-b4ea-a0315c3004fe
{ "language": "Arduino" }
```arduino ``` Add support for Arduino MKR ETH shield
```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 Arduino MKR ETH shield to connect your project to Blynk. Note: This requires the latest Ethernet library (2.0.0+) from http://librarymanager/all#Ethernet WARNING: If you have an SD card, you may need to disable it by setting pin 4 to HIGH. Read more here: https://www.arduino.cc/en/Main/ArduinoEthernetShield Feel free to apply it to any other example. It's simple! *************************************************************/ /* Comment this out to disable prints and save space */ #define BLYNK_PRINT Serial #include <SPI.h> #include <Ethernet.h> #include <BlynkSimpleEthernet.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourAuthToken"; #define MKRETH_CS 5 #define SDCARD_CS 4 void setup() { // Debug console Serial.begin(9600); pinMode(SDCARD_CS, OUTPUT); digitalWrite(SDCARD_CS, HIGH); // Deselect the SD card Ethernet.init(MKRETH_CS); // Init MKR ETH shield Blynk.begin(auth); // You can also specify server: //Blynk.begin(auth, "blynk-cloud.com", 80); //Blynk.begin(auth, IPAddress(192,168,1,100), 8080); // For more options, see Boards_Ethernet/Arduino_Ethernet_Manual example } void loop() { Blynk.run(); } ```
8e2d7cd8-9b06-4f84-80d8-abfc8555c4e6
{ "language": "Arduino" }
```arduino ``` Add example for storing JSON config file in SPIFFS
```arduino // Example: storing JSON configuration file in flash file system // // Uses ArduinoJson library by Benoit Blanchon. // https://github.com/bblanchon/ArduinoJson // // Created Aug 10, 2015 by Ivan Grokhotkov. // // This example code is in the public domain. #include <ArduinoJson.h> #include "FS.h" bool loadConfig() { File configFile = SPIFFS.open("/config.json", "r"); if (!configFile) { Serial.println("Failed to open config file"); return false; } size_t size = configFile.size(); if (size > 1024) { Serial.println("Config file size is too large"); return false; } // Allocate a buffer to store contents of the file. std::unique_ptr<char[]> buf(new char[size]); // We don't use String here because ArduinoJson library requires the input // buffer to be mutable. If you don't use ArduinoJson, you may as well // use configFile.readString instead. configFile.readBytes(buf.get(), size); StaticJsonBuffer<200> jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); if (!json.success()) { Serial.println("Failed to parse config file"); return false; } const char* serverName = json["serverName"]; const char* accessToken = json["accessToken"]; // Real world application would store these values in some variables for // later use. Serial.print("Loaded serverName: "); Serial.println(serverName); Serial.print("Loaded accessToken: "); Serial.println(accessToken); return true; } bool saveConfig() { StaticJsonBuffer<200> jsonBuffer; JsonObject& json = jsonBuffer.createObject(); json["serverName"] = "api.example.com"; json["accessToken"] = "128du9as8du12eoue8da98h123ueh9h98"; File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { Serial.println("Failed to open config file for writing"); return false; } json.printTo(configFile); return true; } void setup() { Serial.begin(115200); Serial.println(""); delay(1000); Serial.println("Mounting FS..."); if (!SPIFFS.begin()) { Serial.println("Failed to mount file system"); return; } if (!saveConfig()) { Serial.println("Failed to save config"); } else { Serial.println("Config saved"); } if (!loadConfig()) { Serial.println("Failed to load config"); } else { Serial.println("Config loaded"); } } void loop() { } ```
75e8316d-9245-4b0b-b0d8-e81af1fc0267
{ "language": "Arduino" }
```arduino ``` Add STM32F103 Blue Pill example
```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! * * Requires STM32duino: https://github.com/rogerclarkmelbourne/Arduino_STM32/wiki/Installation * ************************************************************** * USB HOWTO: http://tiny.cc/BlynkUSB **************************************************************/ #define BLYNK_PRINT Serial2 #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 console Serial2.begin(9600); // Blynk will work through Serial Serial.begin(9600); Blynk.begin(auth, Serial); } void loop() { Blynk.run(); } ```
f13b7c70-5239-481e-8f2c-85d5eed0f153
{ "language": "Arduino" }
```arduino ``` Add example for storing JSON config file in SPIFFS
```arduino // Example: storing JSON configuration file in flash file system // // Uses ArduinoJson library by Benoit Blanchon. // https://github.com/bblanchon/ArduinoJson // // Created Aug 10, 2015 by Ivan Grokhotkov. // // This example code is in the public domain. #include <ArduinoJson.h> #include "FS.h" bool loadConfig() { File configFile = SPIFFS.open("/config.json", "r"); if (!configFile) { Serial.println("Failed to open config file"); return false; } size_t size = configFile.size(); if (size > 1024) { Serial.println("Config file size is too large"); return false; } // Allocate a buffer to store contents of the file. std::unique_ptr<char[]> buf(new char[size]); // We don't use String here because ArduinoJson library requires the input // buffer to be mutable. If you don't use ArduinoJson, you may as well // use configFile.readString instead. configFile.readBytes(buf.get(), size); StaticJsonBuffer<200> jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); if (!json.success()) { Serial.println("Failed to parse config file"); return false; } const char* serverName = json["serverName"]; const char* accessToken = json["accessToken"]; // Real world application would store these values in some variables for // later use. Serial.print("Loaded serverName: "); Serial.println(serverName); Serial.print("Loaded accessToken: "); Serial.println(accessToken); return true; } bool saveConfig() { StaticJsonBuffer<200> jsonBuffer; JsonObject& json = jsonBuffer.createObject(); json["serverName"] = "api.example.com"; json["accessToken"] = "128du9as8du12eoue8da98h123ueh9h98"; File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { Serial.println("Failed to open config file for writing"); return false; } json.printTo(configFile); return true; } void setup() { Serial.begin(115200); Serial.println(""); delay(1000); Serial.println("Mounting FS..."); if (!SPIFFS.begin()) { Serial.println("Failed to mount file system"); return; } if (!saveConfig()) { Serial.println("Failed to save config"); } else { Serial.println("Config saved"); } if (!loadConfig()) { Serial.println("Failed to load config"); } else { Serial.println("Config loaded"); } } void loop() { } ```
3775ad4f-dd0f-458f-822c-be547506a752
{ "language": "Arduino" }
```arduino ``` Add 'ino' file to allow build from Arduino IDE
```arduino /* Stub to allow build from Arduino IDE */ /* Includes to external libraries */ #include <MemoryFree.h> #include <Countdown.h> #include <MQTTClient.h> #include <SoftwareSerial.h> ```
c5279c84-23e9-4da2-9af5-d1ec3b1851a4
{ "language": "Arduino" }
```arduino ``` Include code sample for Arduino
```arduino char incomingByte = 0; const char lampCount = 4; const unsigned short doorUnlockTime = 2000; // in miliseconds bool lampStatus[lampCount]; bool doorStatus; unsigned short doorUnlockTimer; void setup() { Serial.begin(9600); pinMode(13, OUTPUT); for (int i = 0; i < lampCount; ++i) lampStatus[i] = false; doorStatus = false; } void loop() { if (Serial.available() > 2) { // Option can be 'r' (read) or 'w' (write) incomingByte = Serial.read(); if (incomingByte == 'r') { // Option can be 'l' (lamp) or 'd' (door) incomingByte = Serial.read(); if (incomingByte == 'l') { // Option can be 0 to (lampCount-1) (lamp id) incomingByte = Serial.read(); if (incomingByte < lampCount) Serial.write(lampStatus[incomingByte]); } else if (incomingByte == 'd') { // Discard last byte, since door does not have id and last byte has to be consumed Serial.read(); Serial.write(doorStatus); } } else if (incomingByte == 'w') { // Option can be 'l' (lamp) or 'd' (door) incomingByte = Serial.read(); if (incomingByte == 'l') { // Option can be 0 to (lampCount-1) (lamp id) incomingByte = Serial.read(); if (incomingByte < lampCount) { // TODO: Logic to invert lamp status lampStatus[incomingByte] = !lampStatus[incomingByte]; } } else if (incomingByte == 'd') { // Discard last byte, since door does not have id and last byte has to be consumed Serial.read(); // TODO: Logic to unlock the door doorStatus = true; doorUnlockTimer = doorUnlockTime; } } } if (doorUnlockTimer > 0) { digitalWrite(13, HIGH); --doorUnlockTimer; } else { // TODO: Logic to lock the door? digitalWrite(13, LOW); doorStatus = false; } // Delay to make board timing predictable delay(1); } ```
e9c9f3e8-1998-4ab8-b180-115ea8ff69f7
{ "language": "Arduino" }
```arduino ``` Add motor control arduino sketch
```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(")")); } } } ```
ec4fb158-c5f2-418a-ac10-ee8374b9a178
{ "language": "Arduino" }
```arduino ``` Add example of using serial
```arduino #include "VdlkinoSerial.h" VdlkinoSerial vdlkino(14, 6, &Serial); void setup() { Serial.begin(9600); } void loop() { vdlkino.run(); } ```
bcd5bda8-3780-4b9b-985d-e07c0aae8b87
{ "language": "Arduino" }
```arduino ``` Add an example of how to determine the gain setting for a filter.
```arduino // Gain Setting Example // Demonstrates the filter response with unity input to // get the appropriate value for the filter gain setting. #include <FIR.h> // Make an instance of the FIR filter. In this example we'll use // floating point values and a 13 element filter. FIR<long, 13> fir; void setup() { Serial.begin(115200); // Start a serial port // Use an online tool to get these such as http://t-filter.engineerjs.com // This filter rolls off after 2 Hz for a 10 Hz sampling rate. long coef[13] = { 660, 470, -1980, -3830, 504, 10027, 15214, 10027, 504, -3830, -1980, 470, 660}; // Set the coefficients fir.setFilterCoeffs(coef); // Set the gain to 1 to find the actual gain. // After running this sketch you'll see the gain // value sould be 26916. long gain = 1; // Set the gain fir.setGain(gain); } void loop() { // Need to run at least the length of the filter. for (float i=0; i < 14; i++) { Serial.print("Iteration "); Serial.print(i+1); Serial.print(" -> "); Serial.println(fir.processReading(1)); // Input all unity values } while (true) {}; // Spin forever } ```
ddcd377a-f5bb-431c-b44e-f02eb7dab84a
{ "language": "Arduino" }
```arduino ``` Add Feather M0 WiFi example
```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 Adafruit Feather M0 WiFi * to connect your project to Blynk. * * Note: This requires WiFi101 library * from http://librarymanager/all#WiFi101 * * Feel free to apply it to any other example. It's simple! * **************************************************************/ #define BLYNK_PRINT Serial // Comment this out to disable prints and save space #include <WiFi101.h> #include <BlynkSimpleWiFiShield101.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourAuthToken"; // Your WiFi credentials. // Set password to "" for open networks. char ssid[] = "YourNetworkName"; char pass[] = "YourPassword"; void setup() { Serial.begin(9600); WiFi.setPins(8,7,4,2); Blynk.begin(auth, ssid, pass); // Or specify server using one of those commands: //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 8442); //Blynk.begin(auth, ssid, pass, server_ip, port); } void loop() { Blynk.run(); } ```
571e161b-390d-4785-9d9c-9a5f6f008216
{ "language": "Arduino" }
```arduino ``` Add program to adjust pixel color with three potentiometers.
```arduino /* * neopixel_rgb_knob * * This is a test program to adjust the rgb of a strip of * neopixels useing three potentiometers. */ #include <Adafruit_NeoPixel.h> #ifdef __AVR__ #include <avr/power.h> // Required for 16 MHz Adafruit Trinket #endif // Which pin on the Arduino is connected to the NeoPixels? // On a Trinket or Gemma we suggest changing this to 1: #define LED_PIN 6 // How many NeoPixels are attached to the Arduino? #define LED_COUNT 8 // Declare our NeoPixel strip object: Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800); /* Set up three potentiometers to adjust the rgb colors */ #define knob_r 0 #define knob_g 1 #define knob_b 2 void setup() { // put your setup code here, to run once: // These lines are specifically to support the Adafruit Trinket 5V 16 MHz. // Any other board, you can remove this part (but no harm leaving it): #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000) clock_prescale_set(clock_div_1); #endif // END of Trinket-specific code. strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED) strip.show(); // Turn OFF all pixels ASAP strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255) } void loop() { // put your main code here, to run repeatedly: int r, g, b; /* Get each of the rgb values and then map from 0-1023 to 0-255. */ r = analogRead(knob_r); r = map(r, 0, 1023, 0, 255); g = analogRead(knob_g); g = map(g, 0, 1023, 0, 255); b = analogRead(knob_b); b = map(b, 0, 1023, 0, 255); /* set all of the pixels to the same color */ setAll(r, g, b); } /* Simple function to set all of the neopixels to the same color */ void setAll(byte red, byte green, byte blue) { for(int i = 0; i < LED_COUNT; i++ ) { strip.setPixelColor(i, red, green, blue); } strip.show(); } ```
2589d3bf-86ff-44e1-80ed-75058f9b4eb9
{ "language": "Arduino" }
```arduino ``` Add Arduino code for reporting temperature sensor data.
```arduino #include <OneWire.h> #include <DallasTemperature.h> // Change these if appropriate // The pin that sensors are connected to #define ONE_WIRE_BUS 2 // What precision to set the sensor to #define TEMPERATURE_PRECISION 11 OneWire one_wire(ONE_WIRE_BUS); DallasTemperature sensors(&one_wire); // We will store an array of probes we find on initial startup. If you have // more than 20 probes, feel free to bump this number and see if it'll actually // work at all. DeviceAddress probes[20]; int num_probes = 0; void setup() { Serial.begin(9600); sensors.begin(); // Set all devices to the same resolution sensors.setResolution(TEMPERATURE_PRECISION); // Find our sensors, use num_probes as a handy counter. one_wire.reset_search(); while (one_wire.search(probes[num_probes])) { num_probes++; } } void print_address(DeviceAddress device_address) { // Device address is 8 bytes, iterate over them. for (byte i = 0; i < 8; i++) { if (device_address[i] < 16) { Serial.print("0"); } Serial.print(device_address[i], HEX); } } void print_reading(DeviceAddress device_address) { // Print out data in the form of ADDRESS:TEMPERATURE // This bit's annoying enough to get its own function print_address(device_address); Serial.print(":"); Serial.print(sensors.getTempC(device_address)); Serial.print('\n'); } void loop() { // Make sure we're not just spitting out some constant meaningless numbers sensors.requestTemperatures(); for (int i = 0; i < num_probes; i++) { print_reading(probes[i]); } } ```
3af0d6c2-efc4-4d12-ab29-a8735fb04d89
{ "language": "Arduino" }
```arduino ``` Add Bluetooth 2.0 Serial Port Profile (SPP) example
```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 Arduino with HC-06/HC-05 * Bluetooth 2.0 Serial Port Profile (SPP) module * to connect your project to Blynk. * * Feel free to apply it to any other example. It's simple! * * NOTE: Bluetooth support is in beta! * **************************************************************/ // You could use a spare Hardware Serial on boards that have it (like Mega) #include <SoftwareSerial.h> SoftwareSerial DebugSerial(2, 3); // RX, TX #define BLYNK_PRINT DebugSerial #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 console DebugSerial.begin(9600); // Blynk will work through Serial Serial.begin(9600); Blynk.begin(auth, Serial); } void loop() { Blynk.run(); } ```
078296b2-d7b9-46da-9241-1c66076b201d
{ "language": "Arduino" }
```arduino ``` Add Arduino program for working with Analog data
```arduino const int analogInPin = A0; const int analogOutPin = 3; int sensorValue = 0; int outputValue = 0; void setup() { Serial.begin(9600); } void loop() { sensorValue = analogRead(analogInPin); outputValue = map(sensorValue, 0, 1023, 0, 255); analogWrite(analogOutPin, outputValue); // print the results to the serial monitor: Serial.print("sensor = " ); Serial.print(sensorValue); Serial.print("\t output = "); Serial.println(outputValue); delay(250); } ```
1556db59-a128-465c-899d-b95e8a0a8a1f
{ "language": "Arduino" }
```arduino ``` Add canbus FD receive interrupt example
```arduino // demo: CAN-BUS Shield, receive data with interrupt mode // when in interrupt mode, the data coming can't be too fast, must >20ms, or else you can use check mode // loovee, 2014-6-13 #include <SPI.h> #include "mcp2518fd_can.h" /*SAMD core*/ #ifdef ARDUINO_SAMD_VARIANT_COMPLIANCE #define SERIAL SerialUSB #else #define SERIAL Serial #endif #define CAN_2518FD // the cs pin of the version after v1.1 is default to D9 // v0.9b and v1.0 is default D10 const int SPI_CS_PIN = BCM8; const int CAN_INT_PIN = BCM25; #ifdef CAN_2518FD mcp2518fd CAN(SPI_CS_PIN); // Set CS pin #endif unsigned char flagRecv = 0; unsigned char len = 0; unsigned char buf[64]; char str[20]; void setup() { SERIAL.begin(115200); while (!SERIAL) { ; // wait for serial port to connect. Needed for native USB port only } CAN.setMode(0); while (0 != CAN.begin((byte)CAN_500K_1M)) { // init can bus : baudrate = 500k SERIAL.println("CAN BUS Shield init fail"); SERIAL.println(" Init CAN BUS Shield again"); delay(100); } byte mode = CAN.getMode(); SERIAL.printf("CAN BUS get mode = %d\n\r",mode); SERIAL.println("CAN BUS Shield init ok!"); SERIAL.println("CAN BUS Shield init ok!"); pinMode(CAN_INT_PIN, INPUT); attachInterrupt(digitalPinToInterrupt(CAN_INT_PIN), MCP2515_ISR, FALLING); // start interrupt } void MCP2515_ISR() { flagRecv = 1; } void loop() { if (flagRecv) { // check if get data flagRecv = 0; // clear flag SERIAL.println("into loop"); // iterate over all pending messages // If either the bus is saturated or the MCU is busy, // both RX buffers may be in use and reading a single // message does not clear the IRQ conditon. while (CAN_MSGAVAIL == CAN.checkReceive()) { // read data, len: data length, buf: data buf SERIAL.println("checkReceive"); CAN.readMsgBuf(&len, buf); // print the data for (int i = 0; i < len; i++) { SERIAL.print(buf[i]); SERIAL.print("\t"); } SERIAL.println(); } } } /********************************************************************************************************* END FILE *********************************************************************************************************/ ```
38899b52-3044-4a75-8f79-db90dd77d274
{ "language": "Arduino" }
```arduino ``` Switch keyboard with resistor ladder
```arduino int notes[] = {262, 294, 330, 349}; void setup() { Serial.begin(9600); } void loop() { int keyVal = analogRead(A0); Serial.println(keyVal); if (keyVal == 1023) { tone(8, notes[0]); } else if (keyVal >= 950 && keyVal <= 1010) { tone(8, notes[1]); } else if (keyVal >= 505 && keyVal <= 515) { tone(8, notes[2]); } else if (keyVal >= 5 && keyVal <= 10) { tone(8, notes[3]); } else { noTone(8); } } ```
a9853e42-19f4-4ebc-87e4-dd50e2ce4a5e
{ "language": "Arduino" }
```arduino ``` Add separate Blynk Board example. It deserves one! ;)
```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 runs on Sparkfun Blynk Board. * * You need to install this for ESP8266 development: * https://github.com/esp8266/Arduino * * NOTE: You can select NodeMCU 1.0 (compatible board) * in the Tools -> Board menu * * Change WiFi ssid, pass, and Blynk auth token to run :) * **************************************************************/ #define BLYNK_PRINT Serial // Comment this out to disable prints and save space #include <ESP8266WiFi.h> #include <BlynkSimpleEsp8266.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourAuthToken"; // Your WiFi credentials. // Set password to "" for open networks. char ssid[] = "YourNetworkName"; char pass[] = "YourPassword"; void setup() { Serial.begin(9600); Blynk.begin(auth, ssid, pass); } void loop() { Blynk.run(); } ```
9da258e7-b9c6-4ca9-b7a5-f8cf322396b3
{ "language": "Arduino" }
```arduino ``` Add stub implementation for NodeMCU implementation
```arduino #include <ESP8266WiFi.h> const char* ssid = "FRITZ!Box Fon WLAN 7360"; const char* password = "62884846722859294257"; const char* host = "192.168.178.34"; char* clientId = "photo1"; char* requestBody = "{ \"name\":\"%s\", \"weatherData\": { \"temperature\":\"%f\", \"humidity\":\"%f\" } }"; int delayInMillis = 10000; void setup() { Serial.begin(115200); delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } int value = 0; void loop() { delay(5000); ++value; Serial.print("connecting to "); Serial.println(host); // Use WiFiClient class to create TCP connections WiFiClient client; const int httpPort = 8080; if (!client.connect(host, httpPort)) { Serial.println("connection failed"); return; } String url = "/devices"; Serial.print("Requesting URL: "); Serial.println(url); //char* body = printf(requestBody, clientId, "90", "44"); // This will send the request to the server client.print("POST " + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n" + "Content-Type: application/json\r\n" + "Content-Length: 73\r\n" + "\r\n" + "{\"name\":\"node2\", \"weatherData\": { \"temperature\":\"33\", \"humidity\":\"55\" } }"); unsigned long timeout = millis(); while (client.available() == 0) { if (millis() - timeout > 8000) { Serial.println(">>> Client Timeout !"); client.stop(); return; } } // Read all the lines of the reply from server and print them to Serial while(client.available()){ String line = client.readStringUntil('\r'); Serial.print(line); } Serial.println(); Serial.println("closing connection"); } ```