Close

Arduino Code Snippets

JanJan wrote 10/17/2017 at 19:48 • 2 min read • Like

Working code snippets

1. read DS18B20 at interval. output via terminal. non-blocking code

#include <OneWire.h>
#include <DallasTemperature.h>
#include <elapsedMillis.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensor(&oneWire);
uint8_t SensorAdresse[8] = {0x28, 0x56, 0x2D, 0x11, 0x05, 0x00, 0x00, 0x14};
elapsedMillis SensorIntervall;
unsigned int Intervall = 1000;
void setup(void)
{
  Serial.begin(9600);
  sensor.begin();
  sensor.setResolution(SensorAdresse, 10);
  /*Berechnungszeiten (sind hier unwichtig, Code nicht blockend):
   *  9Bit Auflösung (0,5°C)  ->  102ms  
   * 10Bit Auflösung (0,25°C) ->  200ms
   * 12Bit Auflösung          ->  750ms
   */
  // LOG-Kopfausgabe:
  Serial.println("Ausgabeformat CSV, Trenner = ;");
  Serial.println("Zeit [s]; Temperatur [°C]");
  Serial.println("");
   
}
void loop(void)
{
    sensor.setWaitForConversion(false);
    sensor.requestTemperatures();
    float tempC = sensor.getTempC(SensorAdresse);
    sensor.setWaitForConversion(true);
  
  if (SensorIntervall > Intervall)
  {
    Serial.print(millis()/1000);
    Serial.print(";");
    Serial.println(tempC);
    SensorIntervall = 0;
  }
}

2. Show DS3231/DS1307 time on 32x128 I2C OLED display

#include <Wire.h>
#include "SSD1306Ascii.h"
#include "SSD1306AsciiWire.h"
#include <RtcDS3231.h>

RtcDS3231<TwoWire> Rtc(Wire);

// 0X3C+SA0 - 0x3C or 0x3D
#define I2C_ADDRESS 0x3C

// Define proper RST_PIN if required.
#define RST_PIN -1

SSD1306AsciiWire oled;

#define countof(a) (sizeof(a) / sizeof(a[0]))

void printTimeOnly(const RtcDateTime& dt)
{
  char datestring[11];

  snprintf_P(datestring,
             countof(datestring),
             PSTR("%02u:%02u:%02u"),
             dt.Hour(),
             dt.Minute(),
             dt.Second() );
  oled.println(datestring);
}

void printDateOnly(const RtcDateTime& dt)
{
  char datestring[11];

  snprintf_P(datestring,
             countof(datestring),
             PSTR("%02u.%02u.%02u"),
             dt.Day(),
             dt.Month(),
             dt.Year() - 2000);
  oled.println(datestring);
}

void setup() {
  Wire.begin();
  Wire.setClock(400000L);

#if RST_PIN >= 0
  oled.begin(&Adafruit128x32, I2C_ADDRESS, RST_PIN);
#else // RST_PIN >= 0
  oled.begin(&Adafruit128x32, I2C_ADDRESS);
#endif // RST_PIN >= 0

  oled.setFont(lcdnums12x16);

  Rtc.Begin();

  oled.clear();

}
void loop() {
  RtcDateTime now = Rtc.GetDateTime();
  oled.setCursor(0, 0);
  oled.set1X();
  printDateOnly(now);

  oled.setCursor(0, 2);
  oled.set1X();
  printTimeOnly(now);
}
Like

Discussions