Arduino Code first commit : existing files

This commit is contained in:
ThomasFransolet 2019-04-14 23:11:37 +02:00
parent 3a5f526b49
commit 144c74d7cc
916 changed files with 247792 additions and 0 deletions

View File

@ -0,0 +1,279 @@
/***************************************************************************
This is a library for the BME280 humidity, tmperature & pressure sensor
Designed specifically to work with the Adafruit BME280 Breakout
----> http://www.adafruit.com/products/2650
These sensors use I2C or SPI to communicate, 2 or 4 pins are required
to interface. The device's I2C address is either 0x76 or 0x77.
Adafruit invests time and resources providing this open source code,
please support Adafruit andopen-source hardware by purchasing products
from Adafruit!
Written by Limor Fried & Kevin Townsend for Adafruit Industries.
BSD license, all text above must be included in any redistribution
***************************************************************************/
#include <IRremoteESP8266.h>
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11
#define BMP_CS 10
#define SEALEVELPRESSURE_HPA (1013.25)
IRsend irsend(16); //an IR led is connected to digital pin 0
Adafruit_BMP280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
const int gasPin = A0; //GAS sensor output pin to Arduino analog A0 pin
const char* ssid = "VOO-375468";
const char* password = "UYQQMTHF";
const char* topic = "3DPrinterSensors";
const int mqtt_port = 1883;
const char* mqtt_server = "192.168.0.7";
const char* topicLed = "3DPrinterLed";
const char* mqtt_client = "ESP8266Client-3DPrinter-Sensors";
WiFiClient espClient;
PubSubClient client(espClient);
int redPin = 14;
int greenPin = 12;
int bluePin = 13;
unsigned long startMillis; //some global variables available anywhere in the program
unsigned long currentMillis;
const unsigned long period = 30000; //the value is a number of milliseconds => number of ms within every message
char message_buff[100];
void setup() {
irsend.begin();
Serial.begin(9600);
Serial.println(F("BME280 test"));
WiFi.softAPdisconnect(true);
WiFi.begin(ssid, password);
bool status;
// default settings
// (you can also pass in a Wire library object like &Wire2)
status = bme.begin();
if (!status) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
//Serial.println("-- Default Test --");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
setColor(LOW, HIGH, LOW); // green
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
startMillis = millis(); //initial start time
Serial.println();
}
void loop() {
if(WiFi.status() != WL_CONNECTED){
setColor(HIGH, LOW, LOW); // red
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
setColor(LOW, HIGH, LOW); // green
}
if (!client.connected()) {
setColor(LOW, LOW, HIGH); // not connected to mqtt broker
reconnect();
}
else
{
currentMillis = millis(); //get the current "time" (actually the number of milliseconds since the program started)
if (currentMillis - startMillis >= period) //test whether the period has elapsed
{
String pubStringPost = String("{\"Temperature\":\""+String((double)bme.readTemperature())+"\",\"Pressure\":\""+String((int)bme.readPressure())+"\",\"Smoke\":\""+String((int)analogRead(gasPin))+"\"}");
pubStringPost.toCharArray(message_buff, pubStringPost.length()+1);
client.publish(topic,message_buff);
printValues();
startMillis = currentMillis; //IMPORTANT to save the start time of the current LED state.
}
}
client.loop();
}
void printValues() {
Serial.print("Temperature = ");
Serial.print(bme.readTemperature());
Serial.println(" *C");
Serial.print("Pressure = ");
Serial.print(bme.readPressure());
Serial.println(" Pa");
Serial.print("Approx. Altitude = ");
Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
Serial.println(" m");
/*Serial.print("Humidity = ");
Serial.print(bme.readHumidity());
Serial.println(" %");*/
Serial.print("MQ-2 = ");
Serial.print(analogRead(gasPin));
Serial.println(" value");
Serial.println();
}
void setColor(bool red, bool green, bool blue)
{
#ifdef COMMON_ANODE
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
#endif
digitalWrite(redPin, red);
digitalWrite(greenPin, green);
digitalWrite(bluePin, blue);
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
String payloadString;
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
payloadString += (char)payload[i];
}
/*payloadString.toCharArray(message_buff, payloadString.length()+1);
client.publish("TestReceived",message_buff); */
if(payloadString.length() == 8) {
if(payloadString.substring(0,4).equals("0xff"))
{
if (payloadString.equals("0xfff807")) {
sendToIr(0xfff807); //close
} else {
sendToIr(0xffb04f); // open
unsigned long steps2move = strtol(payloadString.c_str(),NULL,0);
//Serial.println(0xffb04f);
//Serial.println(steps2move);
sendToIr(steps2move);
}
}
}
/*switch ((char)payload[0]) {
case '0':
sendToIr(0xfff807); //close
break;
case '1':
sendToIr(0xffb04f); // open
sendToIr(0xffa857); // white
break;
case '2':
sendToIr(0xffb04f); // open
sendToIr(0xff9867); // red
break;
case '3':
sendToIr(0xffb04f); // open
sendToIr(0xffd827); // green
break;
case '4':
sendToIr(0xffb04f); // open
sendToIr(0xff8877); // blue
break;
case '5':
sendToIr(0xffb04f); // open
sendToIr(0xff38c7); // yellow
break;
case '6':
sendToIr(0xffb04f); // open
sendToIr(0xffe817); // red 1
break;
case '7':
sendToIr(0xffb04f); // open
sendToIr(0xff20df); // blue 2
break;
default:
//setColor(LOW, LOW); //close
Serial.println("NOT assigned");
break;
}*/
}
void sendToIr(unsigned long data) {
for (int i = 0; i < 3; i++) {
irsend.sendNEC(data, 32);
delay(40);
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(mqtt_client)) {
Serial.println("connected");
setColor(LOW, HIGH, LOW); // green
client.subscribe(topicLed);
String ipString = "{\"Name\":\"3DPrinterSensor\",\"IpAddress\":\""+ WiFi.localIP().toString()+"\"}";
ipString.toCharArray(message_buff, ipString.length()+1);
client.publish("IpAddress",message_buff);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}

View File

@ -0,0 +1,235 @@
/***************************************************************************
This is a library for the BME280 humidity, tmperature & pressure sensor
Designed specifically to work with the Adafruit BME280 Breakout
----> http://www.adafruit.com/products/2650
These sensors use I2C or SPI to communicate, 2 or 4 pins are required
to interface. The device's I2C address is either 0x76 or 0x77.
Adafruit invests time and resources providing this open source code,
please support Adafruit andopen-source hardware by purchasing products
from Adafruit!
Written by Limor Fried & Kevin Townsend for Adafruit Industries.
BSD license, all text above must be included in any redistribution
***************************************************************************/
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#define BME_SCK 13
#define BME_MISO 12
#define BME_MOSI 11
#define BME_CS 10
#define SEALEVELPRESSURE_HPA (1013.25)
Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
const int gasPin = A0; //GAS sensor output pin to Arduino analog A0 pin
const char* ssid = "VOO-375468";
const char* password = "UYQQMTHF";
const char* topic = "3DPrinterSensors";
const char* mqtt_server = "192.168.0.24";
const int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
int redPin = 14;
int greenPin = 12;
int bluePin = 13;
unsigned long startMillis; //some global variables available anywhere in the program
unsigned long currentMillis;
const unsigned long period = 5000; //the value is a number of milliseconds
char message_buff[100];
void setup() {
Serial.begin(9600);
Serial.println(F("BME280 test"));
WiFi.softAPdisconnect(true);
WiFi.begin(ssid, password);
bool status;
// default settings
// (you can also pass in a Wire library object like &Wire2)
status = bme.begin();
if (!status) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
Serial.println("-- Default Test --");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
setColor(LOW, HIGH, LOW); // green
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
startMillis = millis(); //initial start time
Serial.println();
}
void loop() {
if(WiFi.status() != WL_CONNECTED){
setColor(HIGH, LOW, LOW); // red
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
setColor(LOW, HIGH, LOW); // green
}
if (!client.connected()) {
setColor(HIGH, HIGH, LOW);
reconnect();
}
else
{
currentMillis = millis(); //get the current "time" (actually the number of milliseconds since the program started)
if (currentMillis - startMillis >= period) //test whether the period has elapsed
{
String pubStringPost = String("Temp="+String((double)bme.readTemperature())+",Hum="+String((int)bme.readHumidity())+",Gas="+String((int)analogRead(gasPin)));
pubStringPost.toCharArray(message_buff, pubStringPost.length()+1);
client.publish(topic,message_buff);
printValues();
startMillis = currentMillis; //IMPORTANT to save the start time of the current LED state.
}
}
client.loop();
}
void printValues() {
Serial.print("Temperature = ");
Serial.print(bme.readTemperature());
Serial.println(" *C");
Serial.print("Pressure = ");
Serial.print(bme.readPressure() / 100.0F);
Serial.println(" hPa");
Serial.print("Approx. Altitude = ");
Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
Serial.println(" m");
Serial.print("Humidity = ");
Serial.print(bme.readHumidity());
Serial.println(" %");
Serial.print("MQ-2 = ");
Serial.print(analogRead(gasPin));
Serial.println(" value");
Serial.println();
}
void setColor(bool red, bool green, bool blue)
{
#ifdef COMMON_ANODE
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
#endif
digitalWrite(redPin, red);
digitalWrite(greenPin, green);
digitalWrite(bluePin, blue);
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
Serial.println("Hello there");
switch ((char)payload[0]) {
case '0':
setColor(LOW, LOW, LOW); //close
break;
case '1':
setColor(HIGH, LOW, LOW); //red
break;
case '2':
setColor(LOW, HIGH, LOW); //green
break;
case '3':
setColor(LOW, LOW, HIGH); //blue
break;
case '4':
setColor(HIGH, HIGH, LOW); //yellow
break;
case '5':
setColor(LOW, HIGH, HIGH); //
break;
case '6':
setColor(HIGH, LOW, HIGH); //
break;
case '7':
setColor(HIGH, HIGH, HIGH); //white
break;
default:
setColor(LOW, LOW, LOW); //close
Serial.println("NOT assigned");
break;
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client-3DPrinter-Sensors")) {
Serial.println("connected");
client.subscribe("3DPrinterLed");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}

View File

@ -0,0 +1,236 @@
/***************************************************************************
This is a library for the BME280 humidity, tmperature & pressure sensor
Designed specifically to work with the Adafruit BME280 Breakout
----> http://www.adafruit.com/products/2650
These sensors use I2C or SPI to communicate, 2 or 4 pins are required
to interface. The device's I2C address is either 0x76 or 0x77.
Adafruit invests time and resources providing this open source code,
please support Adafruit andopen-source hardware by purchasing products
from Adafruit!
Written by Limor Fried & Kevin Townsend for Adafruit Industries.
BSD license, all text above must be included in any redistribution
***************************************************************************/
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11
#define BMP_CS 10
#define SEALEVELPRESSURE_HPA (1013.25)
Adafruit_BMP280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
const int gasPin = A0; //GAS sensor output pin to Arduino analog A0 pin
const char* ssid = "VOO-375468";
const char* password = "UYQQMTHF";
const char* topic = "3DPrinterSensors";
const int mqtt_port = 1883;
const char* mqtt_server = "192.168.0.24";
const char* topicLed = "3DPrinterLed";
const char* mqtt_client = "ESP8266Client-3DPrinter-Sensors";
WiFiClient espClient;
PubSubClient client(espClient);
int redPin = 14;
int greenPin = 12;
int bluePin = 13;
unsigned long startMillis; //some global variables available anywhere in the program
unsigned long currentMillis;
const unsigned long period = 5000; //the value is a number of milliseconds
char message_buff[100];
void setup() {
Serial.begin(9600);
Serial.println(F("BME280 test"));
WiFi.softAPdisconnect(true);
WiFi.begin(ssid, password);
bool status;
// default settings
// (you can also pass in a Wire library object like &Wire2)
status = bme.begin();
if (!status) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
Serial.println("-- Default Test --");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
setColor(LOW, HIGH, LOW); // green
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
startMillis = millis(); //initial start time
Serial.println();
}
void loop() {
if(WiFi.status() != WL_CONNECTED){
setColor(HIGH, LOW, LOW); // red
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
setColor(LOW, HIGH, LOW); // green
}
if (!client.connected()) {
setColor(HIGH, HIGH, LOW);
reconnect();
}
else
{
currentMillis = millis(); //get the current "time" (actually the number of milliseconds since the program started)
if (currentMillis - startMillis >= period) //test whether the period has elapsed
{
String pubStringPost = String("Temp="+String((double)bme.readTemperature())+",Press="+String((int)bme.readPressure())+",Gas="+String((int)analogRead(gasPin)));
pubStringPost.toCharArray(message_buff, pubStringPost.length()+1);
client.publish(topic,message_buff);
printValues();
startMillis = currentMillis; //IMPORTANT to save the start time of the current LED state.
}
}
client.loop();
}
void printValues() {
Serial.print("Temperature = ");
Serial.print(bme.readTemperature());
Serial.println(" *C");
Serial.print("Pressure = ");
Serial.print(bme.readPressure());
Serial.println(" Pa");
Serial.print("Approx. Altitude = ");
Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
Serial.println(" m");
/*Serial.print("Humidity = ");
Serial.print(bme.readHumidity());
Serial.println(" %");*/
Serial.print("MQ-2 = ");
Serial.print(analogRead(gasPin));
Serial.println(" value");
Serial.println();
}
void setColor(bool red, bool green, bool blue)
{
#ifdef COMMON_ANODE
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
#endif
digitalWrite(redPin, red);
digitalWrite(greenPin, green);
digitalWrite(bluePin, blue);
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
Serial.println("Hello there");
switch ((char)payload[0]) {
case '0':
setColor(LOW, LOW, LOW); //close
break;
case '1':
setColor(HIGH, LOW, LOW); //red
break;
case '2':
setColor(LOW, HIGH, LOW); //green
break;
case '3':
setColor(LOW, LOW, HIGH); //blue
break;
case '4':
setColor(HIGH, HIGH, LOW); //yellow
break;
case '5':
setColor(LOW, HIGH, HIGH); //
break;
case '6':
setColor(HIGH, LOW, HIGH); //
break;
case '7':
setColor(HIGH, HIGH, HIGH); //white
break;
default:
setColor(LOW, LOW, LOW); //close
Serial.println("NOT assigned");
break;
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(mqtt_client)) {
Serial.println("connected");
client.subscribe(topicLed);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@ -0,0 +1,63 @@
int motion = 2;
int motionLed = 4;
const int relayPin = D1;
int LightSensor = A0;
int sensorValue = 0;
long TimeRequestMillis;
long waitTime = 20000;
bool activate = false;
void setup() {
Serial.begin(115200);
pinMode(motion, INPUT);
pinMode(motionLed, OUTPUT);
pinMode(relayPin, OUTPUT);
TimeRequestMillis = millis();
delay(2000);
}
void loop()
{
sensorValue = analogRead(A0); // read the value from the sensor
unsigned long currentMillis = millis();
long sensor = digitalRead(motion);
Serial.println(currentMillis - TimeRequestMillis);
Serial.println(sensorValue);
if(sensor == HIGH && sensorValue<500){
Serial.println("J'ouvre !");
digitalWrite (motionLed, HIGH);
digitalWrite(D1, HIGH);
TimeRequestMillis = currentMillis;
activate = true;
delay(9000);
}
if(activate && sensor == HIGH) {
TimeRequestMillis = currentMillis;
Serial.println("mouvement, je laisse ouvert");
delay(2000);
}
if(activate && (currentMillis - TimeRequestMillis > waitTime)){
Serial.println("Je ferme");
digitalWrite (motionLed, LOW);
digitalWrite(D1, LOW);
activate = false;
}
delay(200);
}

View File

@ -0,0 +1,65 @@
int motion = 7;
int motionLed = 3;
int Relay = 9;
int LightSensor = A0;
int sensorValue = 0;
long TimeRequestMillis;
long waitTime = 40000;
bool activate = false;
void setup() {
Serial.begin(115200);
pinMode(motion, INPUT);
pinMode(motionLed, OUTPUT);
pinMode(Relay, OUTPUT);
TimeRequestMillis = millis();
digitalWrite(Relay, LOW);
delay(2000);
}
void loop()
{
sensorValue = analogRead(LightSensor); // read the value from the sensor
unsigned long currentMillis = millis();
long sensor = digitalRead(motion);
Serial.println(currentMillis - TimeRequestMillis);
Serial.println(sensorValue);
if(sensor == HIGH && sensorValue<500){
Serial.println("J'ouvre !");
digitalWrite (motionLed, HIGH);
digitalWrite(Relay, HIGH);
TimeRequestMillis = currentMillis;
activate = true;
delay(10000);
}
if(activate && sensor == HIGH) {
TimeRequestMillis = currentMillis;
Serial.println("mouvement, je laisse ouvert");
delay(10000);
}
if(activate && (currentMillis - TimeRequestMillis > waitTime)){
Serial.println("Je ferme");
digitalWrite (motionLed, LOW);
digitalWrite(Relay, LOW);
activate = false;
}
delay(800);
}

View File

@ -0,0 +1,150 @@
#include <IRremoteESP8266.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
IRsend irsend(4); //an IR led is connected to GPIO pin 0
/*const char* ssid = "bigChief2";
const char* password = "987654321";*/
const char* ssid = "VOO-375468";
const char* password = "UYQQMTHF";
const char* mqtt_server = "192.168.0.15";
const int led = 5;
WiFiClient espClient;
PubSubClient client(espClient);
void setup()
{
irsend.begin();
pinMode(led, OUTPUT);
Serial.begin(115200);
WiFi.softAPdisconnect(true);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(led, HIGH);
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
String temp = "";
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
temp = temp + (char)payload[i];
}
Serial.println();
//char temp = (char)payload[0];
//String temp = String((char*)payload);
Serial.println(temp);
if (temp.equals("ON")) {
Serial.println("Envoie code IR vers TV Sony");
for (int i = 0; i < 3; i++) {
irsend.sendSony(0xa90, 12);
delay(40);
}
Serial.println("POWER");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0x80BF3BC4, 32);
delay(40);
}
Serial.println("TV");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0x80BF5BA4, 32);
delay(40);
}
Serial.println("EXIT");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0x80BF41BE, 32);
delay(40);
}
Serial.println("OK");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0x80BF738C, 32);
delay(40);
}
Serial.println("Guide");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0x80BFA35C, 32);
delay(40);
}
Serial.println("RED");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0x80BF916E, 32);
delay(40);
}
}
/*if (temp.equals("ON")) {
Serial.println("Envoie code IR vers TV Sony");
for (int i = 0; i < 3; i++) {
irsend.sendSony(0xa90, 12);
delay(40);
}
}*/
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client-IR", "oilkfgjy", "lEyZb90q49Rf")) {
Serial.println("connected");
client.subscribe("TV");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop(void) {
if(WiFi.status() != WL_CONNECTED){
digitalWrite(led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
digitalWrite(led, HIGH);
}
if (!client.connected()) {
digitalWrite(led, LOW);
reconnect();
}else{
digitalWrite(led, HIGH);
}
client.loop();
}

128
Arduino Code/LM35/LM35.ino Normal file
View File

@ -0,0 +1,128 @@
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
#define NUMFLAKES 10
#define XPOS 0
#define YPOS 1
#define DELTAY 2
#define LOGO16_GLCD_HEIGHT 16
#define LOGO16_GLCD_WIDTH 16
static const unsigned char PROGMEM logo16_glcd_bmp[] =
{ B00000000, B11000000,
B00000001, B11000000,
B00000001, B11000000,
B00000011, B11100000,
B11110011, B11100000,
B11111110, B11111000,
B01111110, B11111111,
B00110011, B10011111,
B00011111, B11111100,
B00001101, B01110000,
B00011011, B10100000,
B00111111, B11100000,
B00111111, B11110000,
B01111100, B11110000,
B01110000, B01110000,
B00000000, B00110000 };
#if (SSD1306_LCDHEIGHT != 32)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif
const int Led = 9;
const int Relay = 4;
const int diffDegree = 3;
long waitTime = 60000;
long TimeRequestMillis;
char* relaystate = "Close";
bool lock = false;
void setup() {
Serial.begin(115200);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3C (for the 128x32)
display.display();
delay(2000);
// Clear the buffer.
display.clearDisplay();
pinMode(Relay, OUTPUT);
digitalWrite(Relay, LOW);
TimeRequestMillis = millis();
}
void loop() {
unsigned long currentMillis = millis();
int valeur_brute = analogRead(A0);
float temperature_Panneaux = valeur_brute * (5.0 / 1023.0 * 100.0);
//Serial.println("LM35 : "+temperature_celcius); *0.63652437
//Serial.print("Temperature LM35: ");
//Serial.println(temperature_Panneaux);
int valeur_brute2 = analogRead(A1);
float temperature_Boiler = valeur_brute2 * (5.0 / 1023.0 * 100.0);
//Serial.print("Temperature2 LM35: ");
//Serial.println(temperature_Boiler);
if(lock == false){
if((temperature_Panneaux > temperature_Boiler + diffDegree) && (lock == false)){ //mettre plus diff de degré
digitalWrite(Relay, HIGH);
relaystate = "Open";
}
else{
digitalWrite(Relay, LOW);
relaystate = "Close";
}
Serial.println("Lock");
lock = true;
}
if(currentMillis - TimeRequestMillis > waitTime){
TimeRequestMillis = currentMillis;
Serial.println("Unlocked !");
lock = false;
}
// text display tests
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.print("Panneaux: ");
display.print(temperature_Panneaux);
display.println("C");
display.print("Boiler: ");
display.print(temperature_Boiler);
display.println("C");
display.print("Statut relay : ");
display.println(relaystate);
display.display();
delay(2000); //mettre plus ! ;)
display.clearDisplay();
}

View File

@ -0,0 +1,152 @@
#include <IRremoteESP8266.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
IRsend irsend(4); //an IR led is connected to GPIO pin 0
const char* ssid = "bigChief2";
const char* password = "987654321";
ESP8266WebServer server(80);
const int led = 5;
void handleRoot() {
server.send(200, "text/plain", "Wemos IR Remote");
}
void handleNotFound(){
digitalWrite(led, 1);
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
digitalWrite(led, 0);
}
void setup()
{
irsend.begin();
pinMode(led, OUTPUT);
Serial.begin(115200);
WiFi.softAPdisconnect(true);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(led, HIGH);
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/cloud", [](){
server.send(200, "text/plain", "cloud");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xff20df, 32);
delay(40);
}
});
server.on("/snow", [](){
server.send(200, "text/plain", "snow");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffa857, 32);
delay(40);
}
});
server.on("/rain", [](){
server.send(200, "text/plain", "rain");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xff8877, 32);
delay(40);
}
});
server.on("/sun", [](){
server.send(200, "text/plain", "sun");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xff38c7, 32);
delay(40);
}
});
server.on("/thunder", [](){
server.send(200, "text/plain", "thunder");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffe817, 32);
delay(40);
}
});
server.on("/close", [](){
server.send(200, "text/plain", "close led");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xfff807, 32);
delay(40);
}
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
if(WiFi.status() != WL_CONNECTED){
digitalWrite(led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
digitalWrite(led, HIGH);
}
}

View File

@ -0,0 +1,166 @@
#include <IRremoteESP8266.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
IRsend irsend(4); //an IR led is connected to GPIO pin 0
/*const char* ssid = "bigChief2";
const char* password = "987654321";*/
const char* ssid = "ESP8266 - TEST";
const char* password = "Coconuts09";
const char* mqtt_server = "m21.cloudmqtt.com";
const int led = 5;
WiFiClient espClient;
PubSubClient client(espClient);
void setup()
{
irsend.begin();
pinMode(led, OUTPUT);
Serial.begin(115200);
WiFi.softAPdisconnect(true);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(led, HIGH);
client.setServer(mqtt_server, 18932);
client.setCallback(callback);
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
if ((char)payload[0] == '0') {
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xfff807, 32);
delay(40);
}
}
if ((char)payload[0] == '1') {
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xff8877, 32);
delay(40);
}
}
if ((char)payload[0] == '2') {
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xff38c7, 32);
delay(40);
}
}
if ((char)payload[0] == '3') {
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffa857, 32);
delay(40);
}
}
if ((char)payload[0] == '4') {
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffe817, 32);
delay(40);
}
}
if ((char)payload[0] == '5') {
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xff20df, 32);
delay(40);
}
}
if ((char)payload[0] == '6') {
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xff8877, 32);
delay(40);
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client-LedWeatherSensor", "oilkfgjy", "lEyZb90q49Rf")) {
Serial.println("connected");
client.subscribe("temp");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop(void) {
if(WiFi.status() != WL_CONNECTED){
digitalWrite(led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
digitalWrite(led, HIGH);
}
if (!client.connected()) {
digitalWrite(led, LOW);
reconnect();
}else{
digitalWrite(led, HIGH);
}
client.loop();
}

View File

@ -0,0 +1,105 @@
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const int movePin = 4; // the number of the pushbutton pin
const int Led = 14;
long TimeRequestMillis;
long waitTime = 30000;
bool activate = false;
/*const char* ssid = "bigChief2";
const char* password = "987654321";*/
const char* ssid = "ESP8266 - TEST";
const char* password = "Coconuts09";
const char* mqtt_server = "m21.cloudmqtt.com";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup() {
Serial.begin(115200);
Serial.println("MoveSensor MyMirror test!");
WiFi.softAPdisconnect(true);
pinMode(Led, OUTPUT);
pinMode(movePin, INPUT);
setup_wifi();
client.setServer(mqtt_server, 18932);
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
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());
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client-MoveSensor", "oilkfgjy", "lEyZb90q49Rf")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
digitalWrite(Led, LOW);
reconnect();
}else{
digitalWrite(Led, HIGH);
}
client.loop();
unsigned long currentMillis = millis();
long sensor = digitalRead(movePin);
Serial.println(currentMillis - TimeRequestMillis);
if(sensor == HIGH){
Serial.println("J'ouvre !");
TimeRequestMillis = currentMillis;
activate = true;
client.publish("Close", "No");
delay(5000);
}
if(activate && (currentMillis - TimeRequestMillis > waitTime)){
Serial.println("Je ferme");
client.publish("Close", "Yes");
activate = false;
}
delay(1000);
}

View File

@ -0,0 +1,19 @@
#include <HX711.h>
// Scale Settings
const int SCALE_DOUT_PIN = D2;
const int SCALE_SCK_PIN = D3;
HX711 scale(SCALE_DOUT_PIN, SCALE_SCK_PIN);
void setup() {
Serial.begin(115200);
scale.set_scale();// <- set here calibration factor!!!
scale.tare();
}
void loop() {
float weight = scale.get_units(1);
Serial.println(String(weight, 2));
delay(1000);
}

View File

@ -0,0 +1,119 @@
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
#define DHTPIN 2 // what digital pin we're connected to
#define DHTTYPE DHT11 // DHT 22 (AM2302), AM2321
/*const char* ssid = "ESP8266";
const char* password = "password";*/
/*const char* ssid = "bigChief2";
const char* password = "987654321";*/
const char* ssid = "VOO-375468";
const char* password = "UYQQMTHF";
const char* mqtt_server = "m21.cloudmqtt.com";
char message_buff[100];
WiFiClient espClient;
PubSubClient client(espClient);
const int Led = 14;
// 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.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
Serial.println("DHT22 test!");
WiFi.softAPdisconnect(true);
dht.begin();
pinMode(Led, OUTPUT);
WiFi.begin(ssid, password);
Serial.println("");
digitalWrite(Led, LOW);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(Led, HIGH);
client.setServer(mqtt_server, 18932);
/*server.on("/temp", []() {
String page = "{ \"temperature\":" + String((int)dht.readTemperature()) + ", \"humidity\":" + String((int)dht.readHumidity())+"}";
server.send(200, "text/plain", page);
});*/
//client = PubSubClient(mqtt_server, 18932, callback);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client-TempSensor", "oilkfgjy", "lEyZb90q49Rf")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop() {
if(WiFi.status() != WL_CONNECTED){
digitalWrite(Led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
}else{
if(digitalRead(Led)==LOW){
digitalWrite(Led, HIGH);
}
}
if (!client.connected()) {
digitalWrite(Led, LOW);
reconnect();
}else{
digitalWrite(Led, HIGH);
}
client.loop();
String pubString = String((int)dht.readTemperature());
String pubStringPost = String("Degree="+pubString);
pubStringPost.toCharArray(message_buff, pubStringPost.length()+1);
client.publish("DegreeHome",message_buff);
delay(5000);
}

View File

@ -0,0 +1,81 @@
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "VOO-375468";
const char* password = "UYQQMTHF";
const char* mqtt_server = "192.168.0.13";
String pubString ;
char message_buff[100];
WiFiClient espClient;
PubSubClient client(espClient);
const int Led = 14;
int i;
int val;
int redpin=0;
void setup() {
pinMode(Led, OUTPUT);
pinMode(redpin,OUTPUT);
digitalWrite(Led, LOW);
Serial.begin(9600);
WiFi.softAPdisconnect(true);
WiFi.begin(ssid, password);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
client.setServer(mqtt_server, 1883);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client-TempSensor")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}else{
digitalWrite(Led, HIGH);
i=analogRead(redpin);
val=(6762/(i-9))-4;
if(5<val && val<50){
pubString = String((int)val);
// pubString = "Sound : " + pubString;
pubString.toCharArray(message_buff, pubString.length()+1);
Serial.println(val);
client.publish("Sound",message_buff); }
delay(130);
}
client.loop();
}

View File

@ -0,0 +1,25 @@
#include <RH_ASK.h>
#include <SPI.h> // Not actualy used but needed to compile
//Avant dernier, près du gnd -> pin 11
RH_ASK driver;
void setup()
{
Serial.begin(9600); // Debugging only
if (!driver.init())
Serial.println("init failed");
}
void loop()
{
uint8_t buf[12];
uint8_t buflen = sizeof(buf);
if (driver.recv(buf, &buflen)) // Non-blocking
{
int i;
// Message with a good checksum received, dump it.
Serial.print("Message: ");
Serial.println((char*)buf);
}
}

View File

@ -0,0 +1,28 @@
#include <RH_ASK.h>
#include <SPI.h> // Not actually used but needed to compile
//ATAD pin -> 12
RH_ASK driver;
int i = 0;
void setup()
{
Serial.begin(9600); // Debugging only
int i = 0;
if (!driver.init())
Serial.println("init failed");
}
void loop()
{
char chaine_nombre[5];
itoa(i, chaine_nombre, 10);
//const char *msg = "Coucou Thomas !";
driver.send((uint8_t *)chaine_nombre, strlen(chaine_nombre));
driver.waitPacketSent();
delay(1000);
i = i+1;
}

View File

@ -0,0 +1,93 @@
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
const char *ssid = "ESP8266";
const char *password = "password";
const int Red = 14;
const int Green = 12;
const int Blue = 13;
ESP8266WebServer server(80);
void handleRoot() {
server.send(200, "text/html", "<h1>You are connected</h1>");
}
void setup() {
pinMode(Red, OUTPUT);
pinMode(Green, OUTPUT);
pinMode(Blue, OUTPUT);
delay(1000);
Serial.begin(115200);
Serial.println();
Serial.print("Configuring access point...");
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.on("/", handleRoot);
server.on("/inline", [](){
server.send(200, "text/plain", "this works as well");
});
server.on("/openRed", [](){
server.send(200, "text/plain", "open red led");
digitalWrite(Red, HIGH);
});
server.on("/closeRed", [](){
server.send(200, "text/plain", "close red led");
digitalWrite(Red, LOW);
});
server.on("/openGreen", [](){
server.send(200, "text/plain", "open green led");
digitalWrite(Green, HIGH);
});
server.on("/closeGreen", [](){
server.send(200, "text/plain", "close green led");
digitalWrite(Green, LOW);
});
server.on("/openBlue", [](){
server.send(200, "text/plain", "open blue led");
digitalWrite(Blue, HIGH);
});
server.on("/closeBlue", [](){
server.send(200, "text/plain", "close blue led");
digitalWrite(Blue, LOW);
});
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
}

View File

@ -0,0 +1,138 @@
#define IP_FORWARD 1
#include <ESP8266WiFi.h>
#include <WiFiUDP.h>
/* Set these to your desired credentials for ESP8266 AP. */
const char *ssid = "ESP8266 - RepeteurWifi";
const char *password = "azerty123";
IPAddress apIP(192, 168, 4, 1);
const int led = 5;
//const char* ssidExt = "dlink";
//const char* passwordExt = "";
// Setup credentials for original WiFi, that we plan to repeat
const char* ssidExt = "WiFi-2.4-C913";
const char* passwordExt = "BC94570E97";
const byte DNS_PORT = 53;
// A UDP instance to let us send and receive packets over UDP
WiFiUDP Udp;
byte packetBuffer[512]; //buffer to hold incoming and outgoing packets
WiFiUDP Udp8;
// Update these with values suitable for your network.
IPAddress ip(192, 168, 0, 13); //Node static IP
IPAddress gateway(192, 168, 0, 1);
IPAddress subnet(255, 255, 255, 0);
void setup()
{
Serial.begin(115200);
Serial.println();
WiFi.mode(WIFI_AP_STA);
//WiFi.mode(WIFI_AP);
Serial.println("!!!!!!!!!!!!!!!!!!!++");
WiFi.begin(ssidExt, passwordExt);
WiFi.config(ip, gateway, subnet);
//Wifi connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
digitalWrite(led, HIGH);
Serial.println(ssidExt);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("dnsIP address: ");
Serial.println(WiFi.dnsIP());
Serial.print("gatewayIP address: ");
Serial.println(WiFi.gatewayIP());
Serial.print("subnetMask address: ");
Serial.println(WiFi.subnetMask());
Serial.println("");
Serial.println("Configuring access point...");
/* You can remove the password parameter if you want the AP to be open. */
//WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
Udp.begin(DNS_PORT);
Udp8.begin(DNS_PORT);
}
void loop()
{
if(WiFi.status() != WL_CONNECTED){
digitalWrite(led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
digitalWrite(led, HIGH);
}
int noBytes = Udp.parsePacket();
if ( noBytes ) {
// Serial.print(millis() / 1000);
// Serial.print(":Packet of ");
// Serial.print(noBytes);
// Serial.print(" received from ");
// Serial.print(Udp.remoteIP());
// Serial.print(":");
// Serial.println(Udp.remotePort());
// We've received a packet, read the data from it
Udp.read(packetBuffer, noBytes); // read the packet into the buffer
// display the packet contents in HEX
// for (int i = 1; i <= noBytes; i++) {
// Serial.print(packetBuffer[i - 1], HEX);
// if (i % 32 == 0) {
// Serial.println();
// }
// else Serial.print(' ');
// } // end for
// Serial.println();
IPAddress ip8(8, 8, 8, 8);
Udp8.beginPacket(ip8, DNS_PORT); //NTP requests are to port 123
Udp8.write(packetBuffer, noBytes);
Udp8.endPacket();
delay(100);
int cb = Udp8.parsePacket();
if (!cb) {
// Serial.println("no packet yet");
}
else {
// Serial.print("packet received, length=");
// Serial.println(cb);
byte packetBuffer8[cb];
Udp8.read(packetBuffer8, cb);
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(packetBuffer8, cb);
Udp.endPacket();
}
} // end if
}

View File

@ -0,0 +1,10 @@
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
}

View File

@ -0,0 +1,29 @@
/*
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://www.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(1, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(1, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(1, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}

View File

@ -0,0 +1,28 @@
int motion = 9;
int motionLed = 4;
int Relay = 7;
void setup() {
pinMode(motion, INPUT);
pinMode(motionLed, OUTPUT);
pinMode(Relay, OUTPUT);
}
void loop()
{
long sensor = digitalRead(motion);
if(sensor == HIGH){
digitalWrite (motionLed, HIGH);
digitalWrite(Relay, HIGH);
}
else
{
digitalWrite (motionLed, LOW);
digitalWrite(Relay, LOW);
}
}

View File

@ -0,0 +1,135 @@
#include <SPI.h>
#include <Wire.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266HTTPClient.h>;
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 16; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
const int Led = 14;
int buttonState; // variable for reading the pushbutton status
int lastState;
int ledState;
const char* ssid = "ESP8266 - TEST";
const char* password = "Coconuts08";
const char* host = "192.168.101.22";
void setup() {
Serial.begin(115200);
Serial.println("Button test!");
pinMode(Led, OUTPUT);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
WiFi.begin(ssid, password);
Serial.println("");
digitalWrite(Led, LOW);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
String IP = WiFi.localIP()+"";
digitalWrite(Led, HIGH);
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
}
void loop() {
if(WiFi.status() != WL_CONNECTED){
digitalWrite(Led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
}else{
if(digitalRead(Led)==LOW) digitalWrite(Led, HIGH);
}
buttonState = digitalRead(buttonPin);
if(buttonState != lastState){
if (buttonState == HIGH) {
if(ledState == LOW) ledState = HIGH;
Serial.println("C'est appuyé");
//APPEL /OPEN
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
digitalWrite(Led, LOW);
return;
}
HTTPClient http;
http.begin("http://192.168.101.22/open");
int httpCode = http.GET();
if(httpCode == HTTP_CODE_OK){
Serial.print("HTTP response code ");
Serial.println(httpCode);
}
else
{
Serial.println("Error in HTTP request");
}
http.end();
} else {
ledState = LOW;
Serial.println("C'est relaché");
//APPEL /OPEN
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
digitalWrite(Led, LOW);
return;
}
HTTPClient http;
http.begin("http://192.168.101.22/close");
int httpCode = http.GET();
if(httpCode == HTTP_CODE_OK){
Serial.print("HTTP response code ");
Serial.println(httpCode);
}
else
{
Serial.println("Error in HTTP request");
}
http.end();
}
lastState = buttonState;
}
digitalWrite(ledPin, ledState);
}

View File

@ -0,0 +1,122 @@
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const int buttonPin = 16; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
const int Led = 14;
int buttonState; // variable for reading the pushbutton status
int lastState;
int ledState;
const char* ssid = "ESP8266 - TEST";
const char* password = "Coconuts08";
const char* mqtt_server = "138.48.32.159";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
long waitTime = 12000;
long TimeRequestMillis;
bool AlreadyNotified = false;
void setup() {
Serial.begin(115200);
Serial.println("Button test!");
pinMode(Led, OUTPUT);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
setup_wifi();
client.setServer(mqtt_server, 1883);
TimeRequestMillis = millis();
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
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());
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client-RINGBUTTON")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
digitalWrite(Led, LOW);
reconnect();
}else{
digitalWrite(Led, HIGH);
}
client.loop();
buttonState = digitalRead(buttonPin);
unsigned long currentMillis = millis();
if(buttonState != lastState){
TimeRequestMillis = currentMillis;
lastState = buttonState;
AlreadyNotified = false;
if (buttonState == HIGH) {
if(ledState == LOW) ledState = HIGH;
} else {
ledState = LOW;
}
}
if((currentMillis - TimeRequestMillis > waitTime) && (buttonState == lastState) && (AlreadyNotified == false)) {
if (buttonState == HIGH) {
Serial.println("C'est appuyé");
client.publish("inTopic", "1");
}
AlreadyNotified = true;
}
if((buttonState == LOW) && (AlreadyNotified == false)){
Serial.println("C'est relaché");
client.publish("inTopic", "0");
AlreadyNotified = true;
}
digitalWrite(ledPin, ledState);
}

View File

@ -0,0 +1,93 @@
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
const char *ssid = "ESP8266";
const char *password = "password";
const int Red = 14;
const int Green = 12;
const int Blue = 13;
ESP8266WebServer server(80);
void handleRoot() {
server.send(200, "text/html", "<h1>You are connected</h1>");
}
void setup() {
pinMode(Red, OUTPUT);
pinMode(Green, OUTPUT);
pinMode(Blue, OUTPUT);
delay(1000);
Serial.begin(115200);
Serial.println();
Serial.print("Configuring access point...");
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.on("/", handleRoot);
server.on("/inline", [](){
server.send(200, "text/plain", "this works as well");
});
server.on("/openRed", [](){
server.send(200, "text/plain", "open red led");
digitalWrite(Red, HIGH);
});
server.on("/closeRed", [](){
server.send(200, "text/plain", "close red led");
digitalWrite(Red, LOW);
});
server.on("/openGreen", [](){
server.send(200, "text/plain", "open green led");
digitalWrite(Green, HIGH);
});
server.on("/closeGreen", [](){
server.send(200, "text/plain", "close green led");
digitalWrite(Green, LOW);
});
server.on("/openBlue", [](){
server.send(200, "text/plain", "open blue led");
digitalWrite(Blue, HIGH);
});
server.on("/closeBlue", [](){
server.send(200, "text/plain", "close blue led");
digitalWrite(Blue, LOW);
});
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
}

View File

@ -0,0 +1,119 @@
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
const char *ssid = "TestHotSpot";
const char *password = "password2";
ESP8266WebServer server(80);
const char* ssidC = "WiFi-2.4-C913";
const char* passwordC = "BC94570E97";
//const char* host = "wifitest.adafruit.com";
const int led = 5;
void handleRoot() {
server.send(200, "text/html", "<h1>You are connected to RepeteurWifi</h1>");
}
void setup() {
delay(1000);
pinMode(led, OUTPUT);
Serial.begin(115200);
Serial.println();
Serial.print("Configuring access point...");
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.on("/", handleRoot);
server.begin();
Serial.println("HTTP server started");
WiFi.begin(ssidC, passwordC);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
digitalWrite(led, HIGH);
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
int value = 0;
void loop() {
server.handleClient();
if(WiFi.status() != WL_CONNECTED){
digitalWrite(led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
digitalWrite(led, HIGH);
}
/*
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
// We now create a URI for the request
String url = "/testwifi/index.html";
Serial.print("Requesting URL: ");
Serial.println(url);
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
delay(500);
// 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");
*/
}

View File

@ -0,0 +1,143 @@
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include "DHT.h"
#define DHTPIN 2 // what digital pin we're connected to
#define DHTTYPE DHT11 // DHT 22 (AM2302), AM2321
/*const char* ssid = "ESP8266";
const char* password = "password";*/
const char* ssid = "bigChief2";
const char* password = "987654321";
ESP8266WebServer server(80);
const int Led = 14;
// 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.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);
void handleRoot() {
server.send(200, "text/plain", "hello from esp8266 - TEMP!");
}
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void setup() {
Serial.begin(115200);
Serial.println("DHT22 test!");
dht.begin();
pinMode(Led, OUTPUT);
WiFi.begin(ssid, password);
Serial.println("");
digitalWrite(Led, LOW);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(Led, HIGH);
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
/*
// 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 (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(hic);
Serial.print(" *C ");
Serial.print(hif);
Serial.println(" *F");*/
server.on("/", handleRoot);
server.on("/temp", []() {
String page = "{ \"temperature\":" + String((int)dht.readTemperature()) + ", \"humidity\":" + String((int)dht.readHumidity())+"}";
server.send(200, "text/plain", page);
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
if(WiFi.status() != WL_CONNECTED){
digitalWrite(Led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
}else{
if(digitalRead(Led)==LOW){
digitalWrite(Led, HIGH);
}
}
}

View File

@ -0,0 +1,116 @@
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include "DHT.h"
#define DHTPIN 2 // what digital pin we're connected to
#define DHTTYPE DHT11 // DHT 22 (AM2302), AM2321
const char* ssid = "Smart_Kot";
const char* password = "Coconuts08";
ESP8266WebServer server(80);
const int Led = 14;
// 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.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
Serial.println("DHT11 test!");
dht.begin();
pinMode(Led, OUTPUT);
WiFi.begin(ssid, password);
Serial.println("");
digitalWrite(Led, LOW);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(Led, HIGH);
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// 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 (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(hic);
Serial.print(" *C ");
Serial.print(hif);
Serial.println(" *F");
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
digitalWrite(Led, LOW);
return;
}
// We now create a URI for the request
String urlTemp = "/temp";
Serial.print("Requesting URL: ");
/*client.print(String("POST ") + urlTemp + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n" +
"Content-Type: application/x-www-form-urlencoded;\r\n" +
"\r\n" +
"temp="+ t +"&humidity="+ h +"\n");
}

View File

@ -0,0 +1,94 @@
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
const char* ssid = "ESP8266 - TEST";
const char* password = "Coconuts08";
ESP8266WebServer server(80);
const int led = 13;
const int motion = 12;
void handleRoot() {
digitalWrite(led, 1);
server.send(200, "text/plain", "hello from esp8266!");
digitalWrite(led, 0);
}
void handleNotFound(){
digitalWrite(led, 1);
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
digitalWrite(led, 0);
}
void setup(void){
pinMode(led, OUTPUT);
pinMode(motion, INPUT);
digitalWrite(led, 0);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/inline", [](){
server.send(200, "text/plain", "this works as well");
});
server.on("/open", [](){
server.send(200, "text/plain", "open led");
digitalWrite(led, HIGH);
});
server.on("/close", [](){
server.send(200, "text/plain", "close led");
digitalWrite(led, LOW);
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
/*long sensor = digitalRead(motion);
if(sensor == HIGH){
digitalWrite (led, HIGH);
}
else
{
digitalWrite (led, LOW);
}*/
}

View File

@ -0,0 +1,227 @@
/*
* ESP8266 Web server with Web Socket to control an LED.
*
* The web server keeps all clients' LED status up to date and any client may
* turn the LED on or off.
*
* For example, clientA connects and turns the LED on. This changes the word
* "LED" on the web page to the color red. When clientB connects, the word
* "LED" will be red since the server knows the LED is on. When clientB turns
* the LED off, the word LED changes color to black on clientA and clientB web
* pages.
*
* References:
*
* https://github.com/Links2004/arduinoWebSockets
*
*/
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <Hash.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
static const char ssid[] = "ESP8266-Test";
static const char password[] = "pcf00521";
MDNSResponder mdns;
static void writeLED(bool);
ESP8266WiFiMulti WiFiMulti;
ESP8266WebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);
static const char PROGMEM INDEX_HTML[] = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0, maximum-scale = 1.0, user-scalable=0">
<title>ESP8266 WebSocket Demo</title>
<style>
"body { background-color: #808080; font-family: Arial, Helvetica, Sans-Serif; Color: #000000; }"
</style>
<script>
var websock;
function start() {
websock = new WebSocket('ws://' + window.location.hostname + ':81/');
websock.onopen = function(evt) { console.log('websock open'); };
websock.onclose = function(evt) { console.log('websock close'); };
websock.onerror = function(evt) { console.log(evt); };
websock.onmessage = function(evt) {
console.log(evt);
var e = document.getElementById('ledstatus');
if (evt.data === 'ledon') {
e.style.color = 'red';
}
else if (evt.data === 'ledoff') {
e.style.color = 'black';
}
else {
console.log('unknown event');
}
};
}
function buttonclick(e) {
websock.send(e.id);
}
</script>
</head>
<body onload="javascript:start();">
<h1>ESP8266 WebSocket Demo</h1>
<div id="ledstatus"><b>LED</b></div>
<button id="ledon" type="button" onclick="buttonclick(this);">On</button>
<button id="ledoff" type="button" onclick="buttonclick(this);">Off</button>
</body>
</html>
)rawliteral";
// GPIO#0 is for Adafruit ESP8266 HUZZAH board. Your board LED might be on 13.
const int LEDPIN = 0;
// Current LED status
bool LEDStatus;
// Commands sent through Web Socket
const char LEDON[] = "ledon";
const char LEDOFF[] = "ledoff";
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)
{
Serial.printf("webSocketEvent(%d, %d, ...)\r\n", num, type);
switch(type) {
case WStype_DISCONNECTED:
Serial.printf("[%u] Disconnected!\r\n", num);
break;
case WStype_CONNECTED:
{
IPAddress ip = webSocket.remoteIP(num);
Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload);
// Send the current LED status
if (LEDStatus) {
webSocket.sendTXT(num, LEDON, strlen(LEDON));
}
else {
webSocket.sendTXT(num, LEDOFF, strlen(LEDOFF));
}
}
break;
case WStype_TEXT:
Serial.printf("[%u] get Text: %s\r\n", num, payload);
if (strcmp(LEDON, (const char *)payload) == 0) {
writeLED(true);
}
else if (strcmp(LEDOFF, (const char *)payload) == 0) {
writeLED(false);
}
else {
Serial.println("Unknown command");
}
// send data to all connected clients
webSocket.broadcastTXT(payload, length);
break;
case WStype_BIN:
Serial.printf("[%u] get binary length: %u\r\n", num, length);
hexdump(payload, length);
// echo data back to browser
webSocket.sendBIN(num, payload, length);
break;
default:
Serial.printf("Invalid WStype [%d]\r\n", type);
break;
}
}
void handleRoot()
{
server.send(200, "text/html", INDEX_HTML);
}
void handleNotFound()
{
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send_P(404, "text/plain", message);
}
static void writeLED(bool LEDon)
{
LEDStatus = LEDon;
// Note inverted logic for Adafruit HUZZAH board
if (LEDon) {
digitalWrite(LEDPIN, 0);
}
else {
digitalWrite(LEDPIN, 1);
}
}
void setup()
{
pinMode(LEDPIN, OUTPUT);
writeLED(false);
Serial.begin(115200);
//Serial.setDebugOutput(true);
Serial.println();
Serial.println();
Serial.println();
for(uint8_t t = 4; t > 0; t--) {
Serial.printf("[SETUP] BOOT WAIT %d...\r\n", t);
Serial.flush();
delay(1000);
}
WiFiMulti.addAP(ssid, password);
while(WiFiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(100);
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (mdns.begin("espWebSock", WiFi.localIP())) {
Serial.println("MDNS responder started");
mdns.addService("http", "tcp", 80);
mdns.addService("ws", "tcp", 81);
}
else {
Serial.println("MDNS.begin failed");
}
Serial.print("Connect to http://espWebSock.local or http://");
Serial.println(WiFi.localIP());
server.on("/", handleRoot);
server.onNotFound(handleNotFound);
server.begin();
webSocket.begin();
webSocket.onEvent(webSocketEvent);
}
void loop()
{
webSocket.loop();
server.handleClient();
}

View File

@ -0,0 +1,100 @@
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
const char* ssid = "ESP8266";
const char* password = "password";
const char* host = "192.168.4.3";
ESP8266WebServer server(80);
const int Door = 13;
const int Led = 14;
bool ChangementEtat = true;
int avant = 3;
void setup(void){
pinMode(Led, OUTPUT);
Serial.begin(115200);
pinMode(Door, INPUT_PULLUP);
WiFi.begin(ssid, password);
Serial.println("");
digitalWrite(Led, LOW);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(Led, HIGH);
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
}
void loop(void){
if(WiFi.status() != WL_CONNECTED){
digitalWrite(Led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
}else{
if(digitalRead(Led)==LOW){
digitalWrite(Led, HIGH);
}
if((digitalRead(Door) == LOW and avant == 0) or (digitalRead(Door) == HIGH and avant == 1)) {ChangementEtat = false;} else {ChangementEtat = true;}
if(ChangementEtat){
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
digitalWrite(Led, LOW);
return;
}
// We now create a URI for the request
String urlOpen = "/open";
String urlClose = "/close";
Serial.print("Requesting URL: ");
if(digitalRead(Door) == LOW) {
Serial.println("Door closed");
// This will send the request to the server
client.print(String("GET ") + urlClose + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
avant=0;
} else {
Serial.println("Door is open!");
// This will send the request to the server
client.print(String("GET ") + urlOpen + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
avant=1;
}
}
delay(500);
}
}

View File

@ -0,0 +1,22 @@
const int Door = 13;
const int Led = 16;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(Door, INPUT_PULLUP);
pinMode(Led, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
if(digitalRead(Door) == LOW) {
Serial.println("Door closed");
digitalWrite(Led, HIGH);
} else {
Serial.println("Door is open!");
digitalWrite(Led, LOW);}
}

View File

@ -0,0 +1,24 @@
int motion = 13;
int motionLed = 15;
void setup() {
pinMode(motion, INPUT);
pinMode(motionLed, OUTPUT);
}
void loop()
{
long sensor = digitalRead(motion);
if(sensor == HIGH){
digitalWrite (motionLed, HIGH);
}
else
{
digitalWrite (motionLed, LOW);
}
}

View File

@ -0,0 +1,160 @@
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ArduinoJson.h>
Adafruit_SSD1306 display = Adafruit_SSD1306();
#define BUTTON_A 0
#define BUTTON_B 16
#define BUTTON_C 2
#define LED 0
const char* ssid = "ESP8266 - TEST";
const char* password = "Coconuts08";
/*const char* ssid = "ESP8266";
const char* password = "password";*/
const char* host = "192.168.101.18";
ESP8266WebServer server(80);
const int Led = 14;
#if (SSD1306_LCDHEIGHT != 32)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif
void setup() {
pinMode(Led, OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
digitalWrite(Led, LOW);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
String IP = WiFi.localIP()+"";
digitalWrite(Led, HIGH);
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
// by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3C (for the 128x32)
// init done
// Show image buffer on the display hardware.
// Since the buffer is intialized with an Adafruit splashscreen
// internally, this will display the splashscreen.
display.display();
delay(1000);
// Clear the buffer.
display.clearDisplay();
display.display();
Serial.println("IO test");
pinMode(BUTTON_A, INPUT_PULLUP);
pinMode(BUTTON_B, INPUT_PULLUP);
pinMode(BUTTON_C, INPUT_PULLUP);
// text display tests
display.setTextSize(1);
display.setTextColor(WHITE);
}
void loop() {
/* if (! digitalRead(BUTTON_A)) display.print("A");
if (! digitalRead(BUTTON_B)) display.print("B");
if (! digitalRead(BUTTON_C)) display.print("C");
delay(10);
yield();
display.display();*/
if(WiFi.status() != WL_CONNECTED){
digitalWrite(Led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
}else{
if(digitalRead(Led)==LOW){
digitalWrite(Led, HIGH);
}
if(!digitalRead(BUTTON_A)){
display.clearDisplay();
display.setCursor(0,0);
display.println("Connect to hum sensor");
display.println("");
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
digitalWrite(Led, LOW);
return;
}
String urlTemp = "/temp";
Serial.print("Requesting URL: ");
client.print(String("GET ") + urlTemp + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
String json = "";
boolean httpBody = false;
// while (client.available()) {
String line = client.readStringUntil('\r');
Serial.println(line);
if (!httpBody && line.charAt(1) == '{') {
httpBody = true;
}
if (httpBody) {
json += line;
}
//}
StaticJsonBuffer<200> jsonBuffer;
Serial.println("Got data:");
Serial.println(json);
JsonObject& root = jsonBuffer.parseObject(json);
String temp = root["temperature"];
String hum = root["humidity"];
Serial.println("Temperature :"+temp);
Serial.println("Humidity :"+hum);
display.println("Temp: "+temp+"C - Hum: "+hum+"%");
display.display();
}
}
}

View File

@ -0,0 +1,63 @@
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display = Adafruit_SSD1306();
#define BUTTON_A 0
#define BUTTON_B 16
#define BUTTON_C 2
#define LED 0
#if (SSD1306_LCDHEIGHT != 32)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif
void setup() {
Serial.begin(115200);
Serial.println("OLED FeatherWing test");
// by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3C (for the 128x32)
// init done
Serial.println("OLED begun");
// Show image buffer on the display hardware.
// Since the buffer is intialized with an Adafruit splashscreen
// internally, this will display the splashscreen.
display.display();
delay(1000);
// Clear the buffer.
display.clearDisplay();
display.display();
Serial.println("IO test");
pinMode(BUTTON_A, INPUT_PULLUP);
pinMode(BUTTON_B, INPUT_PULLUP);
pinMode(BUTTON_C, INPUT_PULLUP);
// text display tests
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.print("Connecting to SSID\n'adafruit':");
display.print("connected!");
display.println("IP: 10.0.1.23");
display.println("Sending val #0");
display.setCursor(0,0);
display.display(); // actually display all of the above
}
void loop() {
if (! digitalRead(BUTTON_A)) display.print("A");
if (! digitalRead(BUTTON_B)) display.print("B");
if (! digitalRead(BUTTON_C)) display.print("C");
delay(10);
yield();
display.display();
}

View File

@ -0,0 +1,156 @@
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ArduinoJson.h>
#include <ESP8266HTTPClient.h>;
Adafruit_SSD1306 display = Adafruit_SSD1306();
#define BUTTON_A 0
#define BUTTON_B 16
#define BUTTON_C 2
#define LED 0
const char* ssid = "ESP8266 - TEST";
const char* password = "Coconuts08";
/*const char* ssid = "ESP8266";
const char* password = "password";*/
const char* host = "192.168.101.18";
ESP8266WebServer server(80);
const int Led = 14;
#if (SSD1306_LCDHEIGHT != 32)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif
void setup() {
pinMode(Led, OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
digitalWrite(Led, LOW);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
String IP = WiFi.localIP()+"";
digitalWrite(Led, HIGH);
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
// by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3C (for the 128x32)
// init done
// Show image buffer on the display hardware.
// Since the buffer is intialized with an Adafruit splashscreen
// internally, this will display the splashscreen.
display.display();
delay(1000);
// Clear the buffer.
display.clearDisplay();
display.display();
Serial.println("IO test");
pinMode(BUTTON_A, INPUT_PULLUP);
pinMode(BUTTON_B, INPUT_PULLUP);
pinMode(BUTTON_C, INPUT_PULLUP);
// text display tests
display.setTextSize(1);
display.setTextColor(WHITE);
}
void loop() {
/* if (! digitalRead(BUTTON_A)) display.print("A");
if (! digitalRead(BUTTON_B)) display.print("B");
if (! digitalRead(BUTTON_C)) display.print("C");
delay(10);
yield();
display.display();*/
if(WiFi.status() != WL_CONNECTED){
digitalWrite(Led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
}else{
if(digitalRead(Led)==LOW){
digitalWrite(Led, HIGH);
}
//if(!digitalRead(BUTTON_A)){
display.clearDisplay();
display.setCursor(0,0);
display.println("Connect to hum sensor");
display.println("");
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
digitalWrite(Led, LOW);
return;
}
HTTPClient http;
http.begin("http://192.168.101.18/temp");
int httpCode = http.GET();
if(httpCode == HTTP_CODE_OK){
Serial.print("HTTP response code ");
Serial.println(httpCode);
String response = http.getString();
Serial.println(response);
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(response);
String temp = root["temperature"];
String hum = root["humidity"];
Serial.println("Temperature :"+temp);
Serial.println("Humidity :"+hum);
display.println("Temp: "+temp+"C - Hum: "+hum+"%");
display.display();
}
else
{
Serial.println("Error in HTTP request");
}
http.end();
delay(5000);
// }
}
}

View File

@ -0,0 +1,103 @@
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
const char* ssid = "ESP8266";
const char* password = "password";
ESP8266WebServer server(80);
const int Relay = 13;
const int Led = 14;
void handleRoot() {
server.send(200, "text/plain", "hello from esp8266!");
}
void handleNotFound(){
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void setup(void){
pinMode(Led, OUTPUT);
pinMode(Relay, OUTPUT);
Serial.begin(115200);
WiFi.softAPdisconnect(true);
WiFi.begin(ssid, password);
Serial.println("");
digitalWrite(Led, LOW);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(Led, HIGH);
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/open", [](){
server.send(200, "text/plain", "open led");
digitalWrite(Relay, HIGH);
});
server.on("/close", [](){
server.send(200, "text/plain", "close led");
digitalWrite(Relay, LOW);
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
if(WiFi.status() != WL_CONNECTED){
digitalWrite(Led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
}else{
if(digitalRead(Led)==LOW){
digitalWrite(Led, HIGH);
}
}
/*long sensor = digitalRead(motion);
if(sensor == HIGH){
digitalWrite (led, HIGH);
}
else
{
digitalWrite (led, LOW);
}*/
}

View File

@ -0,0 +1,17 @@
const int Temp = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(Temp, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.print("Temperature: ");
Serial.println(analogRead(Temp));
delay(1000);
}

View File

@ -0,0 +1,101 @@
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
const char* ssid = "ESP8266 - TEST";
const char* password = "Coconuts08";
ESP8266WebServer server(80);
const int RelayL = 13;
const int Led = 14;
bool flash = false;
void handleRoot() {
server.send(200, "text/plain", "hello from esp8266-relayL!");
}
void handleNotFound(){
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void setup(void){
pinMode(RelayL, OUTPUT);
pinMode(Led, OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
digitalWrite(Led, LOW);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(Led, HIGH);
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/open", [](){
server.send(200, "text/plain", "open relayL");
flash = true;
});
server.on("/close", [](){
server.send(200, "text/plain", "close relayL");
flash = false;
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
if(WiFi.status() != WL_CONNECTED){
digitalWrite(Led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
}else{
if(digitalRead(Led)==LOW){
digitalWrite(Led, HIGH);
}
if(flash){
digitalWrite(RelayL, HIGH);
delay(1000);
digitalWrite(RelayL, LOW);
}
delay(1000);
}
}

View File

@ -0,0 +1,117 @@
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "ESP8266 - TEST";
const char* password = "Coconuts08";
const char* mqtt_server = "138.48.32.159";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
const int RelayL = 13;
const int Led = 14;
bool flash = false;
bool RelayState = false;
void setup(void){
pinMode(RelayL, OUTPUT);
pinMode(Led, OUTPUT);
Serial.begin(115200);
Serial.println("");
digitalWrite(Led, LOW);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
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());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
if ((char)payload[0] == '1') {
RelayState = digitalRead(RelayL); // getState
Serial.println(digitalRead(RelayL));
flash = true;
}
if ((char)payload[0] == '0') {
flash = false;
Serial.println(digitalRead(RelayL));
if(RelayState==0)digitalWrite(RelayL, LOW); else digitalWrite(RelayL, HIGH); // récupère state
}
if ((char)payload[0] == '4' && flash == false) digitalWrite(RelayL, HIGH);
if ((char)payload[0] == '5' && flash == false) digitalWrite(RelayL, LOW);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop(void){
if (!client.connected()) {
digitalWrite(Led, LOW);
reconnect();
}else{
digitalWrite(Led, HIGH);
}
client.loop();
if(flash){
digitalWrite(RelayL, HIGH);
delay(1000);
digitalWrite(RelayL, LOW);
}
delay(1000);
}

View File

@ -0,0 +1,83 @@
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
const char* ssid = "ESP8266";
const char* password = "password";
const char* host = "192.168.4.2";
ESP8266WebServer server(80);
const int Led = 14;
void setup() {
pinMode(Led, OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
digitalWrite(Led, LOW);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(Led, HIGH);
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
}
void loop() {
if(WiFi.status() != WL_CONNECTED){
digitalWrite(Led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
}else{
if(digitalRead(Led)==LOW){
digitalWrite(Led, HIGH);
}
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
digitalWrite(Led, LOW);
return;
}
String urlTemp = "/temp";
Serial.print("Requesting URL: ");
client.print(String("GET ") + urlTemp + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
delay(20000);
}
}

View File

@ -0,0 +1,102 @@
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ArduinoJson.h>
const char* ssid = "ESP8266";
const char* password = "password";
const char* host = "192.168.4.3";
ESP8266WebServer server(80);
const int Led = 14;
void setup() {
pinMode(Led, OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
digitalWrite(Led, LOW);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(Led, HIGH);
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
}
void loop() {
if(WiFi.status() != WL_CONNECTED){
digitalWrite(Led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
}else{
if(digitalRead(Led)==LOW){
digitalWrite(Led, HIGH);
}
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
digitalWrite(Led, LOW);
return;
}
String urlTemp = "/temp";
Serial.print("Requesting URL: ");
client.print(String("GET ") + urlTemp + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
String json = "";
boolean httpBody = false;
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
if (!httpBody && line.charAt(1) == '{') {
httpBody = true;
}
if (httpBody) {
json += line;
}
}
StaticJsonBuffer<200> jsonBuffer;
Serial.println("Got data:");
Serial.println(json);
JsonObject& root = jsonBuffer.parseObject(json);
String temp = root["temperature"];
String hum = root["humidity"];
Serial.println("Temperature :"+temp);
Serial.println("Humidity :"+hum);
delay(5000);
}
}

View File

@ -0,0 +1,70 @@
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
const char* ssid = "ESP8266";
const char* password = "password";
ESP8266WebServer server(80);
const int Led = 14;
void handleRoot() {
server.send(200, "text/plain", "hello from esp8266!");
}
void handleNotFound(){
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void setup(void){
pinMode(Led, OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
digitalWrite(Led, LOW);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(Led, HIGH);
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/temp", [](){
String arguments = server.arg("coucou");
server.send(200, "text/plain", arguments);
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
}

View File

@ -0,0 +1,72 @@
/*
* Simple HTTP get webclient test
*/
#include <ESP8266WiFi.h>
const char* ssid = "ESP8266-Test";
const char* password = "pcf00521";
const char* host = "wifitest.adafruit.com";
void setup() {
Serial.begin(115200);
delay(100);
// 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 = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
// We now create a URI for the request
String url = "/testwifi/index.html";
Serial.print("Requesting URL: ");
Serial.println(url);
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
delay(500);
// 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");
}

View File

@ -0,0 +1,59 @@
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
int i;
int redpin=0;
const char* ssid = "Smart_Kot";
const char* password = "Coconuts08";
const char* host = "192.168.200.179";
void setup() {
pinMode(redpin,INPUT);
Serial.begin(9600);
WiFi.softAPdisconnect(true);
WiFi.begin(ssid, password);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
i=analogRead(redpin);
Serial.println(i);
delay(500);
if(i<100){
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
String urlTV = "/TV";
Serial.print("Requesting URL: ");
client.print(String("GET ") + urlTV + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
delay(2000);
String urlLed = "/ledGreen";
Serial.print("Requesting URL: ");
client.print(String("GET ") + urlLed + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
delay(4000);
}
}

View File

@ -0,0 +1,68 @@
#include <OneWire.h>
// ---------- Initialisation des variables ---------------------
// Variables propres au DS18B20
const int DS18B20_PIN=10;
const int DS18B20_ID=0x28;
// Déclaration de l'objet ds
OneWire ds(DS18B20_PIN); // on pin DS18B20_PIN (a 4.7K resistor is necessary)
// Variables générales
float DS18B20_temperature;
const int SERIAL_PORT=9600;
void setup() {
// Initialisation du port de communication avec le PC
Serial.begin(SERIAL_PORT);
Serial.println("Initialisation du programme");
}
void loop() {
DS18B20_temperature = getTemperatureDS18b20(); // On lance la fonction d'acquisition de T°
// on affiche la T°
Serial.print("(DS18B20) =>\t temperature: ");
Serial.println(DS18B20_temperature);
}
/* --------------- Acquisition de la température ----------------------------------- */
float getTemperatureDS18b20(){
byte i;
byte data[12];
byte addr[8];
float temp =0.0;
//Il n'y a qu'un seul capteur, donc on charge l'unique adresse.
ds.search(addr);
// Cette fonction sert à surveiller si la transmission s'est bien passée
if (OneWire::crc8( addr, 7) != addr[7]) {
Serial.println("getTemperatureDS18b20 : <!> CRC is not valid! <!>");
return false;
}
// On vérifie que l'élément trouvé est bien un DS18B20
if (addr[0] != DS18B20_ID) {
Serial.println("L'équipement trouvé n'est pas un DS18B20");
return false;
}
// Demander au capteur de mémoriser la température et lui laisser 850ms pour le faire (voir datasheet)
ds.reset();
ds.select(addr);
ds.write(0x44);
delay(850);
// Demander au capteur de nous envoyer la température mémorisé
ds.reset();
ds.select(addr);
ds.write(0xBE);
// Le MOT reçu du capteur fait 9 octets, on les charge donc un par un dans le tableau data[]
for ( i = 0; i < 9; i++) {
data[i] = ds.read();
}
// Puis on converti la température (*0.0625 car la température est stockée sur 12 bits)
temp = ( (data[1] << 8) + data[0] )*0.0625;
return temp;
}

View File

@ -0,0 +1,13 @@
int i;
int val;
int redpin=0;
void setup() {
pinMode(redpin,OUTPUT);
Serial.begin(9600);
}
void loop() {
i=analogRead(redpin);
Serial.println(i* 0.0078125);
delay(500);
}

View File

@ -0,0 +1,32 @@
#include <SPI.h>
#include <RFID.h>
RFID monModuleRFID(10,9);
int UID[5];
void setup()
{
Serial.begin(9600);
SPI.begin();
monModuleRFID.init();
}
void loop()
{
if (monModuleRFID.isCard()) {
if (monModuleRFID.readCardSerial()) {
Serial.print("L'UID est: ");
for(int i=0;i<=4;i++)
{
UID[i]=monModuleRFID.serNum[i];
Serial.print(UID[i],DEC);
Serial.print(".");
}
Serial.println("");
}
monModuleRFID.halt();
}
delay(1);
}

View File

@ -0,0 +1,22 @@
int Led = 13 ;// define LED Interface
int buttonpin = 4; // define the obstacle avoidance sensor interface
int val ;// define numeric variables val
void setup ()
{
pinMode (Led, OUTPUT) ;// define LED as output interface
pinMode (buttonpin, INPUT) ;// define the obstacle avoidance sensor output interface
Serial.begin(9600);
}
void loop ()
{
val = digitalRead (buttonpin) ;// digital interface will be assigned a value of 3 to read val
Serial.println(val);
if (val == HIGH) // When the obstacle avoidance sensor detects a signal, LED flashes
{
digitalWrite (Led, HIGH);
}
else
{
digitalWrite (Led, LOW);
}
}

View File

@ -0,0 +1,20 @@
#include <IRremoteESP8266.h>
int RECV_PIN = 2; //an IR detector/demodulatord is connected to GPIO pin 2
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}
void loop() {
if (irrecv.decode(&results)) {
// Print value
Serial.println(results.value, HEX);
irrecv.resume(); // Receive the next value
}
}

View File

@ -0,0 +1,149 @@
#include <IRremoteESP8266.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
IRsend irsend(4); //an IR led is connected to GPIO pin 0
const char* ssid = "VOO-375468";
const char* password = "UYQQMTHF";
ESP8266WebServer server(80);
const int led = 5;
void handleRoot() {
server.send(200, "text/plain", "Wemos IR Remote");
}
void handleNotFound(){
digitalWrite(led, 1);
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
digitalWrite(led, 0);
}
void setup()
{
irsend.begin();
pinMode(led, OUTPUT);
Serial.begin(115200);
WiFi.softAPdisconnect(true);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(led, HIGH);
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/TV", [](){
server.send(200, "text/plain", "open/close tv");
for (int i = 0; i < 5; i++) {
irsend.sendSony(0xa90, 12);
delay(40);
}
});
server.on("/ledRed", [](){
server.send(200, "text/plain", "open red led");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xff9867, 32);
delay(40);
}
});
server.on("/ledGreen", [](){
server.send(200, "text/plain", "open green led");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffd827, 32);
delay(40);
}
});
server.on("/ledBlue", [](){
server.send(200, "text/plain", "open blue led");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xff8877, 32);
delay(40);
}
});
server.on("/ledWhite", [](){
server.send(200, "text/plain", "open white led");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffa857, 32);
delay(40);
}
});
server.on("/ledClose", [](){
server.send(200, "text/plain", "close led");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xfff807, 32);
delay(40);
}
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
if(WiFi.status() != WL_CONNECTED){
digitalWrite(led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
digitalWrite(led, HIGH);
}
}

View File

@ -0,0 +1,16 @@
#include <IRremoteESP8266.h>
IRsend irsend(0); //an IR led is connected to GPIO pin 0
void setup()
{
irsend.begin();
}
void loop() {
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(20);
}
delay(3000); //5 second delay between each signal burst
}

View File

@ -0,0 +1,149 @@
#include <IRremoteESP8266.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
IRsend irsend(4); //an IR led is connected to GPIO pin 0
const char* ssid = "Smart_Kot";
const char* password = "Coconuts08";
ESP8266WebServer server(80);
const int led = 5;
void handleRoot() {
server.send(200, "text/plain", "Wemos IR Remote");
}
void handleNotFound(){
digitalWrite(led, 1);
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
digitalWrite(led, 0);
}
void setup()
{
irsend.begin();
pinMode(led, OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(led, HIGH);
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/TV", [](){
server.send(200, "text/plain", "open/close tv");
for (int i = 0; i < 3; i++) {
irsend.sendSony(0xa90, 12);
delay(40);
}
});
server.on("/ledRed", [](){
server.send(200, "text/plain", "open red led");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xff9867, 32);
delay(40);
}
});
server.on("/ledGreen", [](){
server.send(200, "text/plain", "open green led");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffd827, 32);
delay(40);
}
});
server.on("/ledBlue", [](){
server.send(200, "text/plain", "open blue led");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xff8877, 32);
delay(40);
}
});
server.on("/ledWhite", [](){
server.send(200, "text/plain", "open white led");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffb04f, 32);
delay(40);
}
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xffa857, 32);
delay(40);
}
});
server.on("/ledClose", [](){
server.send(200, "text/plain", "close led");
for (int i = 0; i < 3; i++) {
irsend.sendNEC(0xfff807, 32);
delay(40);
}
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
if(WiFi.status() != WL_CONNECTED){
digitalWrite(led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
digitalWrite(led, HIGH);
}
}

View File

@ -0,0 +1,24 @@
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
void setup() {
myservo.attach(2); // attaches the servo on pin 9 to the servo object
}
void loop() {
myservo.write(0); // tell servo to go to position in variable 'pos'
delay(1000); // waits 15ms for the servo to reach the position
myservo.write(180); // tell servo to go to position in variable 'pos'
delay(1000);
/* Example:
for (pos = 2200; pos >= 800; pos -= 20) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(25); // waits 15ms for the servo to reach the position
}*/
}

View File

@ -0,0 +1,19 @@
/* Testing MQ-2 GAS sensor with serial monitor
Suitable for detecting of LPG, i-butane, propane, methane ,alcohol, Hydrogen or smoke
More info: http://www.ardumotive.com/how-to-use-mq2-gas-sensor-en.html
Dev: Michalis Vasilakis // Date: 11/6/2015 // www.ardumotive.com */
const int gasPin = A0; //GAS sensor output pin to Arduino analog A0 pin
void setup()
{
Serial.begin(9600); //Initialize serial port - 9600 bps
}
void loop()
{
Serial.println(analogRead(gasPin));
delay(1000); // Print value every 1 sec.
}

View File

@ -0,0 +1,32 @@
const char analogPin = 0;
const char digitalPin = 4;
const char ledPin = 3;
void setup() {
// put your setup code here, to run once:
pinMode(analogPin, INPUT);
pinMode(digitalPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
//Serial.print("Analog: ");
//Serial.println(analogRead(analogPin));
//Serial.print("Digital: ");
//Serial.println(digitalRead(digitalPin));
if(digitalRead(digitalPin)==1){
delay(100);
Serial.println("test");
if(digitalRead(digitalPin)==1){
Serial.println("double clap !");
}
}
}

View File

@ -0,0 +1,25 @@
// Programme du capteur de son
// Letmeknow.fr
const int capteur = 5;// pin connecté à la sortie digital du capteur
const int LED = 3;// pin connecté à la LED + resistance
void setup()
{
pinMode(capteur, INPUT);
pinMode(LED, OUTPUT);
}
void loop()
{
if(digitalRead(capteur)== HIGH)
{
digitalWrite(LED, HIGH);// Allumer la LED
delay(10);// Temps de traitement
}
else
{
digitalWrite(LED, LOW);// Eteindre la LED
delay(10);// Temps de traitement
}
}

View File

@ -0,0 +1,52 @@
/*********
Rui Santos
Complete project details at http://randomnerdtutorials.com
*********/
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into pin D1 on the ESP8266 12-E - GPIO 5
#define ONE_WIRE_BUS 5
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature DS18B20(&oneWire);
char temperatureCString[6];
char temperatureFString[6];
// only runs once on boot
void setup() {
// Initializing serial port for debugging purposes
Serial.begin(115200);
delay(10);
DS18B20.begin(); // IC Default 9 bit. If you have troubles consider upping it 12. Ups the delay giving the IC more time to process the temperature measurement
}
void getTemperature() {
float tempC;
float tempF;
DS18B20.requestTemperatures();
tempC = DS18B20.getTempCByIndex(0);
dtostrf(tempC, 2, 2, temperatureCString);
tempF = DS18B20.getTempFByIndex(0);
dtostrf(tempF, 3, 2, temperatureFString);
delay(100);
}
// runs over and over again
void loop() {
getTemperature();
Serial.println(temperatureCString);
Serial.println(temperatureFString);
}

View File

@ -0,0 +1,19 @@
const int tracingPin = 4;
const int ledPin = 13;
void setup()
{
pinMode(tracingPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop()
{
int val = digitalRead(tracingPin);
if(val == HIGH)
{
digitalWrite(ledPin, HIGH);
}
else
{
digitalWrite(ledPin, LOW);
}
}

View File

@ -0,0 +1,102 @@
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ArduinoJson.h>
const char* ssid = "ESP8266";
const char* password = "password";
const char* host = "192.168.4.3";
ESP8266WebServer server(80);
const int Led = 14;
void setup() {
pinMode(Led, OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
digitalWrite(Led, LOW);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(Led, HIGH);
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
}
void loop() {
if(WiFi.status() != WL_CONNECTED){
digitalWrite(Led, LOW);
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
}else{
if(digitalRead(Led)==LOW){
digitalWrite(Led, HIGH);
}
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
digitalWrite(Led, LOW);
return;
}
String urlTemp = "/temp";
Serial.print("Requesting URL: ");
client.print(String("GET ") + urlTemp + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
String json = "";
boolean httpBody = false;
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
if (!httpBody && line.charAt(1) == '{') {
httpBody = true;
}
if (httpBody) {
json += line;
}
}
StaticJsonBuffer<200> jsonBuffer;
Serial.println("Got data:");
Serial.println(json);
JsonObject& root = jsonBuffer.parseObject(json);
String temp = root["temperature"];
String hum = root["humidity"];
Serial.println("Temperature :"+temp);
Serial.println("Humidity :"+hum);
delay(5000);
}
}

Binary file not shown.

View File

@ -0,0 +1,35 @@
#include <Arduino.h>
#include <time.h>
void setup() {
// put your setup code here, to run once:
setup_RTC_interrupt();
Serial.begin(38400); // open the serial port at 9600 bps:
tm CurrTimeDate; // set up an array for the RTC info.
// <year yyyy> <month mm Jan=0> <date dd> <day d Sun=0> <hour hh> <minute mm> <second ss>
CurrTimeDate.tm_year = (uint8_t)( 2016 - 1900 );
CurrTimeDate.tm_mon = (uint8_t) 0;
CurrTimeDate.tm_mday = (uint8_t) 12;
CurrTimeDate.tm_wday = (uint8_t) 2;
CurrTimeDate.tm_hour = (uint8_t) 17;
CurrTimeDate.tm_min = (uint8_t) 16;
CurrTimeDate.tm_sec = (uint8_t) 0;
set_system_time( mktime( (ptm)&CurrTimeDate));
}
void loop() {
// put your main code here, to run repeatedly:
time_t currentTick; // set up a location for the current time stamp since the
time((time_t *)&currentTick);
Serial.println(ctime( (time_t *)&currentTick));
delay(2000);
}

View File

@ -0,0 +1,9 @@
name=AVR Standard C Time Library
version=1.8.0-4
author=Michael Duane Rice <mike@mikerice.name>
maintainer=Phillip Stevens <phillip.stevens@gmail.com>
sentence=Time functions for AVR (Goldilocks, Uno, Leonardo, Mega).
paragraph=The implementation aspires to conform with ISO/IEC 9899 (C90). However, due to limitations of the target processor and the nature of its development environment, a practical AVR implementation must of necessity deviate from the C90 standard time.h. Will work with AVR ATmega with a clock crystal on Timer 2.
category=Timing
url=https://github.com/feilipu/Arduino_RTC_Library
architectures=avr

View File

@ -0,0 +1,141 @@
This is a fork of Michael Duane C library Time functions, optimised for the Arduino AVR devices,
found in avr_libc version 1.8.0 and above.
It has been created to provide access to RTC capabilities on AVR devices with the ability to
connect a 32kHz watch crystal on Timer 2.
It is not compatible with the Arduino tones.h functions, as the tones library has not been
fully implemented to use another timer other than Timer 2.
## General
The implementation aspires to conform with ISO/IEC 9899 (C90). However, due to limitations of the
target processor and the nature of its development environment, a practical implementation must
of necessity deviate from the standard.
Section 7.23.2.1 clock()
The type clock_t, the macro CLOCKS_PER_SEC, and the function clock() are not implemented. We
consider these items belong to operating system code, or to application code when no operating
system is present.
Section 7.23.2.3 mktime()
The standard specifies that mktime() should return (time_t) -1, if the time cannot be represented.
This implementation always returns a 'best effort' representation.
Section 7.23.2.4 time()
The standard specifies that time() should return (time_t) -1, if the time is not available.
Since the application must initialize the time system, this functionality is not implemented.
Section 7.23.2.2, difftime()
Due to the lack of a 64 bit double, the function difftime() returns a long integer. In most cases
this change will be invisible to the user, handled automatically by the compiler.
Section 7.23.1.4 struct tm
Per the standard, struct tm->tm_isdst is greater than zero when Daylight Saving time is in effect.
This implementation further specifies that, when positive, the value of tm_isdst represents
the amount time is advanced during Daylight Saving time.
Section 7.23.3.5 strftime()
Only the 'C' locale is supported, therefore the modifiers 'E' and 'O' are ignored.
The 'Z' conversion is also ignored, due to the lack of time zone name.
In addition to the above departures from the standard, there are some behaviors which are different
from what is often expected, though allowed under the standard.
There is no 'platform standard' method to obtain the current time, time zone, or
daylight savings 'rules' in the AVR environment. Therefore the application must initialize
the time system with this information. The functions set_zone(), set_dst(), and
set_system_time() are provided for initialization. Once initialized, system time is maintained by
calling the function system_tick() at one second intervals.
Though not specified in the standard, it is often expected that time_t is a signed integer
representing an offset in seconds from Midnight Jan 1 1970... i.e. 'Unix time'. This implementation
uses an unsigned 32 bit integer offset from Midnight Jan 1 2000. The use of this 'epoch' helps to
simplify the conversion functions, while the 32 bit value allows time to be properly represented
until Tue Feb 7 06:28:15 2136 UTC. The macros UNIX_OFFSET and NTP_OFFSET are defined to assist in
converting to and from Unix and NTP time stamps.
Unlike desktop counterparts, it is impractical to implement or maintain the 'zoneinfo' database.
Therefore no attempt is made to account for time zone, daylight saving, or leap seconds in past dates.
All calculations are made according to the currently configured time zone and daylight saving 'rule'.
In addition to C standard functions, re-entrant versions of ctime(), asctime(), gmtime() and
localtime() are provided which, in addition to being re-entrant, have the property of claiming
less permanent storage in RAM. An additional time conversion, isotime() and its re-entrant version,
uses far less storage than either ctime() or asctime().
Along with the usual smattering of utility functions, such as is_leap_year(), this library includes
a set of functions related the sun and moon, as well as sidereal time functions.
## Reference Manual
http://www.nongnu.org/avr-libc/user-manual/group__avr__time.html
The tm structure contains a representation of time 'broken down' into components of the
Gregorian calendar.
The normal ranges of the elements of tm are..
```
tm_sec seconds after the minute - [ 0 to 59 ]
tm_min minutes after the hour - [ 0 to 59 ]
tm_hour hours since midnight - [ 0 to 23 ]
tm_mday day of the month - [ 1 to 31 ]
tm_wday days since Sunday - [ 0 to 6 ]
tm_mon months since January - [ 0 to 11 ]
tm_year years since 2000
tm_yday days since January 1 - [ 0 to 365 ]
tm_isdst Daylight Saving Time flag *
```
## Compatibility
* ATmega1284p @ 24.576MHz : Seeed Studio Goldilocks, Seeed Studio Goldilocks Analogue
* ATmega2560 @ 16MHz : Arduino Mega, Arduino ADK
* ATmega2560 @ 16MHz : Seeed Studio ADK
## Files & Configuration
* time.h : contains the definitions for all functions.
* setup_RTC_interrupt() : this initialises Timer2, and the "once per second" RTC interrupt.
Example code for basic functions below.
```
#include <Arduino.h>
#include <time.h>
void setup() {
// put your setup code here, to run once:
setup_RTC_interrupt(); // initialise the RTC.
Serial.begin(38400); // open the serial port at 38400 bps.
tm CurrTimeDate; // set up an array for the RTC info.
// <year yyyy> <month mm Jan=0> <date dd> <day d Sun=0> <hour hh> <minute mm> <second ss>
CurrTimeDate.tm_year = (uint8_t)( 2016 - 1900 );
CurrTimeDate.tm_mon = (uint8_t) 0;
CurrTimeDate.tm_mday = (uint8_t) 12;
CurrTimeDate.tm_wday = (uint8_t) 2;
CurrTimeDate.tm_hour = (uint8_t) 17;
CurrTimeDate.tm_min = (uint8_t) 16;
CurrTimeDate.tm_sec = (uint8_t) 0;
set_system_time( mktime( (ptm)&CurrTimeDate));
}
void loop() {
// put your main code here, to run repeatedly:
time_t currentTick; // set up a location for the current time stamp.
time((time_t *)&currentTick); // get the current time stamp.
Serial.println(ctime( (time_t *)&currentTick));
delay(2000);
}
```

View File

@ -0,0 +1,39 @@
/*
* (c)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Private allocation, shared between asctime() and isotime()
*/
#include "time.h"
char __store[26];
char *__asc_store = __store;

View File

@ -0,0 +1,44 @@
/*
* (c)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Standard asctime(), we simply punt to the re-entrant version.
*/
#include "time.h"
extern char *__asc_store;
char *
asctime(const struct tm * timeptr)
{
asctime_r(timeptr, __asc_store);
return __asc_store;
}

View File

@ -0,0 +1,77 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Re-entrant version of asctime().
*/
#include <stdlib.h>
#include "time.h"
const char ascmonths[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
const char ascdays[] = "SunMonTueWedThuFriSat";
extern void __print_lz(int , char *, char );
void
asctime_r(const struct tm * timeptr, char *buffer)
{
uint8_t i, m, d;
div_t result;
d = timeptr->tm_wday * 3;
m = timeptr->tm_mon * 3;
for (i = 0; i < 3; i++) {
buffer[i] = ascdays[d++];
buffer[i+4] = ascmonths[m++];
}
buffer[3]=buffer[7]=' ';
buffer += 8;
__print_lz(timeptr->tm_mday,buffer,' ');
buffer += 3;
__print_lz(timeptr->tm_hour,buffer,':');
buffer += 3;
__print_lz(timeptr->tm_min,buffer,':');
buffer += 3;
__print_lz(timeptr->tm_sec,buffer,' ');
buffer += 3;
result = div(timeptr->tm_year + 1900 , 100);
__print_lz(result.quot,buffer,' ');
buffer += 2;
__print_lz(result.rem,buffer,0);
}

View File

@ -0,0 +1,47 @@
/*
* ©2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Standard ctime(). We have to break down the time stamp, print it into our
private buffer, and return the buffer.
*/
#include "time.h"
extern char *__asc_store;
char *
ctime(const time_t * timeptr)
{
struct tm calendar;
localtime_r(timeptr, &calendar);
asctime_r(&calendar, __asc_store);
return __asc_store;
}

View File

@ -0,0 +1,43 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Re entrant version of ctime()
*/
#include "time.h"
void
ctime_r(const time_t * timeptr, char *buffer)
{
struct tm calendar;
localtime_r(timeptr, &calendar);
asctime_r(&calendar, buffer);
}

View File

@ -0,0 +1,72 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Determine the amount of time the sun is above the horizon. At high latitudes, around the
solstices, this can be zero or greater than ONE_DAY.
*/
#include <math.h>
#include "time.h"
extern int32_t __latitude;
int32_t
daylight_seconds(const time_t * timer)
{
float l, d;
uint32_t n;
/* convert latitude to radians */
l = __latitude / 206264.806;
d = -solar_declination(timer);
/* partial 'Sunrise Equation' */
d = tan(l) * tan(d);
/* magnitude of d may exceed 1.0 at near solstices */
if (d > 1.0)
d = 1.0;
if (d < -1.0)
d = -1.0;
/* derive hour angle */
d = acos(d);
/* but for atmospheric refraction, this would be d /= M_PI */
d /= 3.112505;
n = ONE_DAY * d;
return n;
}

View File

@ -0,0 +1,41 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
The C90 standard specifies this returns a 'double. Since we do not have a true double,
we return a work alike type.
*/
#include "time.h"
int32_t
difftime(time_t t1, time_t t2)
{
return (int32_t) t1 - (int32_t) t2;
}

View File

@ -0,0 +1,34 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
#include <inttypes.h>
#include "time.h"
int16_t (*__dst_ptr) (const time_t *, int32_t *);

View File

@ -0,0 +1,44 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
#ifndef EPHEMERA_PRIVATE_H
#define EPHEMERA_PRIVATE_H
#define TROP_YEAR 31556925
#define ANOM_YEAR 31558433
#define INCLINATION 0.409105176667471 /* Earths axial tilt at the epoch */
#define PERIHELION 31316400 /* perihelion of 1999, 03 jan 13:00 UTC */
#define SOLSTICE 836160 /* winter solstice of 1999, 22 Dec 07:44 UTC */
#define TWO_PI 6.283185307179586476925286766559
#define TROP_CYCLE 5022440.6025
#define ANOM_CYCLE 5022680.6082
#define DELTA_V 0.03342044 /* 2x orbital eccentricity */
#endif

View File

@ -0,0 +1,87 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
The so called Equation of Time.
The eccentricity of Earths orbit contributes about 7.7 minutes of variation to the result. It
has a period of 1 anomalous year, with zeroes at perihelion and aphelion.
The tilt of Earths rotational axis (obliquity) contributes about 9.9 minutes of variation. It
has a period of 1/2 tropical year, with zeroes at solstices and equinoxes. The time of Earths
arrival at these events is influenced by the eccentricity, which causes it to progress along its
orbital path faster as it approaches perihelion, imposing a 'modulation' on the tropical phase.
The algorithm employed computes the orbital position with respect to perihelion, deriving
from that a 'velocity correction factor'. The orbital position with respect to the winter solstice
is then computed, as modulated by that factor. The individual contributions of the obliquity and the
eccentricity components are then summed, and returned as an integer value in seconds.
*/
#include <math.h>
#include "time.h"
#include "ephemera_common.h"
int16_t
equation_of_time(const time_t * timer)
{
int32_t s, p;
float pf, sf, dV;
/* compute orbital position relative to perihelion */
p = *timer % ANOM_YEAR;
p += PERIHELION;
pf = p;
pf /= ANOM_CYCLE;
pf = sin(pf);
/* Derive a velocity correction factor from the perihelion angle */
dV = pf * DELTA_V;
/* compute approximate position relative to solstice */
s = *timer % TROP_YEAR;
s += SOLSTICE;
s *= 2;
sf = s;
sf /= TROP_CYCLE;
/* modulate to derive actual position */
sf += dV;
sf = sin(sf);
/* compute contributions */
sf *= 592.2;
pf *= 459.6;
s = pf + sf;
return (int16_t) -s;
}

View File

@ -0,0 +1,99 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Return a value suitable for use as a FAT file system time stamp.
*/
#include "time.h"
uint32_t
system_fatfs(const struct tm * timeptr)
{
uint32_t ret;
uint32_t n;
n = timeptr->tm_year - 80;
n <<= 25;
ret = n;
n = timeptr->tm_mon + 1;
n <<= 21;
ret |= n;
n = timeptr->tm_mday;
n <<= 16;
ret |= n;
n = timeptr->tm_hour;
n <<= 11;
ret |= n;
n = timeptr->tm_min;
n <<= 5;
ret |= n;
ret |= timeptr->tm_sec >> 1;
return ret;
}
/**
Convert a FAT file system time stamp into a Y2K time stamp.
wFatDate [in]
The MS-DOS date. The date is a packed value with the following format.
Bits Description
0-4 Day of the month (131)
5-8 Month (1 = January, 2 = February, and so on)
9-15 Year offset from 1980, subtract 20 to get Y2K year, add 2000 for Gregorian year.
wFatTime [in]
The MS-DOS time. The time is a packed value with the following format.
Bits Description
0-4 Second divided by 2
5-10 Minute (059)
11-15 Hour (023 on a 24-hour clock)
*/
uint32_t
fatfs_system( uint16_t fsdate, uint16_t fstime, struct tm * timeptr)
{
timeptr->tm_year = ((fsdate >> 9) & 0x007F) + 80;
timeptr->tm_mon = ((uint8_t)(fsdate >> 5 ) & 0x0F) - 1;
timeptr->tm_mday = (uint8_t) fsdate & 0x1F;
timeptr->tm_hour = (uint8_t)(fstime >> 11) & 0x1F;
timeptr->tm_min = (uint8_t)(fstime >> 5) & 0x3F;
timeptr->tm_sec = ((uint8_t) fstime & 0x001F) << 1;
return mktime( timeptr );
}

View File

@ -0,0 +1,34 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
#include <stdint.h>
int32_t __latitude;
int32_t __longitude;

View File

@ -0,0 +1,61 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Greenwich Mean Sidereal Time. A sidereal second is somewhat shorter than a standard second,
about 1.002737909350795 sidereal seconds per standard second.
We resort to fixed point math due to the insufficient resolution of a 'double', using...
timestamp * ( 1.002737909350795 << 31 )
--------------------------------------- + Te
1 << 31
Where Te is the sidereal time at the epoch.
*/
#include <stdint.h>
#include "time.h"
uint32_t
gm_sidereal(const time_t * timer)
{
uint64_t tmp;
tmp = *timer;
tmp *= 0x8059B740;
tmp /= 0x80000000;
tmp += (uint64_t) 23991;
tmp %= ONE_DAY;
return tmp;
}

View File

@ -0,0 +1,45 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Standard gmtime(). We convert binary time into calendar time in our private struct tm object,
returning that object.
*/
#include "time.h"
extern struct tm __tm_store;
struct tm *
gmtime(const time_t * timeptr)
{
gmtime_r(timeptr, &__tm_store);
return &__tm_store;
}

View File

@ -0,0 +1,145 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/* Re entrant version of gmtime(). */
#include <stdlib.h>
#include <inttypes.h>
#include "time.h"
void
gmtime_r(const time_t * timer, struct tm * timeptr)
{
int32_t fract;
ldiv_t lresult;
div_t result;
uint16_t days, n, leapyear, years;
/* break down timer into whole and fractional parts of 1 day */
days = *timer / 86400UL;
fract = *timer % 86400UL;
/*
Extract hour, minute, and second from the fractional day
*/
lresult = ldiv(fract, 60L);
timeptr->tm_sec = lresult.rem;
result = div(lresult.quot, 60);
timeptr->tm_min = result.rem;
timeptr->tm_hour = result.quot;
/* Determine day of week ( the epoch was a Saturday ) */
n = days + SATURDAY;
n %= 7;
timeptr->tm_wday = n;
/*
* Our epoch year has the property of being at the conjunction of all three 'leap cycles',
* 4, 100, and 400 years ( though we can ignore the 400 year cycle in this library).
*
* Using this property, we can easily 'map' the time stamp into the leap cycles, quickly
* deriving the year and day of year, along with the fact of whether it is a leap year.
*/
/* map into a 100 year cycle */
lresult = ldiv((long) days, 36525L);
years = 100 * lresult.quot;
/* map into a 4 year cycle */
lresult = ldiv(lresult.rem, 1461L);
years += 4 * lresult.quot;
days = lresult.rem;
if (years > 100)
days++;
/*
* 'years' is now at the first year of a 4 year leap cycle, which will always be a leap year,
* unless it is 100. 'days' is now an index into that cycle.
*/
leapyear = 1;
if (years == 100)
leapyear = 0;
/* compute length, in days, of first year of this cycle */
n = 364 + leapyear;
/*
* if the number of days remaining is greater than the length of the
* first year, we make one more division.
*/
if (days > n) {
days -= leapyear;
leapyear = 0;
result = div(days, 365);
years += result.quot;
days = result.rem;
}
timeptr->tm_year = 100 + years;
timeptr->tm_yday = days;
/*
Given the year, day of year, and leap year indicator, we can break down the
month and day of month. If the day of year is less than 59 (or 60 if a leap year), then
we handle the Jan/Feb month pair as an exception.
*/
n = 59 + leapyear;
if (days < n) {
/* special case: Jan/Feb month pair */
result = div(days, 31);
timeptr->tm_mon = result.quot;
timeptr->tm_mday = result.rem;
} else {
/*
The remaining 10 months form a regular pattern of 31 day months alternating with 30 day
months, with a 'phase change' between July and August (153 days after March 1).
We proceed by mapping our position into either March-July or August-December.
*/
days -= n;
result = div(days, 153);
timeptr->tm_mon = 2 + result.quot * 5;
/* map into a 61 day pair of months */
result = div(result.rem, 61);
timeptr->tm_mon += result.quot * 2;
/* map into a month */
result = div(result.rem, 31);
timeptr->tm_mon += result.quot;
timeptr->tm_mday = result.rem;
}
/*
Cleanup and return
*/
timeptr->tm_isdst = 0; /* gmt is never in DST */
timeptr->tm_mday++; /* tm_mday is 1 based */
}

View File

@ -0,0 +1,57 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Return 1 if 'year' is a leap year, else 0.
*/
#include <stdlib.h>
#include <stdint.h>
uint8_t
is_leap_year(uint16_t year)
{
div_t d;
/* year must be divisible by 4 to be a leap year */
if (year & 3)
return 0;
/* If there is a remainder after division by 100, year is not divisible by 100 or 400 */
d = div(year, 100);
if (d.rem)
return 1;
/* If the quotient is divisible by 4, then year is divisible by 400 */
if ((d.quot & 3) == 0)
return 1;
return 0;
}

View File

@ -0,0 +1,51 @@
/*
* (c)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Compute the ISO 8601 week date corresponding to the given year and day of year.
See http://en.wikipedia.org/wiki/ISO_week_date for a full description.
See iso_week_date_r.c for implementation details.
*/
#include "time.h"
extern char *__asc_store;
struct week_date *
iso_week_date(uint16_t y, uint16_t yday)
{
struct week_date *iso;
iso = (struct week_date *) __asc_store;
iso_week_date_r(y, yday, iso);
return iso;
}

View File

@ -0,0 +1,114 @@
/*
* (c)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Compute the ISO 8601 week date corresponding to the given year and day of year.
See http://en.wikipedia.org/wiki/ISO_week_date for a full description. To summarize:
Weeks are numbered from 1 to 53.
Week days are numbered 1 to 7, beginning with Monday as day 1.
The first week of the year contains the first Thursday in that year.
Dates prior to week 1 belong to the final week of the previous year.
The final week of the year contains the last Thursday in that year.
Dates after the final week belong to week 1 of the following year.
*/
#include "time.h"
void
iso_week_date_r(uint16_t y, uint16_t yday, struct week_date * iso)
{
uint16_t years, n, wday;
int16_t weeknum;
uint8_t isLeap;
iso->year = y;
isLeap = is_leap_year(y);
/* compute days elapsed since epoch */
years = y - 2000;
n = 365 * years + yday;
if (years) {
n++; /* epoch was a leap year */
n += years / 4;
n -= isLeap;
if (years > 100)
n--;
}
/* compute ISO8601 day of week (1 ... 7, Monday = 1) */
wday = n + 6; /* epoch was a Saturday */
wday %= 7;
if (wday == 0)
wday = 7;
iso->day = wday;
/* compute tentative week number */
weeknum = yday + 11 - wday;
weeknum /= 7;
/* if 53, it could be week 1 of the following year */
if (weeknum == 53) {
/*
The final week must include its Thursday in the year. We determine the yday of this
weeks Thursday, and test whether it exceeds this years length.
*/
/* determine final yday of this year, 364 or 365 */
n = 364 + isLeap;
/* compute yday of this weeks Thursday */
wday--; /* convert to zero based week, Monday = 0 */
yday -= wday; /* yday of this weeks Monday */
yday += 3; /* yday of this weeks Thursday */
/* Is this weeks Thursday included in the year? */
if (yday > (int) n) {
iso->year++;
weeknum = 1;
}
}
iso->week = weeknum;
/*
If zero, it is the final week of the previous year.
We determine that by asking for the week number of Dec 31.
*/
if (weeknum == 0) {
y = y - 1;
iso_week_date_r(y, 364 + is_leap_year(y), iso);
iso->day = wday;
}
}

View File

@ -0,0 +1,44 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
This function returns ISO8601 formatted time, in our private buffer.
*/
#include "time.h"
extern char *__asc_store;
char *
isotime(const struct tm * tmptr)
{
isotime_r(tmptr, __asc_store);
return __asc_store;
}

View File

@ -0,0 +1,70 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Re entrant version of isotime(), which prints the date and time in ISO 8601 format.
*/
#include <stdlib.h>
#include "time.h"
extern void __print_lz(int , char *, char );
void
isotime_r(const struct tm * tmptr, char *buffer)
{
int16_t i;
i = tmptr->tm_year + 1900;
__print_lz(i/100, buffer, '-');
buffer+=2;
__print_lz(i%100, buffer,'-');
buffer+=3;
i = tmptr->tm_mon + 1;
__print_lz(i, buffer,'-');
buffer+=3;
i = tmptr->tm_mday;
__print_lz(i, buffer,' ');
buffer+=3;
i = tmptr->tm_hour;
__print_lz(i, buffer,':');
buffer+=3;
i = tmptr->tm_min;
__print_lz(i, buffer,':');
buffer+=3;
i = tmptr->tm_sec;
__print_lz(i, buffer,0);
}

View File

@ -0,0 +1,47 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Local Mean Sidereal Time. See gm_sidereal() for info.
*/
#include "time.h"
extern long __longitude;
uint32_t
lm_sidereal(const time_t * timer)
{
int32_t n;
n = gm_sidereal(timer) + __longitude / 15L;
n += ONE_DAY;
n %= ONE_DAY;
return n;
}

View File

@ -0,0 +1,44 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Standard localtime() function.
*/
#include "time.h"
extern struct tm __tm_store;
struct tm *
localtime(const time_t * timer)
{
localtime_r(timer, &__tm_store);
return &__tm_store;
}

View File

@ -0,0 +1,60 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Re entrant version of localtime(). Given a binary UTC time stamp, add the time
zone and Daylight savings offset, then break it down into calendar time.
*/
#include "time.h"
extern int32_t __utc_offset;
extern int16_t (*__dst_ptr) (const time_t *, int32_t *);
void
localtime_r(const time_t * timer, struct tm * timeptr)
{
time_t lt;
int16_t dst;
dst = -1;
if (__dst_ptr)
dst = __dst_ptr(timer, &__utc_offset);
lt = *timer + __utc_offset;
if (dst > 0)
lt += dst;
gmtime_r(&lt, timeptr);
timeptr->tm_isdst = dst;
}

View File

@ -0,0 +1,113 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
'Break down' a y2k time stamp into the elements of struct tm.
Unlike mktime(), this function does not 'normalize' the elements of timeptr.
*/
#include "time.h"
time_t
mk_gmtime(const struct tm * timeptr)
{
time_t ret;
uint32_t tmp;
int16_t n, m, d, leaps;
/*
Determine elapsed whole days since the epoch to the beginning of this year. Since our epoch is
at a conjunction of the leap cycles, we can do this rather quickly.
*/
n = timeptr->tm_year - 100;
leaps = 0;
if (n) {
m = n - 1;
leaps = m / 4;
leaps -= m / 100;
leaps++;
}
tmp = 365UL * n + leaps;
/*
Derive the day of year from month and day of month. We use the pattern of 31 day months
followed by 30 day months to our advantage, but we must 'special case' Jan/Feb, and
account for a 'phase change' between July and August (153 days after March 1).
*/
d = timeptr->tm_mday - 1; /* tm_mday is one based */
/* handle Jan/Feb as a special case */
if (timeptr->tm_mon < 2) {
if (timeptr->tm_mon)
d += 31;
} else {
n = 59 + is_leap_year(timeptr->tm_year + 1900);
d += n;
n = timeptr->tm_mon - MARCH;
/* account for phase change */
if (n > (JULY - MARCH))
d += 153;
n %= 5;
/*
* n is now an index into a group of alternating 31 and 30
* day months... 61 day pairs.
*/
m = n / 2;
m *= 61;
d += m;
/*
* if n is odd, we are in the second half of the
* month pair
*/
if (n & 1)
d += 31;
}
/* Add day of year to elapsed days, and convert to seconds */
tmp += d;
tmp *= ONE_DAY;
ret = tmp;
/* compute 'fractional' day */
tmp = timeptr->tm_hour;
tmp *= ONE_HOUR;
tmp += timeptr->tm_min * 60UL;
tmp += timeptr->tm_sec;
ret += tmp;
return ret;
}

View File

@ -0,0 +1,61 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Standard mktime(). The provided broken down Local 'calendar' time is converted into
a binary time stamp. The process is then reversed to 'normalize' timeptr.
*/
#include "time.h"
extern int32_t __utc_offset;
extern int16_t (*__dst_ptr) (const time_t *, int32_t *);
time_t
mktime(struct tm * timeptr)
{
time_t ret;
ret = mk_gmtime(timeptr);
if (timeptr->tm_isdst < 0) {
if (__dst_ptr)
timeptr->tm_isdst = __dst_ptr(&ret, &__utc_offset);
}
if (timeptr->tm_isdst > 0)
ret -= timeptr->tm_isdst;
ret -= __utc_offset;
localtime_r(&ret, timeptr);
return ret;
}

View File

@ -0,0 +1,48 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Return the length of a month in days, given the year and month in question.
The month parameter must be '1 based', ranging from 1 to 12.
*/
#include "time.h"
uint8_t
month_length(uint16_t year, uint8_t month)
{
if (month == 2)
return 28 + is_leap_year(year);
/* 'knuckles' algorithm */
if (month > 7)
month++;
return 30 + (month & 1);
}

View File

@ -0,0 +1,66 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Return an approximation to the phase of the moon. Since no attempt is made to account for
Sol, Jupiter or Venus, it will often be off by several hours.
*/
#include <math.h>
#include "time.h"
int8_t
moon_phase(const time_t * timestamp)
{
uint32_t t;
int32_t n;
float mc;
/* refer to first new moon of the epoch */
t = *timestamp - 1744800UL;
/* constrain to 1 lunar cycle */
n = t % 2551443UL;
/* offset by 1/2 lunar cycle */
n -= 1275721L;
mc = n;
mc /= 1275721.0;
mc *= M_PI;
mc = cos(mc) * sin(mc);
mc *= 12.5;
/* scale to range - 100...+ 100 */
n /= 12757L;
n -= mc;
return (int8_t) n;
}

View File

@ -0,0 +1,45 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/* print 2 digit integer with leading zero: auxillary function for isotime and asctime */
#include <stdlib.h>
void
__print_lz(int i, char *buffer, char s)
{
div_t result;
result = div(i, 10);
*buffer++ = result.quot + '0';
*buffer++ = result.rem + '0';
*buffer = s;
}

View File

@ -0,0 +1,45 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Set the dst function pointer.
*/
#include <inttypes.h>
#include "time.h"
extern int16_t (*__dst_ptr) (const time_t *, int32_t *);
void
set_dst(int16_t (*d) (const time_t *, int32_t *))
{
__dst_ptr = d;
}

View File

@ -0,0 +1,46 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Set the geographic position of the observer. Both parameters are in seconds, with
North latitude and East longitude being positive values.
*/
#include <stdint.h>
extern int32_t __latitude;
extern int32_t __longitude;
void
set_position(int32_t lat, int32_t lon)
{
__latitude = lat;
__longitude = lon;
}

View File

@ -0,0 +1,56 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
* Set the system time. The values passed are assumed to represent local
* standard time, such as would be obtained from the typical Real Time Clock
* integrated circuit. It is necessary for this to be atomic, as the value may be
* incremented at interrupt time.
*/
#include "time.h"
extern volatile time_t __system_time;
void
set_system_time(time_t timestamp)
{
__asm__ __volatile__(
"in __tmp_reg__, __SREG__" "\n\t"
"cli" "\n\t"
::
);
__system_time = timestamp;
__asm__ __volatile__(
"out __SREG__, __tmp_reg__" "\n\t"
::
);
}

View File

@ -0,0 +1,43 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Set the system time zone. The parameter is seconds offset from UTC.
*/
#include <stdint.h>
extern int32_t __utc_offset;
void
set_zone(int32_t z)
{
__utc_offset = z;
}

View File

@ -0,0 +1,78 @@
/*
* (C)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Were it not for the eccentricity of Earths orbit, this would be a trivial function.
We compute the Earths orbital position with respect to perihelion, from which we derive a
'velocity correction factor'. We then compute the orbital angle with respect to the
December solstice, as 'modulated' by that correction factor.
Due to the accumulation of rounding errors, the computed December solstice of 2135 will lag
the actual solstice by many hours. A fudge factor, 'LAG', distributes the error across
the 136 year range of this library.
*/
#include <math.h>
#include "time.h"
#include "ephemera_common.h"
#define LAG 38520
float
solar_declination(const time_t * timer)
{
uint32_t fT, oV;
float dV, dT;
/* Determine orbital angle relative to perihelion of January 1999 */
oV = *timer % ANOM_YEAR;
oV += PERIHELION;
dV = oV;
dV /= ANOM_CYCLE;
/* Derive velocity correction factor from the perihelion angle */
dV = sin(dV);
dV *= DELTA_V;
/* Determine orbital angle relative to solstice of December 1999 */
fT = *timer % TROP_YEAR;
fT += SOLSTICE + LAG;
dT = fT;
dT /= TROP_CYCLE;
dT += dV;
/* Finally having the solstice angle, we can compute the declination */
dT = cos(dT) * INCLINATION;
return -dT;
}

View File

@ -0,0 +1,57 @@
/*
* (c)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Return the time of solar noon at the observers position
*/
#include "time.h"
extern long __longitude;
time_t
solar_noon(const time_t * timer)
{
time_t t;
int32_t n;
/* determine time of solar noon at the prime meridian */
t = *timer % ONE_DAY;
t = *timer - t;
t += 43200L;
t -= equation_of_time(timer);
/* rotate to observers longitude */
n = __longitude / 15L;
t -= n;
return t;
}

View File

@ -0,0 +1,303 @@
/*
* (c)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Standard strftime(). This is a memory hungry monster.
*/
#include <stdlib.h>
#include <stdio.h>
#include "time.h"
extern int32_t __utc_offset;
const char strfwkdays[] = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday ";
const char strfmonths[] = "January February March April May June July August September October November December ";
unsigned char
pgm_copystring(const char *p, unsigned char i, char *b, unsigned char l)
{
unsigned char ret, c;
ret = 0;
while (i) {
c = *p++;
if (c == ' ')
i--;
}
c = *p++;
while (c != ' ' && l--) {
*b++ = c;
ret++;
c = *p++;
}
*b = 0;
return ret;
}
size_t
strftime(char *buffer, size_t limit, const char *pattern, const struct tm * timeptr)
{
uint16_t count, length;
int16_t d, w;
char c;
char _store[26];
struct week_date wd;
count = length = 0;
while (count < limit) {
c = *pattern++;
if (c == '%') {
c = *pattern++;
if (c == 'E' || c == 'O')
c = *pattern++;
switch (c) {
case ('%'):
_store[0] = c;
length = 1;
break;
case ('a'):
length = pgm_copystring(strfwkdays, timeptr->tm_wday, _store, 3);
break;
case ('A'):
length = pgm_copystring(strfwkdays, timeptr->tm_wday, _store, 255);
break;
case ('b'):
case ('h'):
length = pgm_copystring(strfmonths, timeptr->tm_mon, _store, 3);
break;
case ('B'):
length = pgm_copystring(strfmonths, timeptr->tm_mon, _store, 255);
break;
case ('c'):
asctime_r(timeptr, _store);
length = 0;
while (_store[length])
length++;
break;
case ('C'):
d = timeptr->tm_year + 1900;
d /= 100;
length = sprintf(_store, "%.2d", d);
break;
case ('d'):
length = sprintf(_store, "%.2u", timeptr->tm_mday);
break;
case ('D'):
length = sprintf(_store, "%.2u/%.2u/%.2u", \
timeptr->tm_mon + 1, \
timeptr->tm_mday, \
timeptr->tm_year % 100 \
);
break;
case ('e'):
length = sprintf(_store, "%2d", timeptr->tm_mday);
break;
case ('F'):
length = sprintf(_store, "%d-%.2d-%.2d", \
timeptr->tm_year + 1900, \
timeptr->tm_mon + 1, \
timeptr->tm_mday \
);
break;
case ('g'):
case ('G'):
iso_week_date_r(timeptr->tm_year + 1900, timeptr->tm_yday, &wd);
if (c == 'g') {
length = sprintf(_store, "%.2d", wd.year % 100);
} else {
length = sprintf(_store, "%.4d", wd.year);
}
break;
case ('H'):
length = sprintf(_store, "%.2u", timeptr->tm_hour);
break;
case ('I'):
d = timeptr->tm_hour % 12;
if (d == 0)
d = 12;
length = sprintf(_store, "%.2u", d);
break;
case ('j'):
length = sprintf(_store, "%.3u", timeptr->tm_yday + 1);
break;
case ('m'):
length = sprintf(_store, "%.2u", timeptr->tm_mon + 1);
break;
case ('M'):
length = sprintf(_store, "%.2u", timeptr->tm_min);
break;
case ('n'):
_store[0] = 10;
length = 1;
break;
case ('p'):
length = 2;
_store[0] = 'A';
if (timeptr->tm_hour > 11)
_store[0] = 'P';
_store[1] = 'M';
_store[2] = 0;
break;
case ('r'):
d = timeptr->tm_hour % 12;
if (d == 0)
d = 12;
length = sprintf(_store, "%2d:%.2d:%.2d AM", \
d, \
timeptr->tm_min, \
timeptr->tm_sec \
);
if (timeptr->tm_hour > 11)
_store[10] = 'P';
break;
case ('R'):
length = sprintf(_store, "%.2d:%.2d", timeptr->tm_hour, timeptr->tm_min);
break;
case ('S'):
length = sprintf(_store, "%.2u", timeptr->tm_sec);
break;
case ('t'):
length = sprintf(_store, "\t");
break;
case ('T'):
length = sprintf(_store, "%.2d:%.2d:%.2d", \
timeptr->tm_hour, \
timeptr->tm_min, \
timeptr->tm_sec \
);
break;
case ('u'):
w = timeptr->tm_wday;
if (w == 0)
w = 7;
length = sprintf(_store, "%d", w);
break;
case ('U'):
length = sprintf(_store, "%.2u", week_of_year(timeptr, 0));
break;
case ('V'):
iso_week_date_r(timeptr->tm_year + 1900, timeptr->tm_yday, &wd);
length = sprintf(_store, "%.2u", wd.week);
break;
case ('w'):
length = sprintf(_store, "%u", timeptr->tm_wday);
break;
case ('W'):
w = week_of_year(timeptr, 1);
length = sprintf(_store, "%.2u", w);
break;
case ('x'):
length = sprintf(_store, "%.2u/%.2u/%.2u", timeptr->tm_mon + 1, timeptr->tm_mday, timeptr->tm_year % 100);
break;
case ('X'):
length = sprintf(_store, "%.2u:%.2u:%.2u", timeptr->tm_hour, timeptr->tm_min, timeptr->tm_sec);
break;
case ('y'):
length = sprintf(_store, "%.2u", timeptr->tm_year % 100);
break;
case ('Y'):
length = sprintf(_store, "%u", timeptr->tm_year + 1900);
break;
case ('z'):
d = __utc_offset / 60;
w = timeptr->tm_isdst / 60;
if (w > 0)
d += w;
w = abs(d % 60);
d = d / 60;
length = sprintf(_store, "%+.2d%.2d", d, w);
break;
default:
length = 1;
_store[0] = '?';
_store[1] = 0;
break;
}
if ((length + count) < limit) {
count += length;
for (d = 0; d < (int) length; d++) {
*buffer++ = _store[d];
}
} else {
*buffer = 0;
return count;
}
} else { /* copy a literal */
*buffer = c;
buffer++;
count++;
if (c == 0)
return count;
}
}
*buffer = 0;
return count;
}

View File

@ -0,0 +1,49 @@
/*
* (c)2012 Michael Duane Rice All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution. Neither the name of the copyright holders
* nor the names of contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* $Id$ */
/*
Return the approximate time of sun rise.
*/
#include "time.h"
time_t
sun_rise(const time_t * timer)
{
int32_t n;
time_t t;
/* sunrise is 1/2 'day' before solar noon */
t = solar_noon(timer);
n = daylight_seconds(timer) / 2L;
t -= n;
return t;
}

Some files were not shown because too many files have changed in this diff Show More