first commit

This commit is contained in:
Jérôme Delacotte
2025-03-06 11:15:32 +01:00
commit 7b30d6e298
5276 changed files with 2108927 additions and 0 deletions

168
ARDUCAM_TEST/ARDUCAM_TEST.ino Executable file
View File

@@ -0,0 +1,168 @@
// ArduCAM demo (C)2015 Lee
// web: http://www.ArduCAM.com
// This program is a demo of how to use most of the functions
// of the library with a supported camera modules, and can run on any Arduino platform.
//
// This demo was made for Omnivision OV2640 2MP sensor.
// It will run the ArduCAM Mini 2MP as a real 2MP digital camera, provide both JPEG capture.
// The demo sketch will do the following tasks:
// 1. Set the sensor to JPEG mode.
// 2. Capture and buffer the image to FIFO every 5 seconds
// 3. Store the image to Micro SD/TF card with JPEG format in sequential.
// 4. Resolution can be changed by myCAM.set_JPEG_size() function.
// This program requires the ArduCAM V3.4.0 (or later) library and ArduCAM Mini 2MP shield
// and use Arduino IDE 1.5.2 compiler or above
//#include <UTFT_SPI.h>
#include <SD.h>
#include <Wire.h>
#include <ArduCAM.h>
#include <SPI.h>
#include "memorysaver.h"
#if defined(arm)
#include <itoa.h>
#endif
#define SD_CS 4
// set pin 4 as the slave select for SPI:
const int SPI_CS = 10;
ArduCAM myCAM(OV2640, SPI_CS);
UTFT myGLCD(SPI_CS);
void setup()
{
uint8_t vid, pid;
uint8_t temp;
#if defined(SAM3X8E)
Wire1.begin();
#else
Wire.begin();
#endif
Serial.begin(9600);
Serial.println("ArduCAM Start!");
// set the SPI_CS as an output:
pinMode(SPI_CS, OUTPUT);
// initialize SPI:
SPI.begin();
//Check if the ArduCAM SPI bus is OK
myCAM.write_reg(ARDUCHIP_TEST1, 0x55);
temp = myCAM.read_reg(ARDUCHIP_TEST1);
if (temp != 0x55)
{
Serial.println("SPI interface Error!");
while (1);
}
//Check if the camera module type is OV2640
myCAM.rdSensorReg8_8(OV2640_CHIPID_HIGH, &vid);
myCAM.rdSensorReg8_8(OV2640_CHIPID_LOW, &pid);
if ((vid != 0x26) || (pid != 0x42))
Serial.println("Can't find OV2640 module!");
else
Serial.println("OV2640 detected");
//Change to BMP capture mode and initialize the OV2640 module
myCAM.set_format(JPEG);
myCAM.InitCAM();
//myCAM.OV2640_set_JPEG_size(OV2640_640x480);
//myCAM.OV2640_set_JPEG_size(OV2640_1600x1200);
//Initialize SD Card
if (!SD.begin(SD_CS))
{
//while (1); //If failed, stop here
Serial.println("SD Card Error");
}
else
Serial.println("SD Card detected!");
}
void loop()
{
char str[8];
File outFile;
byte buf[256];
static int i = 0;
static int k = 0;
static int n = 0;
uint8_t temp, temp_last;
uint8_t start_capture = 0;
int total_time = 0;
////////////////////////////////
start_capture = 1;
delay(5000);
if (start_capture)
{
//Flush the FIFO
myCAM.flush_fifo();
//Clear the capture done flag
myCAM.clear_fifo_flag();
//Start capture
myCAM.start_capture();
Serial.println("Start Capture");
}
while (!myCAM.get_bit(ARDUCHIP_TRIG , CAP_DONE_MASK));
Serial.println("Capture Done!");
//Construct a file name
k = k + 1;
itoa(k, str, 10);
strcat(str, ".jpg");
//Open the new file
outFile = SD.open(str, O_WRITE | O_CREAT | O_TRUNC);
if (! outFile)
{
Serial.println("open file failed");
return;
}
total_time = millis();
i = 0;
myCAM.CS_LOW();
myCAM.set_fifo_burst();
temp = SPI.transfer(0x00);
//
//Read JPEG data from FIFO
while ( (temp != 0xD9) | (temp_last != 0xFF))
{
temp_last = temp;
temp = SPI.transfer(0x00);
//Write image data to buffer if not full
if (i < 256)
buf[i++] = temp;
else
{
//Write 256 bytes image data to file
myCAM.CS_HIGH();
outFile.write(buf, 256);
i = 0;
buf[i++] = temp;
myCAM.CS_LOW();
myCAM.set_fifo_burst();
}
}
//Write the remain bytes in the buffer
if (i > 0)
{
myCAM.CS_HIGH();
outFile.write(buf, i);
}
//Close the file
outFile.close();
total_time = millis() - total_time;
Serial.print("Total time used:");
Serial.print(total_time, DEC);
Serial.println(" millisecond");
//Clear the capture done flag
myCAM.clear_fifo_flag();
//Clear the start capture flag
start_capture = 0;
}

11
ATMEGA_433_EMETTEUR/.project Executable file
View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ATMEGA_433_EMETTEUR</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
</projectDescription>

View File

@@ -0,0 +1,84 @@
#include <Narcoleptic.h>
#include <Manchester.h>
#define BLINK_MODE true
#define NODE_ID 1 // On 8bits so 0..255
#define MESSAGE_SIZE 6 // Number of bytes to send
#define SEND_MESSAGE_DELAY 5000 // Delay in ms between each value's extraction
#define SEND_433_COUNT 4 // How many times the message has to be send
#define SEND_433_PAUSE 160 // 16 multiple
// Define connectors used for the node
#define TX_PIN 7
#define LED_PIN 13
//#define DHT11_PIN 2
// Array of bytes to will make the message
// In this node : 2 bytes for voltage, 2 bytes for
uint8_t msgData[MESSAGE_SIZE] = {0, 0, 0, 0, 0, 0};
//--------------------------------------------------------------------------------------------------
// Read current supply voltage
//--------------------------------------------------------------------------------------------------
long readVcc() {
bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
long result;
// Read 1.1V reference against Vcc
#if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
#endif
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate Vcc in mV
ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
return result; // Vcc in millivolts
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
if (BLINK_MODE) digitalWrite(LED_PIN, LOW);
man.setupTransmit(TX_PIN, MAN_1200);
msgData[0] = NODE_ID;
// Wait 1s to allow DHT11 to initialize
Narcoleptic.delay(1000);
}
void loop() {
// Read Vcc value
long currentVcc = readVcc();
Serial.println(currentVcc);
uint16_t uint16_currentVcc = (uint16_t)currentVcc;
// Save millivolts in two bytes to keep high precision. Will be decoded by the gateway
uint8_t byteData[2] = {uint16_currentVcc >> 8, uint16_currentVcc & 0xFF};
msgData[2] = byteData[0];
msgData[3] = byteData[1];
// // Read data from DHT11 sensor
// int chk = DHT.read11(DHT11_PIN);
// // DHT11 values can be put in a byte value due to the low precision
// msgData[4] = (uint8_t)DHT.humidity;
// msgData[5] = (uint8_t)DHT.temperature;
// Send message SEND_433_COUNT times with a delay of SEND_433_PAUSE ms for each
for (int i=0; i<SEND_433_COUNT; i++) {
msgData[1] = i;
if (BLINK_MODE) digitalWrite(LED_PIN, HIGH);
man.transmitArray(MESSAGE_SIZE, msgData);
if (BLINK_MODE) digitalWrite(LED_PIN, LOW);
// Wait between each send
Narcoleptic.delay(SEND_433_PAUSE);
}
// Wait before getting new sensor value
Narcoleptic.delay(SEND_MESSAGE_DELAY);
}

42
ATMEGA_COMPAS/ATMEGA_COMPAS.ino Executable file
View File

@@ -0,0 +1,42 @@
#include <Wire.h>
#define Addr 0x1E // 7-bit address of HMC5883 compass
void setup() {
Serial.begin(9600);
delay(100); // Power up delay
Wire.begin();
// Set operating mode to continuous
Wire.beginTransmission(Addr);
Wire.write(byte(0x02));
Wire.write(byte(0x00));
Wire.endTransmission();
}
void loop() {
int x, y, z;
// Initiate communications with compass
Wire.beginTransmission(Addr);
Wire.write(byte(0x03)); // Send request to X MSB register
Wire.endTransmission();
Wire.requestFrom(Addr, 6); // Request 6 bytes; 2 bytes per axis
if(Wire.available() <=6) { // If 6 bytes available
x = Wire.read() << 8 | Wire.read();
z = Wire.read() << 8 | Wire.read();
y = Wire.read() << 8 | Wire.read();
}
// Print raw values
Serial.print("X=");
Serial.print(x);
Serial.print(", Y=");
Serial.print(y);
Serial.print(", Z=");
Serial.println(z);
delay(500);
}

View File

@@ -0,0 +1,133 @@
#include <Wire.h>
#include <RCSwitch.h>
#include <HMC5883L.h>
HMC5883L compass;
RCSwitch mySwitch = RCSwitch();
#define Addr 0x1E // 7-bit address of HMC5883 compass
const unsigned long activation = 111269; // Radiateur
const unsigned long idRad=5883;
const unsigned long desactivation = 962111; // Fin radiateur
const unsigned int delai = 11;
#define DEBUG
void setup() {
#ifdef DEBUG
Serial.begin(9600);
Serial.println("\nCompas radio");
#endif
pinMode(13, OUTPUT);
mySwitch.enableTransmit(9);
//mySwitch.setRepeatTransmit(3);
delay(100); // Power up delay
// Wire.begin();
//
// // Set operating mode to continuous
// Wire.beginTransmission(Addr);
// Wire.write(byte(0x02));
// Wire.write(byte(0x00));
// Wire.endTransmission();
// Initialize Initialize HMC5883L
while (!compass.begin())
{
delay(3000);
for (int i = 1; i<10; i++) {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(20); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(20);
}
}
// Set measurement range
compass.setRange(HMC5883L_RANGE_1_3GA);
// Set measurement mode
compass.setMeasurementMode(HMC5883L_CONTINOUS);
// Set data rate
compass.setDataRate(HMC5883L_DATARATE_30HZ);
}
void loop() {
int x, y, z;
// // Initiate communications with compass
// Wire.beginTransmission(Addr);
// Wire.write(byte(0x03)); // Send request to X MSB register
// Wire.endTransmission();
//qxc
// Wire.requestFrom(Addr, 6); // Request 6 bytes; 2 bytes per axis
// if(Wire.available() <=6) { // If 6 bytes available
// x = Wire.read() << 8 | Wire.read();
// z = Wire.read() << 8 | Wire.read();
// y = Wire.read() << 8 | Wire.read();
// }
Vector mag = compass.readRaw();
// Ranges
//-539:506 / 1045 / 522.5 / OFF : 16.5
//-645:464 / 1109 / 554.5 / OFF : -90.5
//-470:499 / 969 / 484.5 / OFF : 14.5
x = ((mag.XAxis + 16.5) + 522.5) / 10.45;
y = ((mag.YAxis -90.5) + 554.5) / 11.09;
z = ((mag.ZAxis +14.5) + 484.5) / 9.69;
#ifdef DEBUG
// Print raw values
Serial.print("X=");
Serial.print(x);
Serial.print(", Y=");
Serial.print(y);
Serial.print(", Z=");
Serial.println(z);
#endif
// Serial.println(z);
// mySwitch.send(activation, 24);
//delay(delai); //delayMicroseconds
myMessageSend(idRad,1000 + x);
myMessageSend(idRad,2000 + y);
myMessageSend(idRad,3000 + z);
//mySwitch.send(desactivation, 24);
//delay(delai);
// digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
// delay(100); // wait for a second
// digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(10); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(10);
//delay(1000);
}
void myMessageSend(long id, long value) {
#ifdef DEBUG
Serial.print("Send id="); Serial.print(id);
Serial.print(" value="); Serial.println(value);
#endif
// mySwitch.send(id, 24); //"000000000001010100010001");
//delay(delai);
mySwitch.send(value, 24); //"000000000001010100010001");
delay(delai);
//delay(5000);
//delayMicroseconds(TWOTIME*8);
}

View File

@@ -0,0 +1,59 @@
#include <Wire.h>
#define Addr 0x1E // 7-bit address of HMC5883 compass
// Assign LED Output PWM Pins
int Red = 11;
int Green = 10;
int Blue = 9;
void setup() {
// LED
pinMode(Red, OUTPUT);
pinMode(Green, OUTPUT);
pinMode(Blue, OUTPUT);
Serial.begin(9600);
delay(100); // Power up delay
Wire.begin();
// Set operating mode to continuous
Wire.beginTransmission(Addr);
Wire.write(byte(0x02));
Wire.write(byte(0x00));
Wire.endTransmission();
}
void loop() {
int x, y, z;
// Initiate communications with compass
Wire.beginTransmission(Addr);
Wire.write(byte(0x03)); // Send request to X MSB register
Wire.endTransmission();
Wire.requestFrom(Addr, 6); // Request 6 bytes; 2 bytes per axis
if(Wire.available() <=6) { // If 6 bytes available
x = Wire.read() << 8 | Wire.read();
z = Wire.read() << 8 | Wire.read();
y = Wire.read() << 8 | Wire.read();
}
// Print raw values
Serial.print("X="); Serial.print(x);
//Serial.print(min(255, 255.0 * (512 + x) / 1024.0));
Serial.print(", Y="); Serial.print(y);
//Serial.print(min(255, 255.0 * (512 + y) / 1024.0));
Serial.print(", Z="); Serial.println(z);
//Serial.println(min(255, 255.0 * (512 + z) / 1024.0));
analogWrite(Red, min(255, 255.0 * (512 + x) / 1024.0));
analogWrite(Green, min(255, 255.0 * (512 + y) / 1024.0));
analogWrite(Blue, min(255, 255.0 * (512 + z) / 1024.0));
delay(100);
//delay(500);
}

View File

@@ -0,0 +1,32 @@
#include <Wire.h>
#include <HMC5883L.h>
HMC5883L compass;
void setup()
{
Wire.begin();
Serial.begin(9600);
compass = HMC5883L();
Serial.println("Setting scale to +/- 1.3Ga");
int error = compass.SetScale(1.3);
if(error != 0)
Serial.println(compass.GetErrorText(error));
Serial.println("Setting measurement mode to continuous");
error = compass.SetMeasurementMode(Measurement_Continuous);
if(error != 0)
Serial.println(compass.GetErrorText(error));
}
void loop()
{
MagnetometerRaw raw = compass.ReadRawAxis();
float heading = atan2(raw.YAxis, raw.XAxis);
if(heading < 0)
heading += 2*PI;
float headingDegrees = heading * 180/M_PI;
Serial.println(headingDegrees);
delay(1000);
}

View File

@@ -0,0 +1,345 @@
/*
7-17-2011
Spark Fun Electronics 2011
Nathan Seidle
This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license).
This code writes a series of images and text to the Nokia 5110 84x48 graphic LCD:
http://www.sparkfun.com/products/10168
Do not drive the backlight with 5V. It will smoke. However, the backlight on the LCD seems to be
happy with direct drive from the 3.3V regulator.
Although the PCD8544 controller datasheet recommends 3.3V, the graphic Nokia 5110 LCD can run at 3.3V or 5V.
No resistors needed on the signal lines.
You will need 5 signal lines to connect to the LCD, 3.3 or 5V for power, 3.3V for LED backlight, and 1 for ground.0
NE SEMBLE PAS FONCTIONNER !!!!!!!!!!!
NE SEMBLE PAS FONCTIONNER !!!!!!!!!!!
NE SEMBLE PAS FONCTIONNER !!!!!!!!!!!
NE SEMBLE PAS FONCTIONNER !!!!!!!!!!!
NE SEMBLE PAS FONCTIONNER !!!!!!!!!!!
NE SEMBLE PAS FONCTIONNER !!!!!!!!!!!
NE SEMBLE PAS FONCTIONNER !!!!!!!!!!!
*/
#define PIN_SCE 7 //Pin 3 on LCD
#define PIN_RESET 6 //Pin 4 on LCD
#define PIN_DC 5 //Pin 5 on LCD
#define PIN_SDIN 4 //Pin 6 on LCD
#define PIN_SCLK 3 //Pin 7 on LCD
//The DC pin tells the LCD if we are sending a command or data
#define LCD_COMMAND 0
#define LCD_DATA 1
//You may find a different size screen, but this one is 84 by 48 pixels
#define LCD_X 84
#define LCD_Y 48
//This table contains the hex values that represent pixels
//for a font that is 5 pixels wide and 8 pixels high
static const byte ASCII[][5] = {
{0x00, 0x00, 0x00, 0x00, 0x00} // 20
,{0x00, 0x00, 0x5f, 0x00, 0x00} // 21 !
,{0x00, 0x07, 0x00, 0x07, 0x00} // 22 "
,{0x14, 0x7f, 0x14, 0x7f, 0x14} // 23 #
,{0x24, 0x2a, 0x7f, 0x2a, 0x12} // 24 $
,{0x23, 0x13, 0x08, 0x64, 0x62} // 25 %
,{0x36, 0x49, 0x55, 0x22, 0x50} // 26 &
,{0x00, 0x05, 0x03, 0x00, 0x00} // 27 '
,{0x00, 0x1c, 0x22, 0x41, 0x00} // 28 (
,{0x00, 0x41, 0x22, 0x1c, 0x00} // 29 )
,{0x14, 0x08, 0x3e, 0x08, 0x14} // 2a *
,{0x08, 0x08, 0x3e, 0x08, 0x08} // 2b +
,{0x00, 0x50, 0x30, 0x00, 0x00} // 2c ,
,{0x08, 0x08, 0x08, 0x08, 0x08} // 2d -
,{0x00, 0x60, 0x60, 0x00, 0x00} // 2e .
,{0x20, 0x10, 0x08, 0x04, 0x02} // 2f /
,{0x3e, 0x51, 0x49, 0x45, 0x3e} // 30 0
,{0x00, 0x42, 0x7f, 0x40, 0x00} // 31 1
,{0x42, 0x61, 0x51, 0x49, 0x46} // 32 2
,{0x21, 0x41, 0x45, 0x4b, 0x31} // 33 3
,{0x18, 0x14, 0x12, 0x7f, 0x10} // 34 4
,{0x27, 0x45, 0x45, 0x45, 0x39} // 35 5
,{0x3c, 0x4a, 0x49, 0x49, 0x30} // 36 6
,{0x01, 0x71, 0x09, 0x05, 0x03} // 37 7
,{0x36, 0x49, 0x49, 0x49, 0x36} // 38 8
,{0x06, 0x49, 0x49, 0x29, 0x1e} // 39 9
,{0x00, 0x36, 0x36, 0x00, 0x00} // 3a :
,{0x00, 0x56, 0x36, 0x00, 0x00} // 3b ;
,{0x08, 0x14, 0x22, 0x41, 0x00} // 3c <
,{0x14, 0x14, 0x14, 0x14, 0x14} // 3d =
,{0x00, 0x41, 0x22, 0x14, 0x08} // 3e >
,{0x02, 0x01, 0x51, 0x09, 0x06} // 3f ?
,{0x32, 0x49, 0x79, 0x41, 0x3e} // 40 @
,{0x7e, 0x11, 0x11, 0x11, 0x7e} // 41 A
,{0x7f, 0x49, 0x49, 0x49, 0x36} // 42 B
,{0x3e, 0x41, 0x41, 0x41, 0x22} // 43 C
,{0x7f, 0x41, 0x41, 0x22, 0x1c} // 44 D
,{0x7f, 0x49, 0x49, 0x49, 0x41} // 45 E
,{0x7f, 0x09, 0x09, 0x09, 0x01} // 46 F
,{0x3e, 0x41, 0x49, 0x49, 0x7a} // 47 G
,{0x7f, 0x08, 0x08, 0x08, 0x7f} // 48 H
,{0x00, 0x41, 0x7f, 0x41, 0x00} // 49 I
,{0x20, 0x40, 0x41, 0x3f, 0x01} // 4a J
,{0x7f, 0x08, 0x14, 0x22, 0x41} // 4b K
,{0x7f, 0x40, 0x40, 0x40, 0x40} // 4c L
,{0x7f, 0x02, 0x0c, 0x02, 0x7f} // 4d M
,{0x7f, 0x04, 0x08, 0x10, 0x7f} // 4e N
,{0x3e, 0x41, 0x41, 0x41, 0x3e} // 4f O
,{0x7f, 0x09, 0x09, 0x09, 0x06} // 50 P
,{0x3e, 0x41, 0x51, 0x21, 0x5e} // 51 Q
,{0x7f, 0x09, 0x19, 0x29, 0x46} // 52 R
,{0x46, 0x49, 0x49, 0x49, 0x31} // 53 S
,{0x01, 0x01, 0x7f, 0x01, 0x01} // 54 T
,{0x3f, 0x40, 0x40, 0x40, 0x3f} // 55 U
,{0x1f, 0x20, 0x40, 0x20, 0x1f} // 56 V
,{0x3f, 0x40, 0x38, 0x40, 0x3f} // 57 W
,{0x63, 0x14, 0x08, 0x14, 0x63} // 58 X
,{0x07, 0x08, 0x70, 0x08, 0x07} // 59 Y
,{0x61, 0x51, 0x49, 0x45, 0x43} // 5a Z
,{0x00, 0x7f, 0x41, 0x41, 0x00} // 5b [
,{0x02, 0x04, 0x08, 0x10, 0x20} // 5c \
,{0x00, 0x41, 0x41, 0x7f, 0x00} // 5d ]
,{0x04, 0x02, 0x01, 0x02, 0x04} // 5e ^
,{0x40, 0x40, 0x40, 0x40, 0x40} // 5f _
,{0x00, 0x01, 0x02, 0x04, 0x00} // 60 `
,{0x20, 0x54, 0x54, 0x54, 0x78} // 61 a
,{0x7f, 0x48, 0x44, 0x44, 0x38} // 62 b
,{0x38, 0x44, 0x44, 0x44, 0x20} // 63 c
,{0x38, 0x44, 0x44, 0x48, 0x7f} // 64 d
,{0x38, 0x54, 0x54, 0x54, 0x18} // 65 e
,{0x08, 0x7e, 0x09, 0x01, 0x02} // 66 f
,{0x0c, 0x52, 0x52, 0x52, 0x3e} // 67 g
,{0x7f, 0x08, 0x04, 0x04, 0x78} // 68 h
,{0x00, 0x44, 0x7d, 0x40, 0x00} // 69 i
,{0x20, 0x40, 0x44, 0x3d, 0x00} // 6a j
,{0x7f, 0x10, 0x28, 0x44, 0x00} // 6b k
,{0x00, 0x41, 0x7f, 0x40, 0x00} // 6c l
,{0x7c, 0x04, 0x18, 0x04, 0x78} // 6d m
,{0x7c, 0x08, 0x04, 0x04, 0x78} // 6e n
,{0x38, 0x44, 0x44, 0x44, 0x38} // 6f o
,{0x7c, 0x14, 0x14, 0x14, 0x08} // 70 p
,{0x08, 0x14, 0x14, 0x18, 0x7c} // 71 q
,{0x7c, 0x08, 0x04, 0x04, 0x08} // 72 r
,{0x48, 0x54, 0x54, 0x54, 0x20} // 73 s
,{0x04, 0x3f, 0x44, 0x40, 0x20} // 74 t
,{0x3c, 0x40, 0x40, 0x20, 0x7c} // 75 u
,{0x1c, 0x20, 0x40, 0x20, 0x1c} // 76 v
,{0x3c, 0x40, 0x30, 0x40, 0x3c} // 77 w
,{0x44, 0x28, 0x10, 0x28, 0x44} // 78 x
,{0x0c, 0x50, 0x50, 0x50, 0x3c} // 79 y
,{0x44, 0x64, 0x54, 0x4c, 0x44} // 7a z
,{0x00, 0x08, 0x36, 0x41, 0x00} // 7b {
,{0x00, 0x00, 0x7f, 0x00, 0x00} // 7c |
,{0x00, 0x41, 0x36, 0x08, 0x00} // 7d }
,{0x10, 0x08, 0x08, 0x10, 0x08} // 7e ~
,{0x78, 0x46, 0x41, 0x46, 0x78} // 7f DEL
};
//This is the SFE flame in bit form
char SFEFlame[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xE0, 0xF0, 0xF8, 0xFC, 0xFC, 0xFE, 0xFE, 0xFE, 0xFE, 0x1E, 0x0E, 0x02, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFE, 0xFC, 0xF8, 0xF8, 0xF0, 0xF8, 0xFE, 0xFE, 0xFC, 0xF8, 0xE0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xF8, 0xFC, 0xFE, 0xFE, 0xFF, 0xFF, 0xF3, 0xE0, 0xE0, 0xC0, 0xC0, 0xC0, 0xE0, 0xE0,
0xF1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F,
0x3F, 0x1F, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0x7F, 0x3F, 0x1F, 0x0F, 0x0F, 0x0F, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x03, 0x03,
0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x1F,
0x0F, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
//Another SparkFun logo
char SFEFlameBubble [] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
0xC0, 0xC0, 0xE0, 0xE0, 0xF0, 0xF8, 0xF8, 0xFC, 0xFC, 0xFC, 0xFC, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE,
0xFE, 0xFE, 0xFE, 0xFE, 0xFC, 0xFC, 0xFC, 0xFC, 0xFC, 0xF8, 0xF0, 0xE0, 0xE0, 0xC0, 0xC0, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xE0,
0xF8, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x3F, 0x3F, 0x3F,
0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x3F, 0x3F, 0x3F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0xF8, 0xE0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xC0, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0x0F, 0x3F, 0x7F, 0x7F, 0x3F, 0x1E,
0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x03, 0x0F, 0x3F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x3F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0xF0, 0xE0,
0xE0, 0xC0, 0xC0, 0xE0, 0xE0, 0xE0, 0xF0, 0xF8, 0x7C, 0x7C, 0x7E, 0x7C, 0x38, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x1F, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xF8, 0xE0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x0F, 0x3F, 0x7F, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF8, 0xF0, 0xF0,
0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0,
0xE1, 0xE3, 0xE3, 0xE7, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFC, 0xF8, 0xF0, 0xE0,
0xC0, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x07, 0x0F, 0x1F, 0x1F, 0x1F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F,
0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7E, 0x7C, 0x78, 0x70, 0x60, 0x40, 0x40, 0x00,
0x00,
};
//This is awesome in bitmap form
char awesome[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0x70, 0x30, 0x18, 0x1C,
0x0C, 0x0C, 0x06, 0x06, 0x07, 0x07, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x07,
0x07, 0x07, 0x0E, 0x06, 0x1C, 0x1C, 0x38, 0x70, 0x70, 0xE0, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xF0, 0x3C, 0xCE, 0x67, 0x33, 0x18, 0x08,
0x08, 0xC8, 0xF8, 0xF0, 0xE0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0,
0x70, 0x38, 0x18, 0x18, 0x08, 0x08, 0x08, 0xF8, 0xF0, 0xF0, 0xE0, 0xC0, 0x00, 0x00, 0x01, 0x07,
0x0F, 0x3C, 0xF8, 0xE0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0x0F, 0x00, 0x0C, 0x7F,
0x60, 0x60, 0x60, 0x60, 0x60, 0x61, 0x61, 0x61, 0x61, 0x61, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x7F, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x61, 0x61, 0x61, 0x61, 0x63,
0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xFF, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xFF,
0xF0, 0x00, 0x00, 0x00, 0x08, 0x08, 0xFC, 0x8C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
0x0C, 0x0C, 0x0C, 0xF8, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0x1F, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x07, 0x0F, 0x3C, 0x70, 0xE0, 0x80, 0x00, 0x07, 0x0C, 0x38, 0x60, 0xC0,
0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF0, 0xF0, 0xF8, 0xF8, 0xF8, 0xF8, 0xF0,
0xF0, 0xE0, 0xC0, 0x80, 0xC0, 0x30, 0x18, 0x0F, 0x00, 0x00, 0x80, 0xC0, 0x70, 0x3C, 0x1F, 0x07,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x06,
0x0E, 0x1C, 0x18, 0x38, 0x31, 0x73, 0x62, 0x66, 0x64, 0xC7, 0xCF, 0xCF, 0xCF, 0xCF, 0xCF, 0xCF,
0xC7, 0xC7, 0xC7, 0x67, 0x63, 0x63, 0x71, 0x30, 0x38, 0x18, 0x1C, 0x0C, 0x06, 0x03, 0x03, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
void setup(void) {
LCDInit(); //Init the LCD
}
void loop(void) {
LCDClear();
LCDBitmap(SFEFlame);
delay(1000);
LCDClear();
LCDBitmap(SFEFlameBubble);
delay(1000);
LCDClear();
LCDBitmap(awesome);
delay(1000);
LCDClear();
LCDString("nick powley");
delay(1000);
}
void gotoXY(int x, int y) {
LCDWrite(0, 0x80 | x); // Column.
LCDWrite(0, 0x40 | y); // Row. ?
}
//This takes a large array of bits and sends them to the LCD
void LCDBitmap(char my_array[]){
for (int index = 0 ; index < (LCD_X * LCD_Y / 8) ; index++)
LCDWrite(LCD_DATA, my_array[index]);
}
//This function takes in a character, looks it up in the font table/array
//And writes it to the screen
//Each character is 8 bits tall and 5 bits wide. We pad one blank column of
//pixels on each side of the character for readability.
void LCDCharacter(char character) {
LCDWrite(LCD_DATA, 0x00); //Blank vertical line padding
for (int index = 0 ; index < 5 ; index++)
LCDWrite(LCD_DATA, ASCII[character - 0x21][index]);//NOTE THIS WAS CHANGED FROM 0x20 to 0x21
//0x20 is the ASCII character for Space (' '). The font table starts with this character
LCDWrite(LCD_DATA, 0x00); //Blank vertical line padding
}
//Given a string of characters, one by one is passed to the LCD
void LCDString(char *characters) {
while (*characters)
LCDCharacter(*characters++);
}
//Clears the LCD by writing zeros to the entire screen
void LCDClear(void) {
for (int index = 0 ; index < (LCD_X * LCD_Y / 8) ; index++)
LCDWrite(LCD_DATA, 0x00);
gotoXY(0, 0); //After we clear the display, return to the home position
}
//This sends the magical commands to the PCD8544
void LCDInit(void) {
//Configure control pins
pinMode(PIN_SCE, OUTPUT);
pinMode(PIN_RESET, OUTPUT);
pinMode(PIN_DC, OUTPUT);
pinMode(PIN_SDIN, OUTPUT);
pinMode(PIN_SCLK, OUTPUT);
//Reset the LCD to a known state
digitalWrite(PIN_RESET, LOW);
digitalWrite(PIN_RESET, HIGH);
LCDWrite(LCD_COMMAND, 0x21); //Tell LCD that extended commands follow
LCDWrite(LCD_COMMAND, 0xBF); //Set LCD Vop (Contrast): Try 0xB1(good @ 3.3V) or 0xBF if your display is too dark
LCDWrite(LCD_COMMAND, 0x04); //Set Temp coefficent
LCDWrite(LCD_COMMAND, 0x14); //LCD bias mode 1:48: Try 0x13 or 0x14
LCDWrite(LCD_COMMAND, 0x20); //We must send 0x20 before modifying the display control mode
LCDWrite(LCD_COMMAND, 0x0C); //Set display control, 0x0C normal mode. 0x0D for inverse
}
//There are two memory banks in the LCD, data/RAM and commands. This
//function sets the DC pin high or low depending, and then sends
//the data byte
void LCDWrite(byte data_or_command, byte data) {
digitalWrite(PIN_DC, data_or_command); //Tell the LCD that we are writing either to data or a command
//Send the data
digitalWrite(PIN_SCE, LOW);
shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
digitalWrite(PIN_SCE, HIGH);
}

View File

@@ -0,0 +1,249 @@
#include <Adafruit_BMP085.h>
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
// ECRAN LCD
#include <SPI.h> // We'll use SPI to transfer data. Faster!
#define PIN_RESET 3
#define PIN_SCE 4
#define PIN_DC 5
#define PIN_SDIN 6
#define PIN_SCLK 7
#define PIN_LCD 9 // backlight
#define PIN_FADER 1 // analog
#define PIN_TMP 0 // analog
#define LCD_C LOW
#define LCD_D HIGH
#define LCD_COMMAND 0
#define LCD_X 84
#define LCD_Y 48
long contrast = 200;
char strBuffer[255];
int line = 0;
static const byte ASCII[][5] =
{
{0x00, 0x00, 0x00, 0x00, 0x00} // 20
,{0x00, 0x00, 0x5f, 0x00, 0x00} // 21 !
,{0x00, 0x07, 0x00, 0x07, 0x00} // 22 "
,{0x14, 0x7f, 0x14, 0x7f, 0x14} // 23 #
,{0x24, 0x2a, 0x7f, 0x2a, 0x12} // 24 $
,{0x23, 0x13, 0x08, 0x64, 0x62} // 25 %
,{0x36, 0x49, 0x55, 0x22, 0x50} // 26 &
,{0x00, 0x05, 0x03, 0x00, 0x00} // 27 '
,{0x00, 0x1c, 0x22, 0x41, 0x00} // 28 (
,{0x00, 0x41, 0x22, 0x1c, 0x00} // 29 )
,{0x14, 0x08, 0x3e, 0x08, 0x14} // 2a *
,{0x08, 0x08, 0x3e, 0x08, 0x08} // 2b +
,{0x00, 0x50, 0x30, 0x00, 0x00} // 2c ,
,{0x08, 0x08, 0x08, 0x08, 0x08} // 2d -
,{0x00, 0x60, 0x60, 0x00, 0x00} // 2e .
,{0x20, 0x10, 0x08, 0x04, 0x02} // 2f backslash
,{0x3e, 0x51, 0x49, 0x45, 0x3e} // 30 0
,{0x00, 0x42, 0x7f, 0x40, 0x00} // 31 1
,{0x42, 0x61, 0x51, 0x49, 0x46} // 32 2
,{0x21, 0x41, 0x45, 0x4b, 0x31} // 33 3
,{0x18, 0x14, 0x12, 0x7f, 0x10} // 34 4
,{0x27, 0x45, 0x45, 0x45, 0x39} // 35 5
,{0x3c, 0x4a, 0x49, 0x49, 0x30} // 36 6
,{0x01, 0x71, 0x09, 0x05, 0x03} // 37 7
,{0x36, 0x49, 0x49, 0x49, 0x36} // 38 8
,{0x06, 0x49, 0x49, 0x29, 0x1e} // 39 9
,{0x00, 0x36, 0x36, 0x00, 0x00} // 3a :
,{0x00, 0x56, 0x36, 0x00, 0x00} // 3b ;
,{0x08, 0x14, 0x22, 0x41, 0x00} // 3c <
,{0x14, 0x14, 0x14, 0x14, 0x14} // 3d =
,{0x00, 0x41, 0x22, 0x14, 0x08} // 3e >
,{0x02, 0x01, 0x51, 0x09, 0x06} // 3f ?
,{0x32, 0x49, 0x79, 0x41, 0x3e} // 40 @
,{0x7e, 0x11, 0x11, 0x11, 0x7e} // 41 A
,{0x7f, 0x49, 0x49, 0x49, 0x36} // 42 B
,{0x3e, 0x41, 0x41, 0x41, 0x22} // 43 C
,{0x7f, 0x41, 0x41, 0x22, 0x1c} // 44 D
,{0x7f, 0x49, 0x49, 0x49, 0x41} // 45 E
,{0x7f, 0x09, 0x09, 0x09, 0x01} // 46 F
,{0x3e, 0x41, 0x49, 0x49, 0x7a} // 47 G
,{0x7f, 0x08, 0x08, 0x08, 0x7f} // 48 H
,{0x00, 0x41, 0x7f, 0x41, 0x00} // 49 I
,{0x20, 0x40, 0x41, 0x3f, 0x01} // 4a J
,{0x7f, 0x08, 0x14, 0x22, 0x41} // 4b K
,{0x7f, 0x40, 0x40, 0x40, 0x40} // 4c L
,{0x7f, 0x02, 0x0c, 0x02, 0x7f} // 4d M
,{0x7f, 0x04, 0x08, 0x10, 0x7f} // 4e N
,{0x3e, 0x41, 0x41, 0x41, 0x3e} // 4f O
,{0x7f, 0x09, 0x09, 0x09, 0x06} // 50 P
,{0x3e, 0x41, 0x51, 0x21, 0x5e} // 51 Q
,{0x7f, 0x09, 0x19, 0x29, 0x46} // 52 R
,{0x46, 0x49, 0x49, 0x49, 0x31} // 53 S
,{0x01, 0x01, 0x7f, 0x01, 0x01} // 54 T
,{0x3f, 0x40, 0x40, 0x40, 0x3f} // 55 U
,{0x1f, 0x20, 0x40, 0x20, 0x1f} // 56 V
,{0x3f, 0x40, 0x38, 0x40, 0x3f} // 57 W
,{0x63, 0x14, 0x08, 0x14, 0x63} // 58 X
,{0x07, 0x08, 0x70, 0x08, 0x07} // 59 Y
,{0x61, 0x51, 0x49, 0x45, 0x43} // 5a Z
,{0x00, 0x7f, 0x41, 0x41, 0x00} // 5b [
,{0x02, 0x04, 0x08, 0x10, 0x20} // 5c ¥
,{0x00, 0x41, 0x41, 0x7f, 0x00} // 5d ]
,{0x04, 0x02, 0x01, 0x02, 0x04} // 5e ^
,{0x40, 0x40, 0x40, 0x40, 0x40} // 5f _
,{0x00, 0x01, 0x02, 0x04, 0x00} // 60 `
,{0x20, 0x54, 0x54, 0x54, 0x78} // 61 a
,{0x7f, 0x48, 0x44, 0x44, 0x38} // 62 b
,{0x38, 0x44, 0x44, 0x44, 0x20} // 63 c
,{0x38, 0x44, 0x44, 0x48, 0x7f} // 64 d
,{0x38, 0x54, 0x54, 0x54, 0x18} // 65 e
,{0x08, 0x7e, 0x09, 0x01, 0x02} // 66 f
,{0x0c, 0x52, 0x52, 0x52, 0x3e} // 67 g
,{0x7f, 0x08, 0x04, 0x04, 0x78} // 68 h
,{0x00, 0x44, 0x7d, 0x40, 0x00} // 69 i
,{0x20, 0x40, 0x44, 0x3d, 0x00} // 6a j
,{0x7f, 0x10, 0x28, 0x44, 0x00} // 6b k
,{0x00, 0x41, 0x7f, 0x40, 0x00} // 6c l
,{0x7c, 0x04, 0x18, 0x04, 0x78} // 6d m
,{0x7c, 0x08, 0x04, 0x04, 0x78} // 6e n
,{0x38, 0x44, 0x44, 0x44, 0x38} // 6f o
,{0x7c, 0x14, 0x14, 0x14, 0x08} // 70 p
,{0x08, 0x14, 0x14, 0x18, 0x7c} // 71 q
,{0x7c, 0x08, 0x04, 0x04, 0x08} // 72 r
,{0x48, 0x54, 0x54, 0x54, 0x20} // 73 s
,{0x04, 0x3f, 0x44, 0x40, 0x20} // 74 t
,{0x3c, 0x40, 0x40, 0x20, 0x7c} // 75 u
,{0x1c, 0x20, 0x40, 0x20, 0x1c} // 76 v
,{0x3c, 0x40, 0x30, 0x40, 0x3c} // 77 w
,{0x44, 0x28, 0x10, 0x28, 0x44} // 78 x
,{0x0c, 0x50, 0x50, 0x50, 0x3c} // 79 y
,{0x44, 0x64, 0x54, 0x4c, 0x44} // 7a z
,{0x00, 0x08, 0x36, 0x41, 0x00} // 7b {
,{0x00, 0x00, 0x7f, 0x00, 0x00} // 7c |
,{0x00, 0x41, 0x36, 0x08, 0x00} // 7d }
,{0x10, 0x08, 0x08, 0x10, 0x08} // 7e ←
,{0x78, 0x46, 0x41, 0x46, 0x78} // 7f →
};
// FIN ECRAN
void setup() {
Serial.begin(9600);
Serial.println("Ecoute Serial");
// ECRAN
LcdInitialise();
LcdClear();
LcdString("Starting");
setContrast(contrast);
// FIN ECRAN
pinMode(13, OUTPUT);
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
mySerial.println("Hello, world?");
}
void loop() {
// ECRAN
if (mySerial.available()) {
if (line > 5) {
LcdClear();
line = 0;
}
// Serial.write(mySerial.read());
gotoXY(0,5 * line);
int i = 0;
while (mySerial.available()) {
strBuffer[i] = mySerial.read();
i++;
}
LcdString(strBuffer);
line++;
}
// if (Serial.available()) {
// mySerial.write(Serial.read());
// gotoXY(0,20);
// //LcdString(Serial.read());
// }
}
// ECRAN Methodes
void LcdCharacter(char character)
{
LcdWrite(LCD_D, 0x00);
for (int index = 0; index < 5; index++)
{
LcdWrite(LCD_D, ASCII[character - 0x20][index]);
}
LcdWrite(LCD_D, 0x00);
}
void LcdClear(void)
{
for (int index = 0; index < LCD_X * LCD_Y / 8; index++)
{
LcdWrite(LCD_D, 0x00);
}
}
void LcdInitialise(void)
{
pinMode(PIN_SCE, OUTPUT);
pinMode(PIN_RESET, OUTPUT);
pinMode(PIN_DC, OUTPUT);
pinMode(PIN_SDIN, OUTPUT);
pinMode(PIN_SCLK, OUTPUT);
pinMode(PIN_LCD, OUTPUT);
digitalWrite(PIN_LCD, HIGH);
digitalWrite(PIN_RESET, LOW);
digitalWrite(PIN_RESET, HIGH);
LcdWrite(LCD_C, 0x21 ); // LCD Extended Commands.
LcdWrite(LCD_C, 0xB1 ); // Set LCD Vop (Contrast).
LcdWrite(LCD_C, 0x04 ); // Set Temp coefficent. //0x04
LcdWrite(LCD_C, 0x14 ); // LCD bias mode 1:48. //0x13
LcdWrite(LCD_C, 0x0C ); // LCD in normal mode.
LcdWrite(LCD_C, 0x20 );
LcdWrite(LCD_C, 0x0C );
}
void LcdString(char *characters)
{
while (*characters)
{
LcdCharacter(*characters++);
}
}
void LcdWrite(byte dc, byte data)
{
digitalWrite(PIN_DC, dc);
digitalWrite(PIN_SCE, LOW);
shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
digitalWrite(PIN_SCE, HIGH);
}
void setContrast(byte contrast)
{
analogWrite(PIN_LCD, contrast);
}
void gotoXY(int x, int y)
{
LcdWrite( 0, 0x80 | x); // Column.
LcdWrite( 0, 0x40 | y); // Row.
}

44
ATMEGA_EEPROM/ATMEGA_EEPROM.ino Executable file
View File

@@ -0,0 +1,44 @@
#include <Wire.h>
#define eeprom 0x50 //defines the base address of the EEPROM
void setup(void){
Wire.begin(); //creates a Wire object
Serial.begin(9600);
unsigned int address = 0; //first address of the EEPROM
Serial.println("We write the zip code 22222, a zip code in Arlington, Virginia!");
for(address = 0; address< 5; address++)
writeEEPROM(eeprom, address, '2'); // Writes 22222 to the EEPROM
for(address = 0; address< 5; address++) {
Serial.print(readEEPROM(eeprom, address), HEX);
}
}
void loop(){
//there's nothing in the loop() function because we don't want the arduino to repeatedly write the same thing to the EEPROM over and over. We just want a one-time write, so the loop() function is avoided with EEPROMs.
}
//defines the writeEEPROM function
void writeEEPROM(int deviceaddress, unsigned int eeaddress, byte data ) {
Wire.beginTransmission(deviceaddress);
Wire.write((int)(eeaddress >> 8)); //writes the MSB
Wire.write((int)(eeaddress & 0xFF)); //writes the LSB
Wire.write(data);
Wire.endTransmission();
}
//defines the readEEPROM function
byte readEEPROM(int deviceaddress, unsigned int eeaddress ) {
byte rdata = 0xFF;
Wire.beginTransmission(deviceaddress);
Wire.write((int)(eeaddress >> 8)); //writes the MSB
Wire.write((int)(eeaddress & 0xFF)); //writes the LSB
Wire.endTransmission();
Wire.requestFrom(deviceaddress,1);
if (Wire.available())
rdata = Wire.read();
return rdata;
}

View File

@@ -0,0 +1,176 @@
/*
* EEPROM Write
*
* Stores values read from analog input 0 into the EEPROM.
* These values will stay in the EEPROM when the board is
* turned off and may be retrieved later by another sketch.
*/
#include <EEPROM.h>
#include <Wire.h>
#define Addr 0x1E // 7-bit address of HMC5883 compass
// the current address in the EEPROM (i.e. which byte
// we're going to write to next)
int addr = 0;
#define trigPin 7
#define echoPin 6
float distance = 0;
// Assign LED Output PWM Pins
int Red = 11;
int Green = 10;
int Blue = 9;
void setup(){
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
for (int i = 0; i < 512; i++) {
Serial.print(i);
Serial.print("\t");
Serial.print(i, DEC);
Serial.println();
EEPROM.write(i, 100);
}
Wire.begin();
// Set operating mode to continuous
Wire.beginTransmission(Addr);
Wire.write(byte(0x02));
Wire.write(byte(0x00));
Wire.endTransmission();
for (int i = 0; i < 512; i++) {
byte value = EEPROM.read(i);
Serial.print(i);
Serial.print("\t");
Serial.print(value, DEC);
Serial.println();
}
}
void loop()
{
// // need to divide by 4 because analog inputs range from
// // 0 to 1023 and each byte of the EEPROM can only hold a
// // value from 0 to 255.
// int val = analogRead(0) / 4;
//
//
//
// // write the value to the appropriate byte of the EEPROM.
// // these values will remain there when the board is
// // turned off.
// EEPROM.write(addr, val);
//
// // advance to the next address. there are 512 bytes in
// // the EEPROM, so go back to 0 when we hit 512.
// addr = addr + 1;
// if (addr == 512)
// addr = 0;
//
// delay(100);
// long duration, distance;
// digitalWrite(trigPin, LOW);
// delayMicroseconds(2);
// digitalWrite(trigPin, HIGH);
// delayMicroseconds(10);
// digitalWrite(trigPin, LOW);
// duration = pulseIn(echoPin, HIGH);
// distance = (duration/2) / 29.1;
readCompass();
readPresence();
readSerial();
if (distance > 0) {
Serial.print(distance);
Serial.println(" cm");
if (distance < 100) {
//analogWrite(3, 255 - distance * 2.5);
}
} else {
// analogWrite(3, 0);
}
delay(100);
}
void readPresence() {
digitalWrite(trigPin, LOW); //Low high and low level take a short time to trigPin pulse
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
float cm = pulseIn(echoPin, HIGH) / 58.0; //Echo time conversion into cm
// cm = (int(cm * 100.0)) / 100.0; //Keep two decimal places
//distance = cm * 100;
distance = cm;
}
void readSerial() {
// First we check to see if incoming data is available:
while (Serial.available() > 0)
{
// If it is, we'll use parseInt() to pull out any numbers:
int speed = Serial.parseInt();
// Because analogWrite() only works with numbers from
// 0 to 255, we'll be sure the input is in that range:
speed = constrain(speed, 0, 255);
// We'll print out a message to let you know that the
// number was received:
Serial.print("Setting speed to ");
Serial.println(speed);
// And finally, we'll set the speed of the motor!
analogWrite(3, speed);
}
}
void readCompass() {
int x, y, z;
// Initiate communications with compass
Wire.beginTransmission(Addr);
Wire.write(byte(0x03)); // Send request to X MSB register
Wire.endTransmission();
Wire.requestFrom(Addr, 6); // Request 6 bytes; 2 bytes per axis
if(Wire.available() <=6) { // If 6 bytes available
x = Wire.read() << 8 | Wire.read();
z = Wire.read() << 8 | Wire.read();
y = Wire.read() << 8 | Wire.read();
}
// Print raw values
Serial.print("X="); Serial.print(x);
//Serial.print(min(255, 255.0 * (512 + x) / 1024.0));
Serial.print(", Y="); Serial.print(y);
//Serial.print(min(255, 255.0 * (512 + y) / 1024.0));
Serial.print(", Z="); Serial.println(z);
//Serial.println(min(255, 255.0 * (512 + z) / 1024.0));
// EEPROM.write(addr, x);
analogWrite(Red, min(255, 255.0 * (512 + x) / 1024.0));
analogWrite(Green, min(255, 255.0 * (512 + y) / 1024.0));
analogWrite(Blue, min(255, 255.0 * (512 + z) / 1024.0));
}

View File

@@ -0,0 +1,207 @@
// esp8266_test.ino
//
// Plot LM35 data on thingspeak.com using an Arduino and an ESP8266 WiFi
// module.
#include <SoftwareSerial.h>
#include <stdlib.h>
#define DEBUG true
String NomduReseauWifi = "Livebox-37cc"; // Garder les guillements
String MotDePasse = "8A6060920A8A86896F770F2C47"; // Garder les guillements
// LED
int ledPin = 13;
// LM35 analog input
int lm35Pin = A0;
// replace with your channel's thingspeak API key
String apiKey = "ZP1PZO62773HXWVU";
// connect 10 to TX of Serial USB
// connect 11 to RX of serial USB
SoftwareSerial ESP8266(10, 11); // RX, TX
// this runs once
void setup() {
#ifdef DEBUG
Serial.begin(9600);
#endif
// initialize the digital pin as an output.
pinMode(ledPin, OUTPUT);
ESP8266.begin(115200);
envoieAuESP8266("AT+RST");
recoitDuESP8266(2000);
envoieAuESP8266("AT+CIOBAUD=9600");
recoitDuESP8266(2000);
ESP8266.begin(9600);
}
// the loop
void loop() {
initESP8266();
// blink LED on board
digitalWrite(ledPin, HIGH);
delay(200);
digitalWrite(ledPin, LOW);
// read the value from LM35.
// read 10 values for averaging.
int val = 0;
// for(int i = 0; i < 10; i++) {
// val += analogRead(lm35Pin);
// delay(500);
// }
// convert to temp:
// temp value is in 0-1023 range
// LM35 outputs 10mV/degree C. ie, 1 Volt => 100 degrees C
// So Temp = (avg_val/1023)*5 Volts * 100 degrees/Volt
float temp = val*50.0f/1023.0f;
// convert to string
char buf[16];
String strTemp = dtostrf(temp, 4, 1, buf);
Serial.println("Temp " + strTemp);
// TCP connection
debugPrintln("***************** GET ******************************");
String cmd = "AT+CIPSTART=4,\"TCP\",\"192.168.0.10\",8080";
envoieAuESP8266(cmd);
recoitDuESP8266(2000);
// if(ESP8266.find("Error")){
// Serial.println("AT+CIPSTART error");
// return;
// }
// prepare GET string
// String cmdGet = "GET /update?api_key=";
// cmdGet += apiKey;
// cmdGet +="&field1=";
// cmdGet += String(strTemp);
// cmdGet += "\r\n\r\n";
String url = "/json.htm?type=command&param=udevice&idx=158&svalue=255";
String cmdGet = "GET " + url + " HTTP/1.1\r\n"
+ "Host: 192.168.0.10\r\nUser-Agent: ESP8266_HTTP_Client\r\nConnection: close\r\n\r\n";
debugPrintln("***************Commande GET **********************");
// demande d'envoi
int maxLoops = 10;
int currentLoop = 0;
boolean done = false;
ESP8266.print("AT+CIPSEND=4,");
ESP8266.println(cmdGet.length());
//delay(500);
done = ESP8266.find(">");
currentLoop = 0;
while (!done) {
delay(500);
done = ESP8266.find(">");
if (currentLoop >= maxLoops) {
//debugPrintln(" Attente dépassée");
break;
}
currentLoop++;
//debugPrint(".");
}
envoieAuESP8266(cmdGet + "\r\n\r\n");
recoitDuESP8266(8000);
// // send data length
// cmd = "AT+CIPSEND=";
// cmd += String(cmdGet.length());
// ESP8266.println(cmd);
//
// if(ESP8266.find(">")){
// ESP8266.print(cmdGet);
// }
// else{
// ESP8266.println("AT+CIPCLOSE");
// // alert user
// Serial.println("AT+CIPCLOSE");
// }
// thingspeak needs 15 sec delay between updates
delay(16000);
}
void initESP8266()
{
debugPrintln("**************** DEBUT DE L'INITIALISATION ***************");
envoieAuESP8266("AT");
recoitDuESP8266(1000);
envoieAuESP8266("AT+CWMODE=3");
recoitDuESP8266(1000);
envoieAuESP8266("AT+CWJAP=\"" + NomduReseauWifi + "\",\"" + MotDePasse + "\"");
recoitDuESP8266(10000);
envoieAuESP8266("AT+CIFSR");
recoitDuESP8266(1000);
envoieAuESP8266("AT+CIPMUX=1");
recoitDuESP8266(1000);
envoieAuESP8266("AT+CIPSERVER=1,80");
recoitDuESP8266(1000);
debugPrintln("***************** INITIALISATION TERMINEE ****************");
debugPrintln("");
}
/****************************************************************/
/* Fonction qui envoie une commande à l'ESP8266 */
/****************************************************************/
void envoieAuESP8266(String commande)
{
// debugPrintln(commande);
ESP8266.println(commande);
}
/****************************************************************/
/*Fonction qui lit et affiche les messages envoyés par l'ESP8266*/
/****************************************************************/
void recoitDuESP8266(const int timeout)
{
String reponse = "";
long int time = millis();
while ( (time + timeout) > millis())
{
while (ESP8266.available())
{
char c = ESP8266.read();
reponse += c;
}
}
debugPrintln(reponse);
}
void debugPrint(String m) {
#ifdef DEBUG
Serial.print(m);
#endif
}
void debugPrintln(String m) {
#ifdef DEBUG
Serial.println(m);
#endif
}

View File

@@ -0,0 +1,151 @@
#include <SoftwareSerial.h>
#include "DHT.h"
/** DHT **/
#define DHTPIN 5
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
/** ESP8266 **/
String ssid = "Livebox-37cc";
String key = "8A6060920A8A86896F770F2C47";
String serverHost = "192.168.0.10";
String serverPort = "8080";
SoftwareSerial esp8266(10, 11); // RX, TX
bool done = false;
void setup() {
Serial.begin(9600);
/** DHT **/
dht.begin();
Serial.println("1");
/** ESP8266 **/
esp8266.begin(9600);
delay(500);
esp8266.println("AT+RST");
Serial.println("2");
/**
* Initialisation
*/
delay(1000);
esp8266.println("AT");
done = esp8266.find("OK");
if(!done){
delay(1000);
done = esp8266.find("OK");
}
Serial.println(done);
/**
* Se mettreen mode CLIENT
*/
esp8266.println("AT+CWMODE=1");
done = esp8266.find("OK");
if(!done){
delay(1000);
done = esp8266.find("OK");
}
Serial.println(done);
/**
* Connexion auWifi
*/
esp8266.println("AT+CWJAP=\""+ssid+"\",\""+key+"\"");
done = esp8266.find("OK");
while(!done){
delay(1000);
done = esp8266.find("OK");
}
Serial.println(done);
/**
* Se mettre en mode multiple connexions
*/
esp8266.println("AT+CIPMUX=1");
done = esp8266.find("OK");
if(!done){
delay(1000);
done = esp8266.find("OK");
}
Serial.println(done);
/**
* Récupération de l'adresse IP
*/
esp8266.println("AT+CIFSR");
done = esp8266.find("STAIP");
if(!done){
delay(1000);
done = esp8266.find("OK");
}
Serial.println(done);
}
void loop() {
int maxLoops = 5;
/**
* DHT11 : Temperature
*/
float temperature = dht.readTemperature();
if( isnan(temperature) ){
// return;
temperature = 19;
}
// convert float --> String
String temperatureStr = "";
char temperatureChar[15];
dtostrf(temperature,5,2,temperatureChar);
temperatureStr = temperatureChar;
/**
* HTTP GET
*/
String cmd = "AT+CIPSTART=4,\"TCP\",\""+serverHost+"\","+serverPort;
esp8266.println(cmd);
delay(500);
done = esp8266.find("OK");
int currentLoop = 0;
while(!done){
delay(500);
done = esp8266.find("OK");
if(currentLoop >= maxLoops){
break;
}
currentLoop++;
}
String url = "/lda/index.php/data/createdatajson/append?datflval="+
temperatureStr +
"&thing=FIRST";
String cmdGET = "GET " + url + " HTTP/1.1\r\n"+
"Host: "+serverHost+"\r\nUser-Agent: ESP8266_HTTP_Client\r\nConnection: close\r\n\r\n";
esp8266.print("AT+CIPSEND=4,");
esp8266.println(cmdGET.length());
delay(1000);
done = esp8266.find(">");
currentLoop = 0;
while(!done){
delay(500);
done = esp8266.find(">");
if(currentLoop >= maxLoops){
break;
}
currentLoop++;
}
esp8266.println(cmdGET + "\r\n\r\n");
delay(1000);
esp8266.println("AT+CIPSTATUS");
delay(1000);
// Fermeture de toutes les connexions
esp8266.println("AT+CIPCLOSE=5");
delay(1000);
// repart à zero
esp8266.println("AT");
// 4 secondes sont déjà passées
delay(16000);
}

View File

@@ -0,0 +1,11 @@
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
Serial.begin(115200);
Serial.println("AT+RST");
delay(10000);
}

View File

@@ -0,0 +1,128 @@
/*
Arduino Leonardo <--> ESP8266
Eamil: earl@microcontrollerelectonics.com
*/
#define SSID "your_SSID"
#define PASS "your_password"
#define DST_IP "192.168.0.100"
#define CONNECT_ATTEMPTS 5
#define RST 8
#define CHP 9
#define LED 13
void setup() {
pinMode(RST, OUTPUT);
pinMode(LED, OUTPUT);
pinMode(CHP, OUTPUT);
reset();
Serial.begin(9600);
Serial1.begin(115200);
delay(5000);
Serial1.println("AT+RST");
delay(1000);
if (Serial1.find("ready")) Serial.println("Module is ready");
else {
Serial.println("ESP8266 Module did not respond.");
Serial.println("Enter Commands Manually.");
while (1) chk_serial_io();
}
delay(1000);
boolean connected = false;
for (int i = 0; i < CONNECT_ATTEMPTS; i++) {
if (connectWiFi()) {
connected = true;
break;
}
}
if (!connected) {
Serial.println("Enter Commands Manually.");
while (1) chk_serial_io();
}
delay(5000);
Serial1.println("AT+CIFSR");
Serial.println("ip address:");
while (Serial1.available()) Serial.write(Serial1.read());
Serial1.println("AT+CIPMUX=0");
}
void reset() {
digitalWrite(LED,HIGH);
digitalWrite(CHP,HIGH);
digitalWrite(RST,LOW);
delay(100);
digitalWrite(RST,HIGH);
delay(1000);
digitalWrite(LED,LOW);
}
void loop() {
String cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += DST_IP;
cmd += "\",80";
Serial1.println(cmd);
Serial.println(cmd);
if (Serial1.find("Error")) return;
cmd = "GET / HTTP/1.0\r\n\r\n";
Serial1.print("AT+CIPSEND=");
Serial1.println(cmd.length());
if (Serial1.find(">")) {
Serial.print(">");
} else {
Serial1.println("AT+CIPCLOSE");
Serial.println("connect timeout");
delay(1000);
return;
}
Serial1.print(cmd);
delay(2000);
while (Serial1.available()) {
char c = Serial1.read();
Serial.write(c);
if (c == '\r') Serial.print('\n');
}
Serial.println("====");
delay(1000);
}
void chk_serial_io() {
if (Serial1.available()) {
// if (Serial1.find("busy")) {
// Serial.println("Resetting...");
// reset();
// }
int inByte = Serial1.read();
Serial.write(inByte);
}
if (Serial.available()) {
int inByte = Serial.read();
Serial1.write(inByte);
}
}
boolean connectWiFi() {
Serial1.println("AT+CWMODE=1");
String cmd = "AT+CWJAP=\"";
cmd += SSID;
cmd += "\",\"";
cmd += PASS;
cmd += "\"";
Serial.println(cmd);
Serial1.println(cmd);
delay(2000);
if (Serial1.find("OK")) {
Serial.println("OK, WiFi Connected.");
return true;
} else {
Serial.println("Can not connect to WiFi.");
return false;
}
}

View File

@@ -0,0 +1,63 @@
// Present a "Will be back soon web page", as stand-in webserver.
// 2011-01-30 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php
#include <EtherCard.h>
#define STATIC 0 // set to 1 to disable DHCP (adjust myip/gwip values below)
#if STATIC
// ethernet interface ip address
static byte myip[] = { 192,168,0,22 };
// gateway ip address
static byte gwip[] = { 192,168,0,1 };
#endif
// ethernet mac address - must be unique on your network
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
byte Ethernet::buffer[500]; // tcp/ip send and receive buffer
const char page[] PROGMEM =
"HTTP/1.0 200 OK\r\n"
"Content-Type: text/html\r\n"
"Retry-After: 600\r\n"
"\r\n"
"<html>"
"<head><title>"
"my web page"
"</title></head>"
"<body>"
"<h3>hello world !</h3>"
"</body>"
"</html>"
;
void setup(){
Serial.begin(9600);
Serial.println("\n[backSoon]");
if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
Serial.println( "Failed to access Ethernet controller");
#if STATIC
ether.staticSetup(myip, gwip);
#else
if (!ether.dhcpSetup()) {
Serial.println("DHCP failed");
} else {
Serial.println("DHCP Succeeded");
}
#endif
//Serial.println(ether.myip);
ether.printIp("IP: ", ether.myip);
ether.printIp("GW: ", ether.gwip);
ether.printIp("DNS: ", ether.dnsip);
}
void loop(){
// wait for an incoming TCP packet, but ignore its contents
if (ether.packetLoop(ether.packetReceive())) {
memcpy_P(ether.tcpOffset(), page, sizeof page);
ether.httpServerReply(sizeof page - 1);
}
}

View File

@@ -0,0 +1,163 @@
// Ethercard REL example
#include <OneWire.h>
#include <EEPROM.h>
#include <DallasTemperature.h>
#define STATIC 0 // set to 1 to disable DHCP (adjust myip/gwip values below)
#if STATIC
// ethernet interface ip address
static byte myip[] = { 192,168,0,200 };
// gateway ip address
static byte gwip[] = { 192,168,0,1 };
#endif
// ethernet mac address - must be unique on your network
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
#define BUFFER_SIZE 500
byte Ethernet::buffer[BUFFER_SIZE];
BufferFiller bfill;
#define REL 5 // define REL pin
bool RELStatus = false;
float temp;
char temp_str[10];
#define ONE_WIRE_BUS 4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
const char http_OK[] PROGMEM =
"HTTP/1.0 200 OK\r\n"
"Content-Type: text/html\r\n"
"Pragma: no-cache\r\n\r\n";
const char http_Found[] PROGMEM =
"HTTP/1.0 302 Found\r\n"
"Location: /\r\n\r\n";
const char http_Unauthorized[] PROGMEM =
"HTTP/1.0 401 Unauthorized\r\n"
"Content-Type: text/html\r\n\r\n"
"<h1>401 Unauthorized</h1>";
void homePage()
{
String entete = "<meta http-equiv='refresh' content='10'/>"
"<title>Temp Server</title>"
"<body bgcolor=""#99CCFF"">\n";
String table = entete + "<table>";
table += "<TR><TD>Pin</TD><TD>Value</TD></TR>\n";
for (int i = 0; i < 2; i++) {
table += "<TR><TD>";
table += String(i);
table += "</TD><TD>";
table += String(digitalRead(i));
table += "</TD></TR>\n";
}
table += "<\/table>\n";
//table += "<img src=\"http://www.ac-grenoble.fr/ien.vienne1-2/spip/IMG/bmp_Image004.bmp\">";
String pied = "<\/body>";
// html += "<img src=\"http://www.ac-grenoble.fr/ien.vienne1-2/spip/IMG/bmp_Image004.bmp\">";
Serial.println(table);
//bfill.emit_p(String.toCharArray(html));
int len = table.length() + 1;
char tmp[len];
//Serial.println(tmp);
table.toCharArray(tmp, len);
bfill.emit_p(PSTR("$F$F"),http_OK,tmp);
// bfill.emit_p(PSTR("$F"
// "<meta http-equiv='refresh' content='10'/>"
// "<title>Temp Server</title>"
// "<body bgcolor=""#99CCFF"">"
// "<center>"
// "<br />"
// "<font size=""7"">"
// "Temperature: <b>"
// "$S &deg;C"
// "<br />"
// "<br />"
// "<img src=\"http://www.ac-grenoble.fr/ien.vienne1-2/spip/IMG/bmp_Image004.bmp\">"
// "</b>"
// "Relay Status: <a href=\"?REL=$F\">$F</a><b>"), http_OK, temp_str, RELStatus?PSTR("off"):PSTR("on"), RELStatus?PSTR("ON"):PSTR("OFF"));
}
void setup()
{
Serial.begin(9600);
pinMode(REL, OUTPUT);
if (ether.begin(BUFFER_SIZE, mymac) == 0)
Serial.println("Cannot initialise ethernet.");
else
Serial.println("Ethernet initialised.");
//ether.staticSetup(myip);
#if STATIC
ether.staticSetup(myip, gwip);
#else
if (!ether.dhcpSetup())
Serial.println("DHCP failed");
#endif
ether.printIp("IP: ", ether.myip);
ether.printIp("GW: ", ether.gwip);
ether.printIp("DNS: ", ether.dnsip);
}
void loop()
{
digitalWrite(REL, RELStatus); // write to REL digital output
delay(1); // necessary for my system
word len = ether.packetReceive(); // check for ethernet packet
word pos = ether.packetLoop(len); // check for tcp packet
sensors.requestTemperatures();
temp = (sensors.getTempCByIndex(0));
dtostrf(temp, 6, 2, temp_str);
if (pos) {
bfill = ether.tcpOffset();
char *data = (char *) Ethernet::buffer + pos;
if (strncmp("GET /", data, 5) != 0) {
// Unsupported HTTP request
// 304 or 501 response would be more appropriate
bfill.emit_p(http_Unauthorized);
}
else {
data += 5;
if (data[0] == ' ') {
Serial.println("Homepage");
// Return home page
homePage();
}
else if (strncmp("?REL=on ", data, 8) == 0) {
// Set RELStatus true and redirect to home page
RELStatus = true;
bfill.emit_p(http_Found);
}
else if (strncmp("?REL=off ", data, 9) == 0) {
// Set RELStatus false and redirect to home page
RELStatus = false;
bfill.emit_p(http_Found);
}
else {
// Page not found
bfill.emit_p(http_Unauthorized);
}
}
ether.httpServerReply(bfill.position()); // send http response
}
}

View File

@@ -0,0 +1,220 @@
#include <EtherCard.h>
#include <Client.h>
#define STATIC 0 // set to 1 to disable DHCP (adjust myip/gwip values below)
#if STATIC
// ethernet interface ip address
static byte myip[] = { 192,168,0,22 };
// gateway ip address
static byte gwip[] = { 192,168,0,1 };
#endif
// ethernet mac address - must be unique on your network
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
byte Ethernet::buffer[500]; // tcp/ip send and receive buffer
const int ledPin = 7;
BufferFiller bfill; //???????
void homePage() {
// long t = millis() / 1000;
// word h = t / 3600;
// byte m = (t / 60) % 60;
// byte s = t % 60;
// String html = "<img src=\"http://www.ac-grenoble.fr/ien.vienne1-2/spip/IMG/bmp_Image004.bmp\">";
//
// int len = html.length() + 1;
// char tmp[len];
// //Serial.println(tmp);
// html.toCharArray(tmp, len);bfill = ether.tcpOffset();
bfill.emit_p(PSTR( //???????
"HTTP/1.0 200 OK\r\n"
"Content-Type: text/html\r\n"
"Pragma: no-cache\r\n"
"\r\n"
"<meta></meta>" // http-equiv='refresh' content='1'/>"
"<html><head><title>RBBB server</title>"
//"<link rel=""stylesheet"" type=""text/css"" href=""css.css"">"
"</head>"
"<body>")); //???????
delay(1);
bfill.emit_p(PSTR(
"<form method=""get"" action=""/on""><button type=""submit"">$F</button></FORM><form method=""get"" action=""/off""><button type=""submit"">$F</button></FORM>"),
PSTR("ON"), PSTR("OFF"));
bfill.emit_p(PSTR("<a href=""http://google.com"" class=""button"">Go to Google</a>"));
// bfill.emit_p(PSTR("<TABLE>"));
// delay(1);
//
// delay(1);
// //bfill = ether.tcpOffset();
// for (int i = 0; i < 3; i++) {
//// // word pin = 0;
// bfill.emit_p(PSTR("<TR><TD>$F</TD><TD>$F</TD><TD>$F</TD></TR>"),
// PSTR("TOTO"), PSTR("X"), PSTR("O"));
// delay(2);
////
// }
// bfill.emit_p(PSTR("</TABLE></body></html>"));
bfill.emit_p(PSTR("</body></html>"));
delay(1);
}
void setup() {
Serial.begin(9600);
Serial.println("\n[backSoon]");
pinMode(ledPin, OUTPUT);
if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
Serial.println( "Failed to access Ethernet controller");
#if STATIC
ether.staticSetup(myip, gwip);
#else
if (!ether.dhcpSetup())
Serial.println("DHCP failed");
#endif
ether.printIp("IP: ", ether.myip);
ether.printIp("GW: ", ether.gwip);
ether.printIp("DNS: ", ether.dnsip);
}
const char okHeader[] PROGMEM =
"HTTP/1.0 200 OK\r\n"
"Content-Type: text/html\r\n"
"Pragma: no-cache\r\n";
const char okCSS[] PROGMEM =
"HTTP/1.0 200 OK\r\n"
"Content-Type: text/css\r\n"
"Pragma: no-cache\r\n";
static void configPage(const char* data) {
bfill.emit_p(PSTR("$F\r\n"
"<h3>Send a wireless data packet</h3>"
"<form>"
"<p>"
"Data bytes <input type=text name=b size=50> (decimal)<br>"
"Destination node <input type=text name=d size=3> "
"(1..31, or 0 to broadcast)<br>"
"</p>"
"<input type=submit value=Send>"
"</form>"), okHeader);
}
static void cssPage() {
const char css[] = "a.button {"
"-webkit-appearance: button;"
"-moz-appearance: button;"
"appearance: button;"
" text-decoration: none;"
"color: initial;}";
bfill.emit_p(PSTR("$F\r\n$F"), okCSS, css);
}
static void sendPage(const char* data) {
// // pick up submitted data, if present
// const char* p = strstr(data, "b=");
// byte d = getIntArg(data, "d");
// if (data[6] == '?' && p != 0 && 0 <= d && d <= 31) {
// // prepare to send data as soon as possible in loop()
// outDest = d & RF12_HDR_MASK ? RF12_HDR_DST | d : 0;
// outCount = 0;
// // convert the input string to a number of decimal data bytes in outBuf
// ++p;
// while (*p != 0 && *p != '&') {
// outBuf[outCount] = 0;
// while ('0' <= *++p && *p <= '9')
// outBuf[outCount] = 10 * outBuf[outCount] + (*p - '0');
// ++outCount;
// }
//#if SERIAL
// Serial.print("Send to ");
// Serial.print(outDest, DEC);
// Serial.print(':');
// for (byte i = 0; i < outCount; ++i) {
// Serial.print(' ');
// Serial.print(outBuf[i], DEC);
// }
// Serial.println();
//#endif
// // redirect to home page
// bfill.emit_p(PSTR(
// "HTTP/1.0 302 found\r\n"
// "Location: /\r\n"
// "\r\n"));
// return;
// }
// else show a send form
bfill.emit_p(PSTR("$F\r\n"
"<h3>Send a wireless data packet</h3>"
"<form>"
"<p>"
"Data bytes <input type=text name=b size=50> (decimal)<br>"
"Destination node <input type=text name=d size=3> "
"(1..31, or 0 to broadcast)<br>"
"</p>"
"<input type=submit value=Send>"
"</form>"), okHeader);
}
void loop(){
word len = ether.packetReceive();
word pos = ether.packetLoop(len);
// check if valid tcp data is received
if (pos) {
delay(1); // necessary for my system
bfill = ether.tcpOffset();
char* data = (char *) Ethernet::buffer + pos;
Serial.println(data);
// receive buf hasn't been clobbered by reply yet
if (strncmp("GET / ", data, 6) == 0) {
Serial.println("HomePage");
homePage();
} else if (strncmp("GET /css.css", data, 12) == 0) {
Serial.println("CSS");
cssPage();
} else if (strncmp("GET /on", data, 7) == 0) {
Serial.println("ON");
digitalWrite(ledPin, LOW);
homePage();
} else if (strncmp("GET /off", data, 8) == 0) {
Serial.println("OFF");
digitalWrite(ledPin, HIGH);
homePage();
} else if (strncmp("GET /c", data, 6) == 0) {
Serial.println("Config");
configPage(data);
} else if (strncmp("GET /d", data, 6) == 0) {
Serial.println("Data");
sendPage(data);
} else {
bfill.emit_p(PSTR(
"HTTP/1.0 401 Unauthorized\r\n"
"Content-Type: text/html\r\n"
"\r\n"
"<h1>401 Unauthorized</h1>"));
}
ether.httpServerReply(bfill.position()); // send web page data
}
}

View File

@@ -0,0 +1,44 @@
#include <EtherCard.h>
// ethernet interface ip address
static byte myip[] = { 192,168,0,50 };
// gateway ip address
static byte gwip[] = { 192,168,0,1 };
// ethernet mac address - must be unique on your network
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
byte Ethernet::buffer[500]; //??????
BufferFiller bfill; //???????
void setup () {
if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
Serial.println( "Failed to access Ethernet controller");
ether.staticSetup(myip);
}
static word homePage() {
long t = millis() / 1000;
word h = t / 3600;
byte m = (t / 60) % 60;
byte s = t % 60;
bfill = ether.tcpOffset(); //???????
bfill.emit_p(PSTR( //???????
"HTTP/1.0 200 OK\r\n"
"Content-Type: text/html\r\n"
"Pragma: no-cache\r\n"
"\r\n"
"<meta http-equiv='refresh' content='1'/>"
"<title>RBBB server</title>"
"<h1>$D$D:$D$D:$D$D</h1>"),
h/10, h%10, m/10, m%10, s/10, s%10); //???????
return bfill.position(); //???????
}
void loop () {
word len = ether.packetReceive();
word pos = ether.packetLoop(len);
if (pos) // check if valid tcp data is received
ether.httpServerReply(homePage()); // send web page data
}

View File

@@ -0,0 +1,52 @@
#include <RCSwitch.h>
#define couloir 12449942
#define porte 13464924
RCSwitch mySwitch = RCSwitch();
// On limite à un évènement par seconde long
#define debounceDelay 1000
// On a deux détecteurs, donc on a deux timers.
int last_times[2] = {0,0};
void setup() {
Serial.begin(9600);
mySwitch.enableReceive(0);
}
bool debounce(int number) {
if ((last_times[number] == 0) ||
((millis() - last_times[number]) > debounceDelay)) {
last_times[number] = millis();
return true;
}
return false;
}
void loop() {
if (mySwitch.available()) {
int value = mySwitch.getReceivedValue();
// on remet à zero le timer
while (!Serial) ;
switch (value) {
case porte:
if (debounce(0))
Serial.println("Quelqu'un a ouvert la porte !");
break;
case couloir:
if (debounce(1))
Serial.println("Quelqu'un marche dans le couloir !");
break;
default:
Serial.print("Dispositif inconnu: ");
Serial.println(value);
break;
}
mySwitch.resetAvailable();
}
}

445
ATMEGA_GAZ/ATMEGA_GAZ.ino Executable file
View File

@@ -0,0 +1,445 @@
// Gas monitoring device / Code from EquinoxeFR
// RFXmeter code from pyrou https://github.com/pyrou/x10rf
// OOK oregon encoding from http://connectingstuff.net/blog/encodage-protocoles-oregon-scientific-sur-arduino/
//#include <x10rf.h>
//#include <Energia.h>
#include <avr/eeprom.h>
#include <dht11.h>
#define SCHEMA 69 // Change value to initialize or reset the EEPROM
//#define DEBUG 1 // serial debug
#define WITHDHT22
#define DHT22_PIN 5 // Temp/humidity sensor pin
#define txPin 7 // RF 433MHz module
#define txRetry 5 // delay for retry when sending packets
#define transmitLedPin 13
#define reedLedPin 12
#define rfxSensorID 12
#define reedInterrupt 0 // Reed switch pin
#define delayPulse 5 // wait between two pulses. Avoid false reading with slow rotation
#define SEND_HIGH() digitalWrite(txPin, HIGH)
#define SEND_LOW() digitalWrite(txPin, LOW)
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
byte OregonMessageBuffer[9];
dht11 DHT;
unsigned long pulses = 0;
unsigned long previousPulses = 0;
int timer1_counter;
volatile unsigned long timerEeprom = 0;
volatile unsigned long timerSend = 0;
volatile unsigned long timerDebounce = 0;
volatile unsigned long lastDebounce = 0;
//x10rf myx10 = x10rf(txPin,transmitLedPin,txRetry);
void setup()
{
byte status=0;
//myx10.begin();
#ifdef DEBUG
Serial.begin(9600);
#endif
// Timer1 5Hz
noInterrupts(); // disable all interrupts
TCCR1A = 0;
TCCR1B = 0;
timer1_counter = 53036; // preload timer 65536-16MHz/256/5Hz
TCNT1 = timer1_counter; // preload timer
TCCR1B |= (1 << CS12); // 256 prescaler
TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt
interrupts(); // enable all interrupts
// EEProm init or read
eeprom_read_block((void*)&status, (void*)0, sizeof(status));
if (status != SCHEMA)
{
#ifdef DEBUG
Serial.println("New EEPROM detected. Initializing...");
#endif
status=SCHEMA;
// writing SCHEMA version
eeprom_write_block((const void*)&status, (void*)0, sizeof(status));
// writing initial pulse count (0)
eeprom_write_block((const void*)&pulses, (void*)1, sizeof(pulses));
}
else
{
// reading pulses from EEprom
eeprom_read_block((void*)&pulses, (void*)1, sizeof(pulses));
}
previousPulses=pulses;
#ifdef DEBUG
Serial.print("Reading data from eeprom: ");
Serial.println(pulses);
#endif
#ifdef WITHDHT22
// Setup OOK packets for Oregon sensors
byte ID[] = {
0x1A,0x2D };
setType(OregonMessageBuffer, ID);
setChannel(OregonMessageBuffer, 0x20);
setId(OregonMessageBuffer, 0xBB);
#endif
// Setup pins
pinMode(transmitLedPin,OUTPUT);
pinMode(reedLedPin,OUTPUT);
pinMode(reedInterrupt,INPUT);
// Interrupt for reed switch
attachInterrupt(reedInterrupt, debounceInterrupt, RISING);
}
// Main loop
void loop()
{
// Saving pulses to EEprom every hour (100 000 write cycles allowed)
if (timerEeprom >= 3600*5)
{
timerEeprom=0;
if (pulses != previousPulses)
{
#ifdef DEBUG
Serial.println("Saving data to eeprom");
#endif
eeprom_write_block((const void*)&pulses, (void*)1, sizeof(pulses));
}
}
// Sending RF packets every 30s
if (timerSend >= 30*5)
{
timerSend=0;
//myx10.RFXmeter(rfxSensorID,0,pulses);
#ifdef WITHDHT22
int chk = DHT.read(DHT22_PIN);
#ifdef DEBUG
Serial.print("Temp: ");
Serial.println(DHT.temperature, 1);
Serial.print("Humidity: ");
Serial.println(DHT.humidity, 1);
#endif
setBatteryLevel(OregonMessageBuffer, 1);
setTemperature(OregonMessageBuffer, DHT.temperature);
setHumidity(OregonMessageBuffer, DHT.humidity);
calculateAndSetChecksum(OregonMessageBuffer);
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
SEND_LOW();
delayMicroseconds(TWOTIME*8);
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
SEND_LOW();
#endif
}
}
// Timer1 interrupt. Managing timers
ISR(TIMER1_OVF_vect) // interrupt service routine
{
TCNT1 = timer1_counter; // preload timer
timerEeprom++;
timerSend++;
timerDebounce++;
}
// Reed switch interrupt with debounce
void debounceInterrupt() {
#ifdef DEBUG
Serial.println("Int !!!");
Serial.println(timerDebounce);
Serial.println(lastDebounce);
#endif
if ((timerDebounce - lastDebounce) >= delayPulse * 5)
{
lastDebounce = 0;
timerDebounce = 0;
Interrupt();
}
}
// Reed switch
void Interrupt() {
#ifdef DEBUG
Serial.println("New pulse !");
#endif
pulses++;
digitalWrite(reedLedPin,HIGH);
delay(800);
digitalWrite(reedLedPin,LOW);
}
// Other code is from http://connectingstuff.net/blog/encodage-protocoles-oregon-scientific-sur-arduino/
// Copy and paste :)
/**
* \brief Send logical "0" over RF
* \details azero bit be represented by an off-to-on transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendZero(void)
{
SEND_HIGH();
delayMicroseconds(TIME);
SEND_LOW();
delayMicroseconds(TWOTIME);
SEND_HIGH();
delayMicroseconds(TIME);
}
/**
* \brief Send logical "1" over RF
* \details a one bit be represented by an on-to-off transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendOne(void)
{
SEND_LOW();
delayMicroseconds(TIME);
SEND_HIGH();
delayMicroseconds(TWOTIME);
SEND_LOW();
delayMicroseconds(TIME);
}
/**
* Send a bits quarter (4 bits = MSB from 8 bits value) over RF
*
* @param data Source data to process and sent
*/
/**
* \brief Send a bits quarter (4 bits = MSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterMSB(const byte data)
{
(bitRead(data, 4)) ? sendOne() : sendZero();
(bitRead(data, 5)) ? sendOne() : sendZero();
(bitRead(data, 6)) ? sendOne() : sendZero();
(bitRead(data, 7)) ? sendOne() : sendZero();
}
/**
* \brief Send a bits quarter (4 bits = LSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterLSB(const byte data)
{
(bitRead(data, 0)) ? sendOne() : sendZero();
(bitRead(data, 1)) ? sendOne() : sendZero();
(bitRead(data, 2)) ? sendOne() : sendZero();
(bitRead(data, 3)) ? sendOne() : sendZero();
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Send a buffer over RF
* \param data Data to send
* \param size size of data to send
*/
void sendData(byte *data, byte size)
{
for(byte i = 0; i < size; ++i)
{
sendQuarterLSB(data[i]);
sendQuarterMSB(data[i]);
}
}
/**
* \brief Send an Oregon message
* \param data The Oregon message
*/
void sendOregon(byte *data, byte size)
{
sendPreamble();
//sendSync();
sendData(data, size);
sendPostamble();
}
/**
* \brief Send preamble
* \details The preamble consists of 16 "1" bits
*/
inline void sendPreamble(void)
{
byte PREAMBLE[]={
0xFF,0xFF };
sendData(PREAMBLE, 2);
}
/**
* \brief Send postamble
* \details The postamble consists of 8 "0" bits
*/
inline void sendPostamble(void)
{
#ifdef THN132N
sendQuarterLSB(0x00);
#else
byte POSTAMBLE[]={
0x00 };
sendData(POSTAMBLE, 1);
#endif
}
/**
* \brief Send sync nibble
* \details The sync is 0xA. It is not use in this version since the sync nibble
* \ is include in the Oregon message to send.
*/
inline void sendSync(void)
{
sendQuarterLSB(0xA);
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Set the sensor type
* \param data Oregon message
* \param type Sensor type
*/
inline void setType(byte *data, byte* type)
{
data[0] = type[0];
data[1] = type[1];
}
/**
* \brief Set the sensor channel
* \param data Oregon message
* \param channel Sensor channel (0x10, 0x20, 0x30)
*/
inline void setChannel(byte *data, byte channel)
{
data[2] = channel;
}
/**
* \brief Set the sensor ID
* \param data Oregon message
* \param ID Sensor unique ID
*/
inline void setId(byte *data, byte ID)
{
data[3] = ID;
}
/**
* \brief Set the sensor battery level
* \param data Oregon message
* \param level Battery level (0 = low, 1 = high)
*/
void setBatteryLevel(byte *data, byte level)
{
if(!level) data[4] = 0x0C;
else data[4] = 0x00;
}
/**
* \brief Set the sensor temperature
* \param data Oregon message
* \param temp the temperature
*/
void setTemperature(byte *data, float temp)
{
// Set temperature sign
if(temp < 0)
{
data[6] = 0x08;
temp *= -1;
}
else
{
data[6] = 0x00;
}
// Determine decimal and float part
int tempInt = (int)temp;
int td = (int)(tempInt / 10);
int tf = (int)round((float)((float)tempInt/10 - (float)td) * 10);
int tempFloat = (int)round((float)(temp - (float)tempInt) * 10);
// Set temperature decimal part
data[5] = (td << 4);
data[5] |= tf;
// Set temperature float part
data[4] |= (tempFloat << 4);
}
/**
* \brief Set the sensor humidity
* \param data Oregon message
* \param hum the humidity
*/
void setHumidity(byte* data, byte hum)
{
data[7] = (hum/10);
data[6] |= (hum - data[7]*10) << 4;
}
/**
* \brief Sum data for checksum
* \param count number of bit to sum
* \param data Oregon message
*/
int Sum(byte count, const byte* data)
{
int s = 0;
for(byte i = 0; i<count;i++)
{
s += (data[i]&0xF0) >> 4;
s += (data[i]&0xF);
}
if(int(count) != count)
s += (data[count]&0xF0) >> 4;
return s;
}
/**
* \brief Calculate checksum
* \param data Oregon message
*/
void calculateAndSetChecksum(byte* data)
{
#ifdef THN132N
int s = ((Sum(6, data) + (data[6]&0xF) - 0xa) & 0xff);
data[6] |= (s&0x0F) << 4;
data[7] = (s&0xF0) >> 4;
#else
data[8] = ((Sum(8, data) - 0xa) & 0xFF);
#endif
}

View File

@@ -0,0 +1,51 @@
//Measuring Current Using ACS712
const int analogIn = A0; //Connect current sensor with A0 of Arduino
int mVperAmp = 185; // use 100 for 20A Module and 66 for 30A Module
int RawValue= 0;
int ACSoffset = 2500;
double Voltage = 0; //voltage measuring
double Amps = 0;// Current measuring
void setup() {
//baud rate
Serial.begin(9600);//baud rate at which arduino communicates with Laptop/PC
delay(2000);//delay for 2 sec
}
float valeurACS712( int pin )
{
int valeur;
float moyenne = 0;
int nbr_lectures = 50;
for( int i = 0; i < nbr_lectures; i++ )
{
valeur = analogRead( pin );
moyenne = moyenne + float(valeur);
delay(10);
}
moyenne = moyenne / float(nbr_lectures);
return moyenne -235;
}
void loop() //method to run the source code repeatedly
{
RawValue = valeurACS712(analogIn);//reading the value from the analog pin
Voltage = (RawValue / 1024.0) * 5000; // Gets you mV
Amps = ((Voltage - ACSoffset) / mVperAmp);
//Prints on the serial port
Serial.print("Raw Value = " ); // prints on the serial monitor
Serial.print(RawValue); //prints the results on the serial monitor
Serial.print("\t mV = "); // shows the voltage measured
Serial.print(Voltage,3); // the '3' after voltage allows you to display 3 digits after decimal point
Serial.print("\t Amps = "); // shows the voltage measured
Serial.println(Amps,3);// the '3' after voltage allows you to display 3 digits after decimal point
delay(2500);
}

View File

@@ -0,0 +1,76 @@
/*
Measuring Current Using ACS712
*/
#include "math.h"
const int analogIn = A0;
int mVperAmp = 185; // 185 pour 5A, use 100 for 20A Module and 66 for 30A Module
int RawValue= 0;
int ACSoffset = 2500;
double mp_offset = 0.040;
double Voltage = 0;
double Amps = 0;
void setup(){
Serial.begin(9600);
pinMode(A0, INPUT);
}
void loop(){
int i = 0;
RawValue = 0;
// Somme du courant alternatif pendant 20 ms ==> 50hz
// Détermination du max et max pour hauteur de crete
int vmin = 1024;
int vmax = 0;
for (i = 0; i < 20; i++) {
int value = analogRead(analogIn);
if (value >= 0) {
RawValue += value;
vmax = max(value,vmax);
vmin = min(value,vmin);
} else {
i--;
}
delay(1);
}
// Serial.print("Raw Value = " );
// Serial.print(RawValue);
Serial.print("min = " );
Serial.print(vmin);
Serial.print(" max = " );
Serial.print(vmax);
// Serial.print(" i =" );
// Serial.print(i);
// RawValue = RawValue / i;
// Tension continue
// Voltage = (RawValue / 1023.0) * 5000; // Gets you mV
// Amps = ((Voltage - ACSoffset) / mVperAmp);
// La valeur maxi * racine carrée de 2 pour obtenir la tension "réelle"
// La tension efficace pour l'effet Hall étant réduite d'un facteur 0,707
Voltage = ((vmax - vmin) / 430.0) * 5000;
Amps = max(5.5 * (vmax - vmin) / 473.0 -0.0580, 0.0); // <= pour le bruit
// Serial.print(" Raw Value = " ); // shows pre-scaled value
// Serial.print(RawValue);
Serial.print("\t mV = "); // shows the voltage measured
Serial.print(Voltage,3); // the '3' after voltage allows you to display 3 digits after decimal point
Serial.print("\t Amps = "); // shows the voltage measured
Serial.print(Amps,3); // the '3' after voltage allows you to display 3 digits after decimal point
Serial.print("\t Watt = "); // shows the voltage measured
Serial.print(Amps * 220,3);
Serial.print("\t WattH = "); // shows the voltage measured
Serial.println(Amps * 220 / 1200,3);
delay(2500);
}

View File

@@ -0,0 +1,174 @@
#include <RCSwitch.h>
#include <Narcoleptic.h>
#include <Wire.h>
#define SEND_MESSAGE_DELAY 3000 // Ne pas dépasser 32000 !! Delay in ms between each value's extraction
#define SEND_433_PAUSE 160 // 16 multiple
#define DEBUG true
const unsigned long activation = 111269; // Radiateur
const unsigned long idRad=331969;
const unsigned long desactivation = 962111; // Fin radiateur
const unsigned int delai = 11;
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
const int analogIn = A0;
int mVperAmp = 185; // 185 pour 5A, use 100 for 20A Module and 66 for 30A Module
int RawValue= 0;
int ACSoffset = 2500;
double Voltage = 0;
double Amps = 0;
RCSwitch mySwitch = RCSwitch();
void setup() {
#ifdef DEBUG
Serial.begin(9600);
Serial.println("\n[Oregon V2.1 encoder]");
#endif
pinMode(13, OUTPUT);
mySwitch.enableTransmit(9);
}
void loop() {
enableADC();
delay(100);
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(10); // wait for a second
digitalWrite(13, LOW);
long vcc = readVcc();
#ifdef DEBUG
Serial.print("Send vcc=");
Serial.println(vcc);
#endif
mySwitch.send(activation, 24);
delay(delai); //delayMicroseconds
double amp = getAmp();
myMessageSend(idRad,(220.0 * amp));
mySwitch.send(desactivation, 24);
delay(delai);
delayMicroseconds(TWOTIME*8);
disableADC();
Narcoleptic.delay(SEND_MESSAGE_DELAY);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
}
void myMessageSend(long id, long value) {
#ifdef DEBUG
Serial.print("Send id="); Serial.print(id);
Serial.print(" value="); Serial.println(value);
#endif
mySwitch.send(id, 24); //"000000000001010100010001");
delay(delai);
mySwitch.send(value, 24); //"000000000001010100010001");
delay(delai);
//delay(5000);
//delayMicroseconds(TWOTIME*8);
}
void enableADC() {
//bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
delay(2); // Wait for Vref to settle
while (bit_is_set(ADCSRA,ADSC));
}
void disableADC() {
//ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
//while (bit_is_set(ADCSRA,ADSC));
delay(2); // Wait for Vref to settle
}
//--------------------------------------------------------------------------------------------------
// Read current supply voltage
//--------------------------------------------------------------------------------------------------
long readVcc() {
bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
long result;
// Read 1.1V reference against Vcc
#if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
#endif
// ADCSRB = 0;
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate Vcc in mV
// ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
// analogReference(DEFAULT);
return result; // Vcc in millivolts
}
double getAmp() {
int i = 0;
RawValue = 0;
// Somme du courant alternatif pendant 20 ms ==> 50hz
// Détermination du max et max pour hauteur de crete
int vmin = 1024;
int vmax = 0;
for (i = 0; i < 20; i++) {
int value = analogRead(analogIn);
if (value >= 0) {
RawValue += value;
vmax = max(value,vmax);
vmin = min(value,vmin);
} else {
i--;
}
delay(1);
}
#ifdef DEBUG
Serial.print("min = " );
Serial.print(vmin);
Serial.print(" max = " );
Serial.print(vmax);
#endif
// La valeur maxi * racine carrée de 2 pour obtenir la tension "réelle"
// La tension efficace pour l'effet Hall étant réduite d'un facteur 0,707
Voltage = ((vmax - vmin) / 430.0) * 5000;
Amps = 5.5 * (vmax - vmin) / 473.0;
// Serial.print(" Raw Value = " ); // shows pre-scaled value
// Serial.print(RawValue);
#ifdef DEBUG
Serial.print("\t mV = "); // shows the voltage measured
Serial.print(Voltage,3); // the '3' after voltage allows you to display 3 digits after decimal point
Serial.print("\t Amps = "); // shows the voltage measured
Serial.println(Amps,3); // the '3' after voltage allows you to display 3 digits after decimal point
#endif
return Amps;
}

View File

@@ -0,0 +1,36 @@
/*
* IRremote: IRsendDemo - demonstrates sending IR codes with IRsend
* An IR LED must be connected to Arduino PWM pin 3.
* Version 0.1 July, 2009
* Copyright 2009 Ken Shirriff
* http://arcfn.com
*/
#include <IRremote.h>
IRsend irsend;
void setup()
{
Serial.begin(9600);
}
void loop() {
//if (Serial.read() != -1) {
//for (int i = 0; i < 3; i++) {
unsigned int buf[] = {29122,500,250,1750,300,1200,300,5450,50,450,100,400,100,650};
unsigned int buf2[] = {22964,450,350,400,50,450,50,700,350,650,100,400,350,400,100,400,100,400,150,350,150,350,150,600,400,350,150,350,150,350,150,350,150,350,150,350,200,550};
Serial.println("Données envoyées");
//irsend.sendNEC(0x20DF10EF, 32); // Sony TV power code
irsend.sendRaw(buf, 14, 32);
delay(40);
irsend.sendRaw(buf2, 38, 32);
delay(2000);
//}
// }
}

View File

@@ -0,0 +1,25 @@
const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), onEvent, CHANGE);
Serial.println(F("Système intialisé"));
}
void loop() {
digitalWrite(ledPin, state);
}
void onEvent() {
state = !state;
Serial.print(F("Switch LED 13 : "));
if(state){
Serial.println(F("ON"));
}else{
Serial.println(F("OFF"));
}
}

175
ATMEGA_LCD5/ATMEGA_LCD5.ino Executable file
View File

@@ -0,0 +1,175 @@
#define PIN_SCE 7
#define PIN_RESET 6
#define PIN_DC 5
#define PIN_SDIN 4
#define PIN_SCLK 3
#define LCD_C LOW
#define LCD_D HIGH
#define LCD_X 84
#define LCD_Y 48
static const byte ASCII[][5] =
{
{0x00, 0x00, 0x00, 0x00, 0x00} // 20
,{0x00, 0x00, 0x5f, 0x00, 0x00} // 21 !
,{0x00, 0x07, 0x00, 0x07, 0x00} // 22 "
,{0x14, 0x7f, 0x14, 0x7f, 0x14} // 23 #
,{0x24, 0x2a, 0x7f, 0x2a, 0x12} // 24 $
,{0x23, 0x13, 0x08, 0x64, 0x62} // 25 %
,{0x36, 0x49, 0x55, 0x22, 0x50} // 26 &
,{0x00, 0x05, 0x03, 0x00, 0x00} // 27 '
,{0x00, 0x1c, 0x22, 0x41, 0x00} // 28 (
,{0x00, 0x41, 0x22, 0x1c, 0x00} // 29 )
,{0x14, 0x08, 0x3e, 0x08, 0x14} // 2a *
,{0x08, 0x08, 0x3e, 0x08, 0x08} // 2b +
,{0x00, 0x50, 0x30, 0x00, 0x00} // 2c ,
,{0x08, 0x08, 0x08, 0x08, 0x08} // 2d -
,{0x00, 0x60, 0x60, 0x00, 0x00} // 2e .
,{0x20, 0x10, 0x08, 0x04, 0x02} // 2f /
,{0x3e, 0x51, 0x49, 0x45, 0x3e} // 30 0
,{0x00, 0x42, 0x7f, 0x40, 0x00} // 31 1
,{0x42, 0x61, 0x51, 0x49, 0x46} // 32 2
,{0x21, 0x41, 0x45, 0x4b, 0x31} // 33 3
,{0x18, 0x14, 0x12, 0x7f, 0x10} // 34 4
,{0x27, 0x45, 0x45, 0x45, 0x39} // 35 5
,{0x3c, 0x4a, 0x49, 0x49, 0x30} // 36 6
,{0x01, 0x71, 0x09, 0x05, 0x03} // 37 7
,{0x36, 0x49, 0x49, 0x49, 0x36} // 38 8
,{0x06, 0x49, 0x49, 0x29, 0x1e} // 39 9
,{0x00, 0x36, 0x36, 0x00, 0x00} // 3a :
,{0x00, 0x56, 0x36, 0x00, 0x00} // 3b ;
,{0x08, 0x14, 0x22, 0x41, 0x00} // 3c <
,{0x14, 0x14, 0x14, 0x14, 0x14} // 3d =
,{0x00, 0x41, 0x22, 0x14, 0x08} // 3e >
,{0x02, 0x01, 0x51, 0x09, 0x06} // 3f ?
,{0x32, 0x49, 0x79, 0x41, 0x3e} // 40 @
,{0x7e, 0x11, 0x11, 0x11, 0x7e} // 41 A
,{0x7f, 0x49, 0x49, 0x49, 0x36} // 42 B
,{0x3e, 0x41, 0x41, 0x41, 0x22} // 43 C
,{0x7f, 0x41, 0x41, 0x22, 0x1c} // 44 D
,{0x7f, 0x49, 0x49, 0x49, 0x41} // 45 E
,{0x7f, 0x09, 0x09, 0x09, 0x01} // 46 F
,{0x3e, 0x41, 0x49, 0x49, 0x7a} // 47 G
,{0x7f, 0x08, 0x08, 0x08, 0x7f} // 48 H
,{0x00, 0x41, 0x7f, 0x41, 0x00} // 49 I
,{0x20, 0x40, 0x41, 0x3f, 0x01} // 4a J
,{0x7f, 0x08, 0x14, 0x22, 0x41} // 4b K
,{0x7f, 0x40, 0x40, 0x40, 0x40} // 4c L
,{0x7f, 0x02, 0x0c, 0x02, 0x7f} // 4d M
,{0x7f, 0x04, 0x08, 0x10, 0x7f} // 4e N
,{0x3e, 0x41, 0x41, 0x41, 0x3e} // 4f O
,{0x7f, 0x09, 0x09, 0x09, 0x06} // 50 P
,{0x3e, 0x41, 0x51, 0x21, 0x5e} // 51 Q
,{0x7f, 0x09, 0x19, 0x29, 0x46} // 52 R
,{0x46, 0x49, 0x49, 0x49, 0x31} // 53 S
,{0x01, 0x01, 0x7f, 0x01, 0x01} // 54 T
,{0x3f, 0x40, 0x40, 0x40, 0x3f} // 55 U
,{0x1f, 0x20, 0x40, 0x20, 0x1f} // 56 V
,{0x3f, 0x40, 0x38, 0x40, 0x3f} // 57 W
,{0x63, 0x14, 0x08, 0x14, 0x63} // 58 X
,{0x07, 0x08, 0x70, 0x08, 0x07} // 59 Y
,{0x61, 0x51, 0x49, 0x45, 0x43} // 5a Z
,{0x00, 0x7f, 0x41, 0x41, 0x00} // 5b [
,{0x02, 0x04, 0x08, 0x10, 0x20} // 5c ¥
,{0x00, 0x41, 0x41, 0x7f, 0x00} // 5d ]
,{0x04, 0x02, 0x01, 0x02, 0x04} // 5e ^
,{0x40, 0x40, 0x40, 0x40, 0x40} // 5f _
,{0x00, 0x01, 0x02, 0x04, 0x00} // 60 `
,{0x20, 0x54, 0x54, 0x54, 0x78} // 61 a
,{0x7f, 0x48, 0x44, 0x44, 0x38} // 62 b
,{0x38, 0x44, 0x44, 0x44, 0x20} // 63 c
,{0x38, 0x44, 0x44, 0x48, 0x7f} // 64 d
,{0x38, 0x54, 0x54, 0x54, 0x18} // 65 e
,{0x08, 0x7e, 0x09, 0x01, 0x02} // 66 f
,{0x0c, 0x52, 0x52, 0x52, 0x3e} // 67 g
,{0x7f, 0x08, 0x04, 0x04, 0x78} // 68 h
,{0x00, 0x44, 0x7d, 0x40, 0x00} // 69 i
,{0x20, 0x40, 0x44, 0x3d, 0x00} // 6a j
,{0x7f, 0x10, 0x28, 0x44, 0x00} // 6b k
,{0x00, 0x41, 0x7f, 0x40, 0x00} // 6c l
,{0x7c, 0x04, 0x18, 0x04, 0x78} // 6d m
,{0x7c, 0x08, 0x04, 0x04, 0x78} // 6e n
,{0x38, 0x44, 0x44, 0x44, 0x38} // 6f o
,{0x7c, 0x14, 0x14, 0x14, 0x08} // 70 p
,{0x08, 0x14, 0x14, 0x18, 0x7c} // 71 q
,{0x7c, 0x08, 0x04, 0x04, 0x08} // 72 r
,{0x48, 0x54, 0x54, 0x54, 0x20} // 73 s
,{0x04, 0x3f, 0x44, 0x40, 0x20} // 74 t
,{0x3c, 0x40, 0x40, 0x20, 0x7c} // 75 u
,{0x1c, 0x20, 0x40, 0x20, 0x1c} // 76 v
,{0x3c, 0x40, 0x30, 0x40, 0x3c} // 77 w
,{0x44, 0x28, 0x10, 0x28, 0x44} // 78 x
,{0x0c, 0x50, 0x50, 0x50, 0x3c} // 79 y
,{0x44, 0x64, 0x54, 0x4c, 0x44} // 7a z
,{0x00, 0x08, 0x36, 0x41, 0x00} // 7b {
,{0x00, 0x00, 0x7f, 0x00, 0x00} // 7c |
,{0x00, 0x41, 0x36, 0x08, 0x00} // 7d }
,{0x10, 0x08, 0x08, 0x10, 0x08} // 7e ←
,{0x78, 0x46, 0x41, 0x46, 0x78} // 7f →
};
void LcdCharacter(char character)
{
LcdWrite(LCD_D, 0x00);
for (int index = 0; index < 5; index++)
{
LcdWrite(LCD_D, ASCII[character - 0x20][index]);
}
LcdWrite(LCD_D, 0x00);
}
void LcdClear(void)
{
for (int index = 0; index < LCD_X * LCD_Y / 8; index++)
{
LcdWrite(LCD_D, 0x00);
}
}
void LcdInitialise(void)
{
pinMode(PIN_SCE, OUTPUT);
pinMode(PIN_RESET, OUTPUT);
pinMode(PIN_DC, OUTPUT);
pinMode(PIN_SDIN, OUTPUT);
pinMode(PIN_SCLK, OUTPUT);
digitalWrite(PIN_RESET, LOW);
digitalWrite(PIN_RESET, HIGH);
LcdWrite(LCD_C, 0x21 ); // LCD Extended Commands.
LcdWrite(LCD_C, 0xB1 ); // Set LCD Vop (Contrast).
LcdWrite(LCD_C, 0x04 ); // Set Temp coefficent. //0x04
LcdWrite(LCD_C, 0x14 ); // LCD bias mode 1:48. //0x13
LcdWrite(LCD_C, 0x20 ); // LCD Basic Commands
LcdWrite(LCD_C, 0x0C ); // LCD in normal mode.
}
void LcdString(char *characters)
{
while (*characters)
{
LcdCharacter(*characters++);
}
}
void LcdWrite(byte dc, byte data)
{
digitalWrite(PIN_DC, dc);
digitalWrite(PIN_SCE, LOW);
shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
digitalWrite(PIN_SCE, HIGH);
}
void setup(void)
{
//LcdInitialise();
//LcdClear();
LcdString("Hello World!");
}
void loop(void)
{
}

View File

@@ -0,0 +1,195 @@
#include <RCSwitch.h>
#include <Narcoleptic.h>
#include <Adafruit_BMP085.h>
#include <Wire.h>
#include "DHT.h"
#define DHTPIN A2 // what pin we're connected to
#define DHTTYPE DHT11 // DHT 11
// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);
#define SEND_MESSAGE_DELAY 30000 // Ne pas dépasser 32000 !! Delay in ms between each value's extraction
#define SEND_433_PAUSE 160 // 16 multiple
#define DEBUG true
const unsigned long activation = 111269;
const unsigned long idTemp=1969;
const unsigned long idPressure=2069;
const unsigned long idPression=2169;
const unsigned long idLum=2269;
const unsigned long desactivation = 962111;
const unsigned int delai = 11;
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
// ################# Barometre ####
Adafruit_BMP085 bmp;
// #####################
float temperature = 0.0;
float pressure = 0.0;
float pression = 0.0;
float presiune = 0.0;
RCSwitch mySwitch = RCSwitch();
void setup() {
#ifdef DEBUG
Serial.begin(9600);
Serial.println("\n[Oregon V2.1 encoder]");
#endif
mySwitch.enableTransmit(9);
//mySwitch.setRepeatTransmit(2);
// DHT
dht.begin();
}
// Commande pour barometre humidité température
// Virtual Device
// http://192.168.0.10:8080/json.htm?type=command&param=udevice&idx=160&nvalue=0&svalue=23.3;50;2;1024.20;1024&battery=89
void doDHT() {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius
float t = dht.readTemperature();
// Read temperature as Fahrenheit
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;
} else {
// Compute heat index
// Must send in temp in Fahrenheit!
float hi = dht.computeHeatIndex(f, h);
#ifdef DEBUG
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(hi);
Serial.println(" *F");
#endif
}
}
// Prise Eléctrique
//ON 1 1381719 1398103
//ON 2 1394007
//ON 3 1397079 1398103
//
//OFF 1 1381716
//OFF 2 1398103
//OFF 3 1397076
void loop() {
long vcc = readVcc();
barometre();
doDHT();
#ifdef DEBUG
Serial.print("Send");
Serial.println(vcc);
#endif
myMessageSend(idTemp,temperature * 100);
myMessageSend(idPressure,pressure * 10);
myMessageSend(idPression,pression * 10);
// LUX
// R=K*L^-gamma
// R étant la résistance pour un niveau d'éclairement L.
int lum = analogRead(1);
myMessageSend(idLum,(1000.0 * lum / 1024.0));
#ifdef DEBUG
Serial.print("Luminosite=");
Serial.println(lum);
#endif
Narcoleptic.delay(SEND_MESSAGE_DELAY);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
}
void barometre() {
/* See Example: TypeA_WithDIPSwitches */
// mySwitch.switchOn("00001", "10000");
// delay(1000);
// BMP
if (bmp.begin()) {
temperature = bmp.readTemperature();
pressure= bmp.readPressure() / 100.0;
pression = pressure / 101.325;
pression = pression * 0.760 * 100;
// http://en.wikipedia.org/wiki/Atmospheric_pressure#Mean_sea_level_pressure
// Serial.print("Presiure la nivelul marii (calculata) = ");
presiune = bmp.readSealevelPressure(19) / 101.325;
presiune = presiune * 0.760;
#ifdef DEBUG
Serial.print("Temperature="); Serial.println(temperature);
Serial.print("pressure="); Serial.println(pressure);
Serial.print("pression="); Serial.println(pression);
#endif
}
}
void myMessageSend(long id, long value) {
#ifdef DEBUG
Serial.print("Send id="); Serial.print(id);
Serial.print(" value="); Serial.println(value);
#endif
mySwitch.send(activation, 24);
(delai); //delayMicroseconds
mySwitch.send(id, 24); //"000000000001010100010001");
delay(delai);
mySwitch.send(value, 24); //"000000000001010100010001");
delay(delai);
mySwitch.send(desactivation, 24);
delay(delai);
//delay(5000);
delayMicroseconds(TWOTIME*8);
}
//--------------------------------------------------------------------------------------------------
// Read current supply voltage
//--------------------------------------------------------------------------------------------------
long readVcc() {
bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
long result;
// Read 1.1V reference against Vcc
#if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
#endif
// ADCSRB = 0;
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate Vcc in mV
// ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
// analogReference(DEFAULT);
return result; // Vcc in millivolts
}

View File

@@ -0,0 +1,215 @@
#include <RCSwitch.h>
#include <Narcoleptic.h>
#include <Adafruit_BMP085.h>
#include <Wire.h>
#include "DHT.h"
#define DHTPIN A2 // what pin we're connected to
#define DHTTYPE DHT11 // DHT 11
// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);
#define SEND_MESSAGE_DELAY 30000 // Ne pas dépasser 32000 !! Delay in ms between each value's extraction
#define SEND_433_PAUSE 160 // 16 multiple
//#define DEBUG true
const unsigned long activation = 111269;
const unsigned long idTemp=1969;
const unsigned long idPressure=2069;
const unsigned long idPression=2169;
const unsigned long idLum=2269;
const unsigned long idHum=2369;
const unsigned long desactivation = 962111;
const unsigned int delai = 11;
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
// ################# Barometre ####
Adafruit_BMP085 bmp;
// #####################
float temperature = 0.0;
float pressure = 0.0;
float pression = 0.0;
float presiune = 0.0;
float humidite = 0.0;
RCSwitch mySwitch = RCSwitch();
void setup() {
#ifdef DEBUG
Serial.begin(9600);
Serial.println("\n[Oregon V2.1 encoder]");
#endif
pinMode(13, OUTPUT);
mySwitch.enableTransmit(9);
//mySwitch.setRepeatTransmit(2);
// DHT
dht.begin();
}
// Commande pour barometre humidité température
// Virtual Device
// http://192.168.0.10:8080/json.htm?type=command&param=udevice&idx=160&nvalue=0&svalue=23.3;50;2;1024.20;1024&battery=89
void doDHT() {
// 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();
humidite = h;
// Read temperature as Celsius
float t = dht.readTemperature();
// Read temperature as Fahrenheit
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;
} else {
// Compute heat index
// Must send in temp in Fahrenheit!
float hi = dht.computeHeatIndex(f, h);
#ifdef DEBUG
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(hi);
Serial.println(" *F");
#endif
}
}
// Prise Eléctrique
//ON 1 1381719 1398103
//ON 2 1394007
//ON 3 1397079 1398103
//
//OFF 1 1381716
//OFF 2 1398103
//OFF 3 1397076
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(10); // wait for a second
digitalWrite(13, LOW);
long vcc = readVcc();
barometre();
doDHT();
#ifdef DEBUG
Serial.print("Send");
Serial.println(vcc);
#endif
mySwitch.send(activation, 24);
(delai); //delayMicroseconds
myMessageSend(idTemp,temperature * 100);
myMessageSend(idPressure,pressure * 10);
myMessageSend(idPression,pression * 10);
// LUX
// R=K*L^-gamma
// R étant la résistance pour un niveau d'éclairement L.
int lum = analogRead(1);
myMessageSend(idLum,(1000.0 * lum / 1024.0));
myMessageSend(idHum,humidite);
mySwitch.send(desactivation, 24);
delay(delai);
#ifdef DEBUG
Serial.print("Luminosite=");
Serial.println(lum);
delay(delai);
#endif
delayMicroseconds(TWOTIME*8);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
}
void barometre() {
/* See Example: TypeA_WithDIPSwitches */
// mySwitch.switchOn("00001", "10000");
// delay(1000);
// BMP
if (bmp.begin()) {
temperature = bmp.readTemperature();
pressure= bmp.readPressure() / 100.0;
pression = pressure / 101.325;
pression = pression * 0.760 * 100;
// http://en.wikipedia.org/wiki/Atmospheric_pressure#Mean_sea_level_pressure
// Serial.print("Presiure la nivelul marii (calculata) = ");
presiune = bmp.readSealevelPressure(19) / 101.325;
presiune = presiune * 0.760;
#ifdef DEBUG
Serial.print("Temperature="); Serial.println(temperature);
Serial.print("pressure="); Serial.println(pressure);
Serial.print("pression="); Serial.println(pression);
#endif
}
}
void myMessageSend(long id, long value) {
#ifdef DEBUG
Serial.print("Send id="); Serial.print(id);
Serial.print(" value="); Serial.println(value);
#endif
mySwitch.send(id, 24); //"000000000001010100010001");
delay(delai);
mySwitch.send(value, 24); //"000000000001010100010001");
delay(delai);
//delay(5000);
//delayMicroseconds(TWOTIME*8);
}
//--------------------------------------------------------------------------------------------------
// Read current supply voltage
//--------------------------------------------------------------------------------------------------
long readVcc() {
bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
long result;
// Read 1.1V reference against Vcc
#if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
#endif
// ADCSRB = 0;
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate Vcc in mV
// ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
// analogReference(DEFAULT);
return result; // Vcc in millivolts
}

215
ATMEGA_MOTOR/ATMEGA_MOTOR.ino Executable file
View File

@@ -0,0 +1,215 @@
/*
SparkFun Inventor's Kit
Example sketch 12
SPINNING A MOTOR
Use a transistor to spin a motor at different speeds.
We'll also show you how to input data from the serial port
(see the serialSpeed() function below).
Motors are the basis for thousands of things in our daily lives,
and the Arduino can control them. Here we'll use pulse-width
modulation (PWM) to vary the speed of a motor.
The Arduino pins are strong enough to light small LEDs (up to
40 milliAmps), but they're not strong enough to run motors and
other power-hungry parts. (This motor needs 50-100mA).
Because the motor needs more current than an Arduino pin can
provide, we'll use a transistor to do the heavy lifting.
A transistor is a solid-state switch. When we give it a small
amount of current, it can switch a much larger current.
The transistors in your kit (2N2222) can switch up to 200mA.
You can turn a transistor on and off using the digitalWrite()
function, but you can also use the analogWrite() function to
vary the speed of the motor. The analogWrite() function pulses
a pin, varying the width of the pulse from 0% to 100%. We call
this technique "PWM", for "Pulse-Width Modulation".
One thing to keep in mind is that when you lower the speed of
a motor using PWM, you're also reducing the torque (strength)
of the motor. For PWM values below 50 or so, the motor won't have
enough torque to start spinning. It will start spinning when you
raise the speed a bit.
Hardware connections:
Transistor:
The transistor has three pins. Looking at the flat side with the
pins down, the order is COLLECTOR, BASE, EMITTER.
Connect the black wire on the motor to the
COLLECTOR pin on the transistor.
Connect the BASE pin through a 330 Ohm resistor to
digital pin 9.
Connect the EMITTER pin to GND.
Motor:
You've already connected the black wire on the motor to the
COLLECTOR pin on the transistor.
Connect the other (red) wire on the motor to 5V.
Flyback diode:
When the motor is spinning and suddenly turned off, the
magnetic field inside it collapses, generating a voltage spike.
This can damage the transistor. To prevent this, we use a
"flyback diode", which diverts the voltage spike "around" the
transistor.
Connect the side of the diode with the band (cathode) to 5V
Connect the other side of the diode (anode) to the black wire
on the motor.
This sketch was written by SparkFun Electronics,
with lots of help from the Arduino community.
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.
Version 2.0 6/2012 MDG
*/
// We'll be controlling the motor from pin 9.
// This must be one of the PWM-capable pins.
const int motorPin = 9;
void setup()
{
// Set up the motor pin to be an output:
pinMode(motorPin, OUTPUT);
// Set up the serial port:
Serial.begin(9600);
}
void loop()
{
// Here we've used comments to disable some of the examples.
// To try different things, uncomment one of the following lines
// and comment the other ones. See the functions below to learn
// what they do and how they work.
// motorOnThenOff();
// motorOnThenOffWithSpeed();
// motorAcceleration();
serialSpeed();
}
// This function turns the motor on and off like the blinking LED.
// Try different values to affect the timing.
void motorOnThenOff()
{
int onTime = 3000; // milliseconds to turn the motor on
int offTime = 3000; // milliseconds to turn the motor off
digitalWrite(motorPin, HIGH); // turn the motor on (full speed)
delay(onTime); // delay for onTime milliseconds
digitalWrite(motorPin, LOW); // turn the motor off
delay(offTime); // delay for offTime milliseconds
}
// This function alternates between two speeds.
// Try different values to affect the timing and speed.
void motorOnThenOffWithSpeed()
{
int Speed1 = 200; // between 0 (stopped) and 255 (full speed)
int Time1 = 3000; // milliseconds for speed 1
int Speed2 = 50; // between 0 (stopped) and 255 (full speed)
int Time2 = 3000; // milliseconds to turn the motor off
analogWrite(motorPin, Speed1); // turns the motor On
delay(Time1); // delay for onTime milliseconds
analogWrite(motorPin, Speed2); // turns the motor Off
delay(Time2); // delay for offTime milliseconds
}
// This function slowly accelerates the motor to full speed,
// then back down to zero.
void motorAcceleration()
{
int speed;
int delayTime = 20; // milliseconds between each speed step
// accelerate the motor
for(speed = 0; speed <= 255; speed++)
{
analogWrite(motorPin,speed); // set the new speed
delay(delayTime); // delay between speed steps
}
// decelerate the motor
for(speed = 255; speed >= 0; speed--)
{
analogWrite(motorPin,speed); // set the new speed
delay(delayTime); // delay between speed steps
}
}
// This function will let you type a speed into the serial
// monitor window. Open the serial monitor using the magnifying-
// glass icon at the top right of the Arduino window. Then
// type your desired speed into the small text entry bar at the
// top of the window and click "Send" or press return. The motor
// will then operate at that speed. The valid range is 0 to 255.
void serialSpeed()
{
int speed;
Serial.println("Type a speed (0-255) into the box above,");
Serial.println("then click [send] or press [return]");
Serial.println(); // Print a blank line
// In order to type out the above message only once,
// we'll run the rest of this function in an infinite loop:
while(true) // "true" is always true, so this will loop forever.
{
// First we check to see if incoming data is available:
while (Serial.available() > 0)
{
// If it is, we'll use parseInt() to pull out any numbers:
speed = Serial.parseInt();
// Because analogWrite() only works with numbers from
// 0 to 255, we'll be sure the input is in that range:
speed = constrain(speed, 0, 255);
// We'll print out a message to let you know that the
// number was received:
Serial.print("Setting speed to ");
Serial.println(speed);
// And finally, we'll set the speed of the motor!
analogWrite(motorPin, speed);
}
}
}

View File

@@ -0,0 +1,166 @@
// I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class
// 10/7/2011 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
// 2013-05-08 - added multiple output formats
// - added seamless Fastwire support
// 2011-10-07 - initial release
/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2011 Jeff Rowberg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================
*/
// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"
#include "MPU6050.h"
// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 accelgyro;
//MPU6050 accelgyro(0x69); // <-- use for AD0 high
int16_t ax, ay, az;
int16_t gx, gy, gz;
// uncomment "OUTPUT_READABLE_ACCELGYRO" if you want to see a tab-separated
// list of the accel X/Y/Z and then gyro X/Y/Z values in decimal. Easy to read,
// not so easy to parse, and slow(er) over UART.
#define OUTPUT_READABLE_ACCELGYRO
// uncomment "OUTPUT_BINARY_ACCELGYRO" to send all 6 axes of data as 16-bit
// binary, one right after the other. This is very fast (as fast as possible
// without compression or data loss), and easy to parse, but impossible to read
// for a human.
//#define OUTPUT_BINARY_ACCELGYRO
// Assign LED Output PWM Pins
int Red = 11;
int Green = 10;
int Blue = 9;
#define LED_PIN 13
bool blinkState = false;
void setup() {
// LED
pinMode(Red, OUTPUT);
pinMode(Green, OUTPUT);
pinMode(Blue, OUTPUT);
// join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif
// initialize serial communication
// (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
// it's really up to you depending on your project)
Serial.begin(38400);
// initialize device
Serial.println("Initializing I2C devices...");
accelgyro.initialize();
// verify connection
Serial.println("Testing device connections...");
Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");
// use the code below to change accel/gyro offset values
// Serial.println("Updating internal sensor offsets...");
// // -76 -2359 1688 0 0 0
// Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
// Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
// Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
// Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
// Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
// Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
// Serial.print("\n");
// accelgyro.setXGyroOffset(220);
// accelgyro.setYGyroOffset(76);
// accelgyro.setZGyroOffset(-85);
// Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
// Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
// Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
// Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
// Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
// Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
Serial.print("\n");
// configure Arduino LED for
pinMode(LED_PIN, OUTPUT);
}
void loop() {
// read raw accel/gyro measurements from device
accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
// these methods (and a few others) are also available
//accelgyro.getAcceleration(&ax, &ay, &az);
//accelgyro.getRotation(&gx, &gy, &gz);
#ifdef OUTPUT_READABLE_ACCELGYRO
// display tab-separated accel/gyro x/y/z values
Serial.print("a/g:\t");
Serial.print(ax); Serial.print("\t");
Serial.print(ay); Serial.print("\t");
Serial.print(az); Serial.print("\t");
Serial.print(gx); Serial.print("\t");
Serial.print(gy); Serial.print("\t");
Serial.println(gz);
#endif
// #ifdef OUTPUT_BINARY_ACCELGYRO
// Serial.write((uint8_t)(ax >> 8)); Serial.write((uint8_t)(ax & 0xFF));
// Serial.write((uint8_t)(ay >> 8)); Serial.write((uint8_t)(ay & 0xFF));
// Serial.write((uint8_t)(az >> 8)); Serial.write((uint8_t)(az & 0xFF));
// Serial.write((uint8_t)(gx >> 8)); Serial.write((uint8_t)(gx & 0xFF));
// Serial.write((uint8_t)(gy >> 8)); Serial.write((uint8_t)(gy & 0xFF));
// Serial.write((uint8_t)(gz >> 8)); Serial.write((uint8_t)(gz & 0xFF));
// #endif
// blink LED to indicate activity
blinkState = !blinkState;
//digitalWrite(LED_PIN, blinkState);
analogWrite(Red, 255 *(17000 - gx) / 1024);
analogWrite(Green, 255 * (512 - gy) / 1024);
analogWrite(Blue, 255 * (512 - gz) / 1024);
delay(100);
}

69
ATMEGA_NOKIA/ATMEGA_NOKIA.ino Executable file
View File

@@ -0,0 +1,69 @@
#include <Adafruit_GFX.h>
#include <SPI.h>
#include "Adafruit_PCD8544.h"
//Define the pins you are connecting the LCD too.
//PCD8544(SCLK, DIN/MOSI, D/C, SCE/CS, RST);
PCD8544 nokia = PCD8544(3,4,5,7,6);
void setup(void)
{
nokia.init(); //Initialize lcd
// set display to normal mode
nokia.command(PCD8544_DISPLAYCONTROL | PCD8544_DISPLAYNORMAL);
nokia.clear(); //Clear the display
}
void loop(void)
{
// For all functions:
// x range is 0-84
// y range is 0-48
// color is BLACK or WHITE
int pause=2000;
// draw a single pixel
// nokia.setPixel(x, y, color);
nokia.setPixel(30, 30, BLACK);
nokia.display();
delay(pause);
nokia.clear();
// draw line
// nokia.drawline(x1,y1,x2,y2,color); draws a line from (x1,x2) to (y1,y2)
nokia.drawline(5,5,15,40,BLACK);
nokia.display();
delay(pause);
nokia.clear();
// draw rectangle
// nokia.drawrect(x1,y1,x2,y2,color);
//draws a rectange with top left @ (x1,x2) and bottom right @ (y1,y2)
nokia.drawrect(1,1,30,30,BLACK);
nokia.display();
delay(pause);
nokia.clear();
// draw filled rectangle
nokia.fillrect(10,10,20,20,BLACK);
nokia.display();
delay(pause);
nokia.clear();
// draw circle
// nokia.drawcircle(x,y,r,color);
// x,y position with a radius of r
nokia.drawcircle(30,20,5,BLACK);
nokia.display();
delay(pause);
nokia.clear();
// draw filled circle
nokia.fillcircle(10,10,5,BLACK);
nokia.display();
delay(pause);
nokia.clear();
}

277
ATMEGA_NOKIA2/ATMEGA_NOKIA2.ino Executable file
View File

@@ -0,0 +1,277 @@
// Sources:
// http://playground.arduino.cc/Code/PCD8544
// http://dlnmh9ip6v2uc.cloudfront.net/datasheets/LCD/Monochrome/Nokia_5110_Example.pde
// http://forum.arduino.cc/index.php?topic=176794.0
#include <SPI.h> // We'll use SPI to transfer data. Faster!
#define PIN_SCE 4
#define PIN_RESET 3
#define PIN_DC 5
#define PIN_SDIN 6
#define PIN_SCLK 7
#define PIN_LCD 9 // backlight
#define PIN_FADER 1 // analog
#define PIN_TMP 0 // analog
#define LCD_C LOW
#define LCD_D HIGH
#define LCD_COMMAND 0
#define LCD_X 84
#define LCD_Y 48
long contrast = 200;
char strBuffer[30];
int txtCyclesMax = 20;
int txtCyclesCur = 0;
static const byte ASCII[][5] =
{
{0x00, 0x00, 0x00, 0x00, 0x00} // 20
,{0x00, 0x00, 0x5f, 0x00, 0x00} // 21 !
,{0x00, 0x07, 0x00, 0x07, 0x00} // 22 "
,{0x14, 0x7f, 0x14, 0x7f, 0x14} // 23 #
,{0x24, 0x2a, 0x7f, 0x2a, 0x12} // 24 $
,{0x23, 0x13, 0x08, 0x64, 0x62} // 25 %
,{0x36, 0x49, 0x55, 0x22, 0x50} // 26 &
,{0x00, 0x05, 0x03, 0x00, 0x00} // 27 '
,{0x00, 0x1c, 0x22, 0x41, 0x00} // 28 (
,{0x00, 0x41, 0x22, 0x1c, 0x00} // 29 )
,{0x14, 0x08, 0x3e, 0x08, 0x14} // 2a *
,{0x08, 0x08, 0x3e, 0x08, 0x08} // 2b +
,{0x00, 0x50, 0x30, 0x00, 0x00} // 2c ,
,{0x08, 0x08, 0x08, 0x08, 0x08} // 2d -
,{0x00, 0x60, 0x60, 0x00, 0x00} // 2e .
,{0x20, 0x10, 0x08, 0x04, 0x02} // 2f backslash
,{0x3e, 0x51, 0x49, 0x45, 0x3e} // 30 0
,{0x00, 0x42, 0x7f, 0x40, 0x00} // 31 1
,{0x42, 0x61, 0x51, 0x49, 0x46} // 32 2
,{0x21, 0x41, 0x45, 0x4b, 0x31} // 33 3
,{0x18, 0x14, 0x12, 0x7f, 0x10} // 34 4
,{0x27, 0x45, 0x45, 0x45, 0x39} // 35 5
,{0x3c, 0x4a, 0x49, 0x49, 0x30} // 36 6
,{0x01, 0x71, 0x09, 0x05, 0x03} // 37 7
,{0x36, 0x49, 0x49, 0x49, 0x36} // 38 8
,{0x06, 0x49, 0x49, 0x29, 0x1e} // 39 9
,{0x00, 0x36, 0x36, 0x00, 0x00} // 3a :
,{0x00, 0x56, 0x36, 0x00, 0x00} // 3b ;
,{0x08, 0x14, 0x22, 0x41, 0x00} // 3c <
,{0x14, 0x14, 0x14, 0x14, 0x14} // 3d =
,{0x00, 0x41, 0x22, 0x14, 0x08} // 3e >
,{0x02, 0x01, 0x51, 0x09, 0x06} // 3f ?
,{0x32, 0x49, 0x79, 0x41, 0x3e} // 40 @
,{0x7e, 0x11, 0x11, 0x11, 0x7e} // 41 A
,{0x7f, 0x49, 0x49, 0x49, 0x36} // 42 B
,{0x3e, 0x41, 0x41, 0x41, 0x22} // 43 C
,{0x7f, 0x41, 0x41, 0x22, 0x1c} // 44 D
,{0x7f, 0x49, 0x49, 0x49, 0x41} // 45 E
,{0x7f, 0x09, 0x09, 0x09, 0x01} // 46 F
,{0x3e, 0x41, 0x49, 0x49, 0x7a} // 47 G
,{0x7f, 0x08, 0x08, 0x08, 0x7f} // 48 H
,{0x00, 0x41, 0x7f, 0x41, 0x00} // 49 I
,{0x20, 0x40, 0x41, 0x3f, 0x01} // 4a J
,{0x7f, 0x08, 0x14, 0x22, 0x41} // 4b K
,{0x7f, 0x40, 0x40, 0x40, 0x40} // 4c L
,{0x7f, 0x02, 0x0c, 0x02, 0x7f} // 4d M
,{0x7f, 0x04, 0x08, 0x10, 0x7f} // 4e N
,{0x3e, 0x41, 0x41, 0x41, 0x3e} // 4f O
,{0x7f, 0x09, 0x09, 0x09, 0x06} // 50 P
,{0x3e, 0x41, 0x51, 0x21, 0x5e} // 51 Q
,{0x7f, 0x09, 0x19, 0x29, 0x46} // 52 R
,{0x46, 0x49, 0x49, 0x49, 0x31} // 53 S
,{0x01, 0x01, 0x7f, 0x01, 0x01} // 54 T
,{0x3f, 0x40, 0x40, 0x40, 0x3f} // 55 U
,{0x1f, 0x20, 0x40, 0x20, 0x1f} // 56 V
,{0x3f, 0x40, 0x38, 0x40, 0x3f} // 57 W
,{0x63, 0x14, 0x08, 0x14, 0x63} // 58 X
,{0x07, 0x08, 0x70, 0x08, 0x07} // 59 Y
,{0x61, 0x51, 0x49, 0x45, 0x43} // 5a Z
,{0x00, 0x7f, 0x41, 0x41, 0x00} // 5b [
,{0x02, 0x04, 0x08, 0x10, 0x20} // 5c ¥
,{0x00, 0x41, 0x41, 0x7f, 0x00} // 5d ]
,{0x04, 0x02, 0x01, 0x02, 0x04} // 5e ^
,{0x40, 0x40, 0x40, 0x40, 0x40} // 5f _
,{0x00, 0x01, 0x02, 0x04, 0x00} // 60 `
,{0x20, 0x54, 0x54, 0x54, 0x78} // 61 a
,{0x7f, 0x48, 0x44, 0x44, 0x38} // 62 b
,{0x38, 0x44, 0x44, 0x44, 0x20} // 63 c
,{0x38, 0x44, 0x44, 0x48, 0x7f} // 64 d
,{0x38, 0x54, 0x54, 0x54, 0x18} // 65 e
,{0x08, 0x7e, 0x09, 0x01, 0x02} // 66 f
,{0x0c, 0x52, 0x52, 0x52, 0x3e} // 67 g
,{0x7f, 0x08, 0x04, 0x04, 0x78} // 68 h
,{0x00, 0x44, 0x7d, 0x40, 0x00} // 69 i
,{0x20, 0x40, 0x44, 0x3d, 0x00} // 6a j
,{0x7f, 0x10, 0x28, 0x44, 0x00} // 6b k
,{0x00, 0x41, 0x7f, 0x40, 0x00} // 6c l
,{0x7c, 0x04, 0x18, 0x04, 0x78} // 6d m
,{0x7c, 0x08, 0x04, 0x04, 0x78} // 6e n
,{0x38, 0x44, 0x44, 0x44, 0x38} // 6f o
,{0x7c, 0x14, 0x14, 0x14, 0x08} // 70 p
,{0x08, 0x14, 0x14, 0x18, 0x7c} // 71 q
,{0x7c, 0x08, 0x04, 0x04, 0x08} // 72 r
,{0x48, 0x54, 0x54, 0x54, 0x20} // 73 s
,{0x04, 0x3f, 0x44, 0x40, 0x20} // 74 t
,{0x3c, 0x40, 0x40, 0x20, 0x7c} // 75 u
,{0x1c, 0x20, 0x40, 0x20, 0x1c} // 76 v
,{0x3c, 0x40, 0x30, 0x40, 0x3c} // 77 w
,{0x44, 0x28, 0x10, 0x28, 0x44} // 78 x
,{0x0c, 0x50, 0x50, 0x50, 0x3c} // 79 y
,{0x44, 0x64, 0x54, 0x4c, 0x44} // 7a z
,{0x00, 0x08, 0x36, 0x41, 0x00} // 7b {
,{0x00, 0x00, 0x7f, 0x00, 0x00} // 7c |
,{0x00, 0x41, 0x36, 0x08, 0x00} // 7d }
,{0x10, 0x08, 0x08, 0x10, 0x08} // 7e ←
,{0x78, 0x46, 0x41, 0x46, 0x78} // 7f →
};
void LcdCharacter(char character)
{
LcdWrite(LCD_D, 0x00);
for (int index = 0; index < 5; index++)
{
LcdWrite(LCD_D, ASCII[character - 0x20][index]);
}
LcdWrite(LCD_D, 0x00);
}
void LcdClear(void)
{
for (int index = 0; index < LCD_X * LCD_Y / 8; index++)
{
LcdWrite(LCD_D, 0x00);
}
}
void LcdInitialise(void)
{
pinMode(PIN_SCE, OUTPUT);
pinMode(PIN_RESET, OUTPUT);
pinMode(PIN_DC, OUTPUT);
pinMode(PIN_SDIN, OUTPUT);
pinMode(PIN_SCLK, OUTPUT);
pinMode(PIN_LCD, OUTPUT);
digitalWrite(PIN_LCD, HIGH);
digitalWrite(PIN_RESET, LOW);
digitalWrite(PIN_RESET, HIGH);
LcdWrite(LCD_C, 0x21 ); // LCD Extended Commands.
LcdWrite(LCD_C, 0x94 ); // Set LCD Vop (Contrast).
LcdWrite(LCD_C, 0x04 ); // Set Temp coefficent. //0x04
LcdWrite(LCD_C, 0x14 ); // LCD bias mode 1:48. //0x13
LcdWrite(LCD_C, 0x0C ); // LCD in normal mode.
LcdWrite(LCD_C, 0x20 );
LcdWrite(LCD_C, 0x0C );
}
void LcdString(char *characters)
{
while (*characters)
{
LcdCharacter(*characters++);
}
}
void LcdWrite(byte dc, byte data)
{
digitalWrite(PIN_DC, dc);
digitalWrite(PIN_SCE, LOW);
shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
digitalWrite(PIN_SCE, HIGH);
}
void setup(void)
{
// pinMode(PIN_TMP, INPUT);
// pinMode(PIN_FADER, INPUT);
Serial.begin(9600);
Serial.println("TOTO");
LcdInitialise();
Serial.println("TOTO");
LcdClear();
Serial.println("TOTO");
LcdString("Starting");
//contrast = 0;
}
void loop(void)
{
delay(10);
// long contrast = analogRead(PIN_FADER);
//contrast = (contrast * 255)/1024;
//
Serial.print("Contrast:");
Serial.println(contrast);
txtCyclesCur = txtCyclesCur + 1;
setContrast(contrast);
if (txtCyclesCur > txtCyclesMax) {
// contrast+=10;
LcdClear();
float voltage, degreesC1, degreesC2, degreesC3, degreesF1, degreesF2, degreesF3, fractionC, fractionF;
voltage = getVoltage(PIN_TMP);
degreesC1 = (voltage - 0.5) * 1000.0;
degreesC2 = (voltage - 0.5) * 100.0;
degreesC3 = (voltage - 0.5) * 10.0;
fractionC = degreesC1 - ((int)degreesC3 * 100.0);
degreesF1 = degreesC3 * (9.0/5.0) + 32.0;
degreesF2 = degreesF1 * 100.0;
fractionF = degreesF2 - ((int)degreesF1 * 100.0);
/*
Serial.print("trust:");
Serial.println(strBuffer);
Serial.println(voltage);
Serial.println(degreesC3);
Serial.println(fractionC);
Serial.println(degreesF1);
Serial.println(fractionF);
*/
gotoXY(0,10);
LcdString("TEMP ");
itoa(degreesC3,strBuffer,10);
LcdString(strBuffer);
itoa(fractionC,strBuffer,10);
LcdString(".");
LcdString(strBuffer);
LcdString("C ");
itoa(degreesF1,strBuffer,10);
gotoXY(0,20);
LcdString(strBuffer);
itoa(fractionF,strBuffer,10);
LcdString(".");
LcdString(strBuffer);
LcdString("F");
itoa(contrast,strBuffer,10);
delay(1000);
gotoXY(0,0);
LcdString("BACKLT ");
LcdString(strBuffer);
txtCyclesCur = 0;
delay(1000);
}
}
void setContrast(byte contrast)
{
analogWrite(PIN_LCD, contrast);
}
void gotoXY(int x, int y)
{
LcdWrite( 0, 0x80 | x); // Column.
LcdWrite( 0, 0x40 | y); // Row.
}
float getVoltage(int pin)
{
return (analogRead(pin) * 0.004882814);
}

605
ATMEGA_NOKIA4/ATMEGA_NOKIA4.ino Executable file
View File

@@ -0,0 +1,605 @@
#define PIN_SCE 7
#define PIN_RESET 6
#define PIN_DC 5
#define PIN_SDIN 4
#define PIN_SCLK 3
#define LCD_C LOW
#define LCD_D HIGH
#define LCD_X 84
#define LCD_Y 48
#define LCD_DATA 1
byte ASCII[][5] =
{
{0x00, 0x00, 0x00, 0x00, 0x00} // 20
,{0x00, 0x00, 0x5f, 0x00, 0x00} // 21 !
,{0x00, 0x07, 0x00, 0x07, 0x00} // 22 "
,{0x14, 0x7f, 0x14, 0x7f, 0x14} // 23 #
,{0x24, 0x2a, 0x7f, 0x2a, 0x12} // 24 $
,{0x23, 0x13, 0x08, 0x64, 0x62} // 25 %
,{0x36, 0x49, 0x55, 0x22, 0x50} // 26 &
,{0x00, 0x05, 0x03, 0x00, 0x00} // 27 '
,{0x00, 0x1c, 0x22, 0x41, 0x00} // 28 (
,{0x00, 0x41, 0x22, 0x1c, 0x00} // 29 )
,{0x14, 0x08, 0x3e, 0x08, 0x14} // 2a *
,{0x08, 0x08, 0x3e, 0x08, 0x08} // 2b +
,{0x00, 0x50, 0x30, 0x00, 0x00} // 2c ,
,{0x08, 0x08, 0x08, 0x08, 0x08} // 2d -
,{0x00, 0x60, 0x60, 0x00, 0x00} // 2e .
,{0x20, 0x10, 0x08, 0x04, 0x02} // 2f /
,{0x3e, 0x51, 0x49, 0x45, 0x3e} // 30 0
,{0x00, 0x42, 0x7f, 0x40, 0x00} // 31 1
,{0x42, 0x61, 0x51, 0x49, 0x46} // 32 2
,{0x21, 0x41, 0x45, 0x4b, 0x31} // 33 3
,{0x18, 0x14, 0x12, 0x7f, 0x10} // 34 4
,{0x27, 0x45, 0x45, 0x45, 0x39} // 35 5
,{0x3c, 0x4a, 0x49, 0x49, 0x30} // 36 6
,{0x01, 0x71, 0x09, 0x05, 0x03} // 37 7
,{0x36, 0x49, 0x49, 0x49, 0x36} // 38 8
,{0x06, 0x49, 0x49, 0x29, 0x1e} // 39 9
,{0x00, 0x36, 0x36, 0x00, 0x00} // 3a :
,{0x00, 0x56, 0x36, 0x00, 0x00} // 3b ;
,{0x08, 0x14, 0x22, 0x41, 0x00} // 3c <
,{0x14, 0x14, 0x14, 0x14, 0x14} // 3d =
,{0x00, 0x41, 0x22, 0x14, 0x08} // 3e >
,{0x02, 0x01, 0x51, 0x09, 0x06} // 3f ?
,{0x32, 0x49, 0x79, 0x41, 0x3e} // 40 @
,{0x7e, 0x11, 0x11, 0x11, 0x7e} // 41 A
,{0x7f, 0x49, 0x49, 0x49, 0x36} // 42 B
,{0x3e, 0x41, 0x41, 0x41, 0x22} // 43 C
,{0x7f, 0x41, 0x41, 0x22, 0x1c} // 44 D
,{0x7f, 0x49, 0x49, 0x49, 0x41} // 45 E
,{0x7f, 0x09, 0x09, 0x09, 0x01} // 46 F
,{0x3e, 0x41, 0x49, 0x49, 0x7a} // 47 G
,{0x7f, 0x08, 0x08, 0x08, 0x7f} // 48 H
,{0x00, 0x41, 0x7f, 0x41, 0x00} // 49 I
,{0x20, 0x40, 0x41, 0x3f, 0x01} // 4a J
,{0x7f, 0x08, 0x14, 0x22, 0x41} // 4b K
,{0x7f, 0x40, 0x40, 0x40, 0x40} // 4c L
,{0x7f, 0x02, 0x0c, 0x02, 0x7f} // 4d M
,{0x7f, 0x04, 0x08, 0x10, 0x7f} // 4e N
,{0x3e, 0x41, 0x41, 0x41, 0x3e} // 4f O
,{0x7f, 0x09, 0x09, 0x09, 0x06} // 50 P
,{0x3e, 0x41, 0x51, 0x21, 0x5e} // 51 Q
,{0x7f, 0x09, 0x19, 0x29, 0x46} // 52 R
,{0x46, 0x49, 0x49, 0x49, 0x31} // 53 S
,{0x01, 0x01, 0x7f, 0x01, 0x01} // 54 T
,{0x3f, 0x40, 0x40, 0x40, 0x3f} // 55 U
,{0x1f, 0x20, 0x40, 0x20, 0x1f} // 56 V
,{0x3f, 0x40, 0x38, 0x40, 0x3f} // 57 W
,{0x63, 0x14, 0x08, 0x14, 0x63} // 58 X
,{0x07, 0x08, 0x70, 0x08, 0x07} // 59 Y
,{0x61, 0x51, 0x49, 0x45, 0x43} // 5a Z
,{0x00, 0x7f, 0x41, 0x41, 0x00} // 5b [
,{0x02, 0x04, 0x08, 0x10, 0x20} // 5c ¥
,{0x00, 0x41, 0x41, 0x7f, 0x00} // 5d ]
,{0x04, 0x02, 0x01, 0x02, 0x04} // 5e ^
,{0x40, 0x40, 0x40, 0x40, 0x40} // 5f _
,{0x00, 0x01, 0x02, 0x04, 0x00} // 60 `
,{0x20, 0x54, 0x54, 0x54, 0x78} // 61 a
,{0x7f, 0x48, 0x44, 0x44, 0x38} // 62 b
,{0x38, 0x44, 0x44, 0x44, 0x20} // 63 c
,{0x38, 0x44, 0x44, 0x48, 0x7f} // 64 d
,{0x38, 0x54, 0x54, 0x54, 0x18} // 65 e
,{0x08, 0x7e, 0x09, 0x01, 0x02} // 66 f
,{0x0c, 0x52, 0x52, 0x52, 0x3e} // 67 g
,{0x7f, 0x08, 0x04, 0x04, 0x78} // 68 h
,{0x00, 0x44, 0x7d, 0x40, 0x00} // 69 i
,{0x20, 0x40, 0x44, 0x3d, 0x00} // 6a j
,{0x7f, 0x10, 0x28, 0x44, 0x00} // 6b k
,{0x00, 0x41, 0x7f, 0x40, 0x00} // 6c l
,{0x7c, 0x04, 0x18, 0x04, 0x78} // 6d m
,{0x7c, 0x08, 0x04, 0x04, 0x78} // 6e n
,{0x38, 0x44, 0x44, 0x44, 0x38} // 6f o
,{0x7c, 0x14, 0x14, 0x14, 0x08} // 70 p
,{0x08, 0x14, 0x14, 0x18, 0x7c} // 71 q
,{0x7c, 0x08, 0x04, 0x04, 0x08} // 72 r
,{0x48, 0x54, 0x54, 0x54, 0x20} // 73 s
,{0x04, 0x3f, 0x44, 0x40, 0x20} // 74 t
,{0x3c, 0x40, 0x40, 0x20, 0x7c} // 75 u
,{0x1c, 0x20, 0x40, 0x20, 0x1c} // 76 v
,{0x3c, 0x40, 0x30, 0x40, 0x3c} // 77 w
,{0x44, 0x28, 0x10, 0x28, 0x44} // 78 x
,{0x0c, 0x50, 0x50, 0x50, 0x3c} // 79 y
,{0x44, 0x64, 0x54, 0x4c, 0x44} // 7a z
,{0x00, 0x08, 0x36, 0x41, 0x00} // 7b {
,{0xff, 0xff, 0xff, 0xff, 0xff} // 7c | modified
,{0x1c, 0xf6, 0x3f, 0xf6, 0x1c} // 7d } modified
,{0x10, 0x08, 0x08, 0x10, 0x08} // 7e ?
,{0x78, 0x46, 0x41, 0x46, 0x78} // 7f ?
};
byte arduinox [] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xE0, 0xF0, 0xF0,0xF0, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF0, 0xF0, 0xF0, 0xE0,
0xC0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xC0,0xE0, 0xE0, 0xF0, 0xF0, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF0,
0xF0, 0xF0, 0xE0, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xF0, 0xFC, 0xFE, 0xFF, 0xFF, 0x7F,
0x1F, 0x0F, 0x07, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01,0x03, 0x03, 0x07, 0x0F, 0x0F, 0x3F, 0x7F, 0xFF, 0xFE, 0xFC, 0xF8, 0xF0, 0xF0, 0xF8, 0xFC, 0xFE,
0xFF, 0x7F, 0x3F, 0x1F, 0x0F, 0x07, 0x03, 0x03, 0x01, 0x01, 0x00, 0x00, 0xE0, 0xE0, 0xE0, 0x00,0x00, 0x01, 0x01, 0x03, 0x03, 0x07, 0x0F, 0x1F, 0x7F, 0xFF, 0xFF, 0xFE, 0xFC, 0xF0, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0xFF, 0xFF,0xFF, 0xFF, 0xFF, 0xE0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E,
0x0E, 0x0E, 0x0E, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF,0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0xE0, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x0E, 0x0E, 0x0F,
0x7F, 0x7F, 0x7F, 0x0E, 0x0E, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xE0, 0xFF, 0xFF, 0xFF,0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0x7F, 0xFE, 0xFC, 0xF8, 0xF8, 0xF8, 0xF0,0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF8, 0xF8, 0xFC, 0xFC, 0xFE, 0x7F, 0x7F, 0x3F, 0x1F, 0x0F,
0x0F, 0x07, 0x01, 0x00, 0x00, 0x01, 0x07, 0x0F, 0x0F, 0x1F, 0x3F, 0x7F, 0x7F, 0xFE, 0xFC, 0xFC,0xF8, 0xF8, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF8, 0xF8, 0xF8, 0xFC, 0xFE, 0x7F, 0x7F,
0x3F, 0x1F, 0x0F, 0x07, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00,
0x00, 0xC1, 0xC1, 0xC1, 0x41, 0xC1, 0xC1, 0xC1, 0x01, 0x01, 0x01, 0xC1, 0xC0, 0x40, 0xC0, 0xC0,0xC0, 0x80, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0xC0, 0xC0,
0xC0, 0xC0, 0xC0, 0xC0, 0xC1, 0x01, 0x01, 0xC1, 0xC1, 0xC1, 0x81, 0x01, 0x01, 0xC1, 0xC1, 0x00,0x00, 0x80, 0xC0, 0xC0, 0x40, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x7C, 0x3F, 0x1B, 0x19,0x1F, 0x7E, 0x70, 0x00, 0x00, 0x3F, 0x7F, 0x0C, 0x0C, 0x1C, 0x7F, 0x77, 0x00, 0x00, 0x00, 0x7F,
0x7F, 0x60, 0x60, 0x30, 0x3F, 0x1F, 0x00, 0x00, 0x1F, 0x3F, 0x7F, 0x60, 0x60, 0x7F, 0x3F, 0x1F,0x00, 0x00, 0x60, 0x60, 0x7F, 0x7F, 0x7F, 0x60, 0x60, 0x00, 0x00, 0x3F, 0x7F, 0x03, 0x07, 0x0E,
0x3C, 0x7F, 0x7F, 0x00, 0x00, 0x1F, 0x3F, 0x70, 0x60, 0x60, 0x3F, 0x3F, 0x0F, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
byte splash[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0xE0, 0xE0, 0x00, 0x00, 0x00, 0xC0, 0xE0, 0xC0, 0x01, 0x01, 0x01, 0xC1, 0xE1, 0xC1,
0x01, 0xC1, 0xE1, 0x41, 0x01, 0x03, 0x03, 0x03, 0x03, 0xE3, 0xE3, 0x03, 0x03, 0x03, 0x03, 0x07,0xC7, 0xE7, 0xC7, 0x07, 0x07, 0x07, 0xE7, 0xC7, 0xC7, 0x0F, 0xCF, 0xCF, 0x0F, 0x0F, 0x8F, 0xCF,
0xEF, 0xEF, 0xCF, 0x0F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1E, 0x3E, 0x3E,0x3E, 0x3E, 0x3E, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x80, 0xFE, 0xFF, 0x1F, 0xC0, 0xE0, 0xFC, 0xFF, 0xFF, 0xFF, 0x00, 0x00,0xF0, 0xFF, 0x7F, 0xFF, 0xFC, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0x1F, 0x00,
0x00, 0xC0, 0xF0, 0xFE, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xF8, 0xFF, 0x7F, 0xFF, 0xFC, 0xFF, 0x1F,0x00, 0xFC, 0xFF, 0x0F, 0xE1, 0xE7, 0xE7, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x3F, 0x0F, 0x00, 0x3F, 0x3F, 0x07, 0x03,
0x3F, 0x3F, 0x00, 0x10, 0x3F, 0x1F, 0x00, 0x1F, 0x3F, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E,0x3F, 0x3F, 0x3C, 0x3C, 0x08, 0x3F, 0x3F, 0x03, 0x03, 0x3F, 0x3F, 0x00, 0x3E, 0x3F, 0x0F, 0x00,
0x1F, 0x3F, 0x0F, 0x00, 0x00, 0x1F, 0x3F, 0x3C, 0x3F, 0x0F, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0x00, 0x00, 0xF0, 0xF0, 0x00, 0x00, 0x00, 0xF0,0xF0, 0xF0, 0xF0, 0xF0, 0x70, 0x00, 0xC0, 0xE0, 0xF0, 0xF0, 0xE0, 0x00, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xE0, 0x00, 0x00, 0x80, 0xE0, 0xF0, 0xF0, 0xE0, 0xF0,0x00, 0x00, 0xE0, 0xF0, 0xE0, 0x00, 0xE0, 0xF0, 0x60, 0x00, 0xC0, 0xF0, 0xF0, 0x00, 0x00, 0xE0,
0xF0, 0xF0, 0xF0, 0xE0, 0x00, 0xC0, 0xE0, 0xF0, 0xF0, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0x7F, 0x78, 0x78, 0x00, 0xC0, 0xFF, 0xFF, 0x07,
0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x7E, 0x78, 0x38, 0x00, 0xFE, 0xFF, 0x0F, 0xC0, 0xC3, 0x03, 0x00,0x00, 0xF8, 0xFF, 0x1F, 0x00, 0x00, 0xF9, 0xFF, 0xFE, 0xF0, 0x7F, 0x1F, 0x00, 0xF8, 0xFF, 0xFF,
0x01, 0xE0, 0xFF, 0x7F, 0x00, 0xF0, 0xFF, 0x3F, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0xE0, 0xFF, 0xFF,0x03, 0x00, 0xFF, 0xFF, 0x03, 0xC3, 0xC3, 0x01, 0x80, 0x8F, 0xFF, 0xFD, 0xE1, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xF0, 0xF0, 0xF0, 0xE0, 0xE0, 0xE0, 0xFF, 0xFF, 0xFE, 0xFE, 0xE4, 0xE0,0xE7, 0xFF, 0xDF, 0xDE, 0xDE, 0xC0, 0xCF, 0xDF, 0xDE, 0xDE, 0xDE, 0xC0, 0x80, 0x8F, 0x9F, 0x9F,
0x8F, 0x83, 0x80, 0x80, 0x8E, 0x9F, 0x0F, 0x00, 0x00, 0x08, 0x1F, 0x1F, 0x03, 0x1F, 0x3F, 0x18,0x00, 0x03, 0x0F, 0x1F, 0x1F, 0x0F, 0x03, 0x00, 0x00, 0x1F, 0x1F, 0x00, 0x07, 0x1F, 0x1F, 0x00,
0x00, 0x1F, 0x1F, 0x03, 0x00, 0x00, 0x0F, 0x1F, 0x1F, 0x0F, 0x01, 0x00, 0x1F, 0x1F, 0x1F, 0x0F,0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
void splashpage(){
LcdClear();
LcdInitialise(); for (int index = 0 ; index < (LCD_X * LCD_Y / 8) ; index++){
digitalWrite(PIN_DC,1); digitalWrite(PIN_SCE, LOW); shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, splash[index]);
digitalWrite(PIN_SCE, HIGH);} delay(3000);knockdown();}
void arduinopage(){ LcdClear(); LcdInitialise(); for (int index = 0 ; index < (LCD_X * LCD_Y / 8) ; index++){
digitalWrite(PIN_DC,1); digitalWrite(PIN_SCE, LOW);
shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, arduinox[index]); digitalWrite(PIN_SCE, HIGH);}
delay(3000);}
void knockdown(){
for (int index = 0 ; index < 72 ; index++){
LcdString(" ");delay(20);}}
void LcdCharacter(char character){
LcdWrite(LCD_D, 0x00); for (int index = 0; index < 5; index++)
{ LcdWrite(LCD_D, ASCII[character - 0x20][index]); } LcdWrite(LCD_D, 0x00);}
void LcdClear(void){ for (int index = 0; index < 504; index++) { LcdWrite(LCD_D, 0x00);}}
void LcdInitialise(void)
{ pinMode(PIN_SCE, OUTPUT);
pinMode(PIN_RESET, OUTPUT);
pinMode(PIN_DC, OUTPUT);
pinMode(PIN_SDIN, OUTPUT);
pinMode(PIN_SCLK, OUTPUT);
digitalWrite(PIN_RESET, LOW);
digitalWrite(PIN_RESET, HIGH);
LcdWrite(LCD_C, 0x21 ); // LCD Extended Commands.
LcdWrite(LCD_C, 0xB5 ); // Set LCD Vop (Contrast).
LcdWrite(LCD_C, 0x14 ); // LCD bias mode 1:48. //0x13
LcdWrite(LCD_C, 0x20 );
LcdWrite(LCD_C, 0x0C );
}
void LcdString(char *characters)
{ while (*characters) {
LcdCharacter(*characters++);}}
void LcdWrite(byte dc, byte data)
{ digitalWrite(PIN_DC, dc);
digitalWrite(PIN_SCE, LOW);
shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
digitalWrite(PIN_SCE, HIGH);}
void posmarker(int x, int y){
LcdWrite( 0, 0x80 | x); // Column.
LcdWrite( 0, 0x40 | y); // Row
}
void rectangle(){
unsigned char j;
for(j=0; j<84; j++) // top
{ posmarker (j,0);
LcdWrite (1,0x01);}
for(j=0; j<84; j++) //Bottom
{posmarker (j,5);
LcdWrite (1,0x80);}
for(j=0; j<6; j++) // Right
{posmarker (83,j);
LcdWrite (1,0xff);}
for(j=0; j<6; j++) // Left
{posmarker (0,j);
LcdWrite (1,0xff);}}
void setup(void)
{LcdInitialise();LcdClear();LcdString(" ");
LcdString(" Ian Lang ");
LcdString( " Electronics ");
LcdString("Presents...");
delay(2000); splashpage(); LcdClear(); LcdInitialise();
LcdString(" LCD DEMO");delay(2000);
LcdString(" "); LcdString("for text and "); LcdString(" graphics.");
delay(3000);}
void loop(void){
delay(500); LcdClear();LcdInitialise();
LcdString("The original intention of your LCD was as Nokia 5110 phone screens...");delay(5000);
LcdClear();LcdInitialise();
LcdString(" "); LcdString(" But it can be used on your Arduino too.");delay(5000);
arduinopage(); delay(5000);LcdClear(); LcdInitialise();
LcdString("Let's make a box and put some text in it....");delay(5000);LcdClear(); LcdInitialise();
rectangle();delay(2000);posmarker(18,2);////////18th PIXEL not bank and third row
LcdCharacter('A'); LcdCharacter('r'); LcdCharacter('d'); LcdCharacter('u'); LcdCharacter('i'); LcdCharacter('n');
LcdCharacter('o'); delay(3000);knockdown();delay(500); LcdInitialise();
LcdString(" ");LcdString(" How about smaller boxes?");delay(3000);
LcdClear();LcdInitialise();LcdString(" ");LcdString(" No problem.");
for(int j=0; j<84; j++) // top
{ posmarker (j,0); LcdWrite (1,0x01);}
for(int j=0; j<84; j++) //Bottom
{posmarker (j,2);LcdWrite (1,0x80);}
for(int j=0; j<3; j++) // Right
{posmarker (83,j);LcdWrite (1,0xff);}
for(int j=0; j<3; j++) // Left
{posmarker (0,j);LcdWrite (1,0xff);}
delay(1000);
for(int j=0; j<36; j++) // top
{ posmarker (j,4);
LcdWrite (1,0x01);}
for(int j=0; j<36; j++) //Bottom
{ posmarker (j,5);
LcdWrite (1,0x80);}
for(int j=4; j<6; j++) // Right
{ posmarker (35,j);
LcdWrite (1,0xff);}
for(int j=4; j<6; j++) // Left
{posmarker (0,j);
LcdWrite (1,0xff);}delay(1000);
for(int j=40; j<84; j++) // top
{ posmarker (j,4);
LcdWrite (1,0x01);}
for(int j=40; j<84; j++) //Bottom
{posmarker (j,5);
LcdWrite (1,0x80);}
for(int j=4; j<6; j++) // Right
{posmarker (83,j);
LcdWrite (1,0xff);}
for(int j=4; j<6; j++) // Left
{posmarker (40,j);
LcdWrite (1,0xff);}
delay(3000);LcdClear();LcdInitialise();
LcdString(" Let's do some text effects...");
delay(3000); LcdClear(); LcdInitialise(); for (int index = 0 ; index < 72 ; index++){
LcdString("|");delay(20);} LcdInitialise(); for (int index = 0 ; index<72 ; index++){
LcdString(" ");delay(20);} delay(500);int drop=200; for(int j=0;j<4;j++){
posmarker(18,j);LcdCharacter('D');posmarker(18,j-1);LcdCharacter(' ');delay(drop);}
for(int j=0;j<4;j++){
posmarker(25,j);LcdCharacter('r');posmarker(25,j-1);LcdCharacter(' ');delay(drop);}
for(int j=0;j<4;j++){
posmarker(32,j);LcdCharacter('o');posmarker(32,j-1);LcdCharacter(' ');delay(drop);}
for(int j=0;j<4;j++){
posmarker(39,j);LcdCharacter('p');posmarker(39,j-1);LcdCharacter(' ');delay(drop);}
posmarker(46,3);LcdCharacter(' ');
for(int j=0;j<4;j++){
posmarker(53,j);LcdCharacter('i');posmarker(53,j-1);LcdCharacter(' ');delay(drop);}
for(int j=0;j<4;j++){
posmarker(60,j);LcdCharacter('n');posmarker(60,j-1);LcdCharacter(' ');delay(drop);}
delay(2000);
for(int j=3;j>-1;j--){
posmarker(18,j);LcdCharacter('D');posmarker(18,j+1);LcdCharacter(' ');delay(drop);}
for(int j=3;j>-1;j--){
posmarker(25,j);LcdCharacter('r');posmarker(25,j+1);LcdCharacter(' ');delay(drop);}
for(int j=3;j>-1;j--){
posmarker(32,j);LcdCharacter('o');posmarker(32,j+1);LcdCharacter(' ');delay(drop);}
for(int j=3;j>-1;j--){
posmarker(39,j);LcdCharacter('p');posmarker(39,j+1);LcdCharacter(' ');delay(drop);}
posmarker(46,3);LcdCharacter(' ');
for(int j=3;j>-1;j--){
posmarker(53,j);LcdCharacter('i');posmarker(53,j+1);LcdCharacter(' ');delay(drop);}
for(int j=3;j>-1;j--){
posmarker(60,j);LcdCharacter('n');posmarker(60,j+1);LcdCharacter(' ');delay(drop);}
delay(2000);
for(int j=0;j<4;j++){
posmarker(18,j);LcdCharacter('D');posmarker(18,j-1);LcdCharacter(' ');
posmarker(25,j);LcdCharacter('r');posmarker(25,j-1);LcdCharacter(' ');
posmarker(32,j);LcdCharacter('o');posmarker(32,j-1);LcdCharacter(' ');
posmarker(39,j);LcdCharacter('p');posmarker(39,j-1);LcdCharacter(' ');
posmarker(46,3);LcdCharacter(' ');
posmarker(53,j);LcdCharacter('i');posmarker(53,j-1);LcdCharacter(' ');
posmarker(60,j);LcdCharacter('n');posmarker(60,j-1);LcdCharacter(' ');delay(drop);}
delay(3000);
LcdInitialise();
for (int index = 0 ; index < 72 ; index++){
LcdString("|");delay(20);}
for (int index = 72 ; index>-1 ; index--){
LcdString(" ");delay(20);}splashpage();
}

213
ATMEGA_NOKIA6/ATMEGA_NOKIA6.ino Executable file
View File

@@ -0,0 +1,213 @@
#define PIN_SCE 7
#define PIN_RESET 6
#define PIN_DC 5
#define PIN_SDIN 4
#define PIN_SCLK 3
#define LED 13
#define LCD_C LOW
#define LCD_D HIGH
#define LCD_X 84
#define LCD_Y 48
#define LCD_CMD 0
static const byte ASCII[][5] =
{
{0x00, 0x00, 0x00, 0x00, 0x00} // 20
,{0x00, 0x00, 0x5f, 0x00, 0x00} // 21 !
,{0x00, 0x07, 0x00, 0x07, 0x00} // 22 "
,{0x14, 0x7f, 0x14, 0x7f, 0x14} // 23 #
,{0x24, 0x2a, 0x7f, 0x2a, 0x12} // 24 $
,{0x23, 0x13, 0x08, 0x64, 0x62} // 25 %
,{0x36, 0x49, 0x55, 0x22, 0x50} // 26 &
,{0x00, 0x05, 0x03, 0x00, 0x00} // 27 '
,{0x00, 0x1c, 0x22, 0x41, 0x00} // 28 (
,{0x00, 0x41, 0x22, 0x1c, 0x00} // 29 )
,{0x14, 0x08, 0x3e, 0x08, 0x14} // 2a *
,{0x08, 0x08, 0x3e, 0x08, 0x08} // 2b +
,{0x00, 0x50, 0x30, 0x00, 0x00} // 2c ,
,{0x08, 0x08, 0x08, 0x08, 0x08} // 2d -
,{0x00, 0x60, 0x60, 0x00, 0x00} // 2e .
,{0x20, 0x10, 0x08, 0x04, 0x02} // 2f /
,{0x3e, 0x51, 0x49, 0x45, 0x3e} // 30 0
,{0x00, 0x42, 0x7f, 0x40, 0x00} // 31 1
,{0x42, 0x61, 0x51, 0x49, 0x46} // 32 2
,{0x21, 0x41, 0x45, 0x4b, 0x31} // 33 3
,{0x18, 0x14, 0x12, 0x7f, 0x10} // 34 4
,{0x27, 0x45, 0x45, 0x45, 0x39} // 35 5
,{0x3c, 0x4a, 0x49, 0x49, 0x30} // 36 6
,{0x01, 0x71, 0x09, 0x05, 0x03} // 37 7
,{0x36, 0x49, 0x49, 0x49, 0x36} // 38 8
,{0x06, 0x49, 0x49, 0x29, 0x1e} // 39 9
,{0x00, 0x36, 0x36, 0x00, 0x00} // 3a :
,{0x00, 0x56, 0x36, 0x00, 0x00} // 3b ;
,{0x08, 0x14, 0x22, 0x41, 0x00} // 3c <
,{0x14, 0x14, 0x14, 0x14, 0x14} // 3d =
,{0x00, 0x41, 0x22, 0x14, 0x08} // 3e >
,{0x02, 0x01, 0x51, 0x09, 0x06} // 3f ?
,{0x32, 0x49, 0x79, 0x41, 0x3e} // 40 @
,{0x7e, 0x11, 0x11, 0x11, 0x7e} // 41 A
,{0x7f, 0x49, 0x49, 0x49, 0x36} // 42 B
,{0x3e, 0x41, 0x41, 0x41, 0x22} // 43 C
,{0x7f, 0x41, 0x41, 0x22, 0x1c} // 44 D
,{0x7f, 0x49, 0x49, 0x49, 0x41} // 45 E
,{0x7f, 0x09, 0x09, 0x09, 0x01} // 46 F
,{0x3e, 0x41, 0x49, 0x49, 0x7a} // 47 G
,{0x7f, 0x08, 0x08, 0x08, 0x7f} // 48 H
,{0x00, 0x41, 0x7f, 0x41, 0x00} // 49 I
,{0x20, 0x40, 0x41, 0x3f, 0x01} // 4a J
,{0x7f, 0x08, 0x14, 0x22, 0x41} // 4b K
,{0x7f, 0x40, 0x40, 0x40, 0x40} // 4c L
,{0x7f, 0x02, 0x0c, 0x02, 0x7f} // 4d M
,{0x7f, 0x04, 0x08, 0x10, 0x7f} // 4e N
,{0x3e, 0x41, 0x41, 0x41, 0x3e} // 4f O
,{0x7f, 0x09, 0x09, 0x09, 0x06} // 50 P
,{0x3e, 0x41, 0x51, 0x21, 0x5e} // 51 Q
,{0x7f, 0x09, 0x19, 0x29, 0x46} // 52 R
,{0x46, 0x49, 0x49, 0x49, 0x31} // 53 S
,{0x01, 0x01, 0x7f, 0x01, 0x01} // 54 T
,{0x3f, 0x40, 0x40, 0x40, 0x3f} // 55 U
,{0x1f, 0x20, 0x40, 0x20, 0x1f} // 56 V
,{0x3f, 0x40, 0x38, 0x40, 0x3f} // 57 W
,{0x63, 0x14, 0x08, 0x14, 0x63} // 58 X
,{0x07, 0x08, 0x70, 0x08, 0x07} // 59 Y
,{0x61, 0x51, 0x49, 0x45, 0x43} // 5a Z
,{0x00, 0x7f, 0x41, 0x41, 0x00} // 5b [
,{0x02, 0x04, 0x08, 0x10, 0x20} // 5c ¥
,{0x00, 0x41, 0x41, 0x7f, 0x00} // 5d ]
,{0x04, 0x02, 0x01, 0x02, 0x04} // 5e ^
,{0x40, 0x40, 0x40, 0x40, 0x40} // 5f _
,{0x00, 0x01, 0x02, 0x04, 0x00} // 60 `
,{0x20, 0x54, 0x54, 0x54, 0x78} // 61 a
,{0x7f, 0x48, 0x44, 0x44, 0x38} // 62 b
,{0x38, 0x44, 0x44, 0x44, 0x20} // 63 c
,{0x38, 0x44, 0x44, 0x48, 0x7f} // 64 d
,{0x38, 0x54, 0x54, 0x54, 0x18} // 65 e
,{0x08, 0x7e, 0x09, 0x01, 0x02} // 66 f
,{0x0c, 0x52, 0x52, 0x52, 0x3e} // 67 g
,{0x7f, 0x08, 0x04, 0x04, 0x78} // 68 h
,{0x00, 0x44, 0x7d, 0x40, 0x00} // 69 i
,{0x20, 0x40, 0x44, 0x3d, 0x00} // 6a j
,{0x7f, 0x10, 0x28, 0x44, 0x00} // 6b k
,{0x00, 0x41, 0x7f, 0x40, 0x00} // 6c l
,{0x7c, 0x04, 0x18, 0x04, 0x78} // 6d m
,{0x7c, 0x08, 0x04, 0x04, 0x78} // 6e n
,{0x38, 0x44, 0x44, 0x44, 0x38} // 6f o
,{0x7c, 0x14, 0x14, 0x14, 0x08} // 70 p
,{0x08, 0x14, 0x14, 0x18, 0x7c} // 71 q
,{0x7c, 0x08, 0x04, 0x04, 0x08} // 72 r
,{0x48, 0x54, 0x54, 0x54, 0x20} // 73 s
,{0x04, 0x3f, 0x44, 0x40, 0x20} // 74 t
,{0x3c, 0x40, 0x40, 0x20, 0x7c} // 75 u
,{0x1c, 0x20, 0x40, 0x20, 0x1c} // 76 v
,{0x3c, 0x40, 0x30, 0x40, 0x3c} // 77 w
,{0x44, 0x28, 0x10, 0x28, 0x44} // 78 x
,{0x0c, 0x50, 0x50, 0x50, 0x3c} // 79 y
,{0x44, 0x64, 0x54, 0x4c, 0x44} // 7a z
,{0x00, 0x08, 0x36, 0x41, 0x00} // 7b {
,{0x00, 0x00, 0x7f, 0x00, 0x00} // 7c |
,{0x00, 0x41, 0x36, 0x08, 0x00} // 7d }
,{0x10, 0x08, 0x08, 0x10, 0x08} // 7e ?
,{0x00, 0x06, 0x09, 0x09, 0x06} // 7f ?
};
void LcdCharacter(char character)
{
LcdWrite(LCD_D, 0x00);
for (int index = 0; index < 5; index++)
{
LcdWrite(LCD_D, ASCII[character - 0x20][index]);
}
LcdWrite(LCD_D, 0x00);
}
void LcdClear(void)
{
for (int index = 0; index < LCD_X * LCD_Y / 8; index++)
{
LcdWrite(LCD_D, 0x00);
}
}
void LcdInitialise(void)
{
digitalWrite(PIN_RESET, LOW);
// delay(1);
digitalWrite(PIN_RESET, HIGH);
LcdWrite( LCD_CMD, 0x21 ); // LCD Extended Commands.
LcdWrite( LCD_CMD, 0xBF ); // Set LCD Vop (Contrast). //B1 //Actu Bf
LcdWrite( LCD_CMD, 0x04 ); // Set Temp coefficent. //0x04 //04
LcdWrite( LCD_CMD, 0x14 ); // LCD bias mode 1:48. //0x13 //014
LcdWrite( LCD_CMD, 0x0C ); // LCD in normal mode. 0x0d for inverse //0c
LcdWrite(LCD_C, 0x20);
LcdWrite(LCD_C, 0x0C);
}
void LcdString(char *characters)
{
while (*characters)
{
LcdCharacter(*characters++);
}
}
void LcdWrite(byte dc, byte data)
{
digitalWrite(PIN_DC, dc);
digitalWrite(PIN_SCE, LOW);
shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
digitalWrite(PIN_SCE, HIGH);
}
// gotoXY routine to position cursor
// x - range: 0 to 84
// y - range: 0 to 5
void gotoXY(int x, int y)
{
LcdWrite( 0, 0x80 | x); // Column.
LcdWrite( 0, 0x40 | y); // Row.
}
void setup(void)
{
pinMode (LED, OUTPUT);
pinMode(PIN_SCE, OUTPUT);
pinMode(PIN_RESET, OUTPUT);
pinMode(PIN_DC, OUTPUT);
pinMode(PIN_SDIN, OUTPUT);
pinMode(PIN_SCLK, OUTPUT);
LcdInitialise();
LcdClear();
digitalWrite(LED, HIGH);
delay(5000);
}
void loop(void)
{
digitalWrite(LED, LOW);
gotoXY(1,1);
LcdString ("RIR2012");
delay(1000);
LcdClear();
digitalWrite(LED, HIGH);
delay(1000);
digitalWrite(LED, LOW);
digitalWrite(PIN_RESET, LOW);
delay(1000);
digitalWrite(LED, HIGH);
//while(1);
}

119
ATMEGA_NOKIA_3/ATMEGA_NOKIA_3.ino Executable file
View File

@@ -0,0 +1,119 @@
int PIN_SCE = 4 ; //SS
int PIN_RESET = 3;
int PIN_DC = 5; // data
int PIN_SDIN = 6 ; //MOSI SIMO
int PIN_SCLK =7 ; //CLK SCLK
#define PIN_LCD 9 // backlight
#define LCD_C LOW //command
#define LCD_D HIGH //data high command low.
#define LCD_X 84 ///character area //
#define LCD_Y 48 //consists of banks of 7 by eight pixels.//
#define LCD_DATA 1
int cycle=0;
const unsigned char splash[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0xE0, 0xE0, 0x00, 0x00, 0x00, 0xC0, 0xE0, 0xC0, 0x01, 0x01, 0x01, 0xC1, 0xE1, 0xC1,
0x01, 0xC1, 0xE1, 0x41, 0x01, 0x03, 0x03, 0x03, 0x03, 0xE3, 0xE3, 0x03, 0x03, 0x03, 0x03, 0x07,0xC7, 0xE7, 0xC7, 0x07, 0x07, 0x07, 0xE7, 0xC7, 0xC7, 0x0F, 0xCF, 0xCF, 0x0F, 0x0F, 0x8F, 0xCF,
0xEF, 0xEF, 0xCF, 0x0F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1E, 0x3E, 0x3E,0x3E, 0x3E, 0x3E, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x80, 0xFE, 0xFF, 0x1F, 0xC0, 0xE0, 0xFC, 0xFF, 0xFF, 0xFF, 0x00, 0x00,0xF0, 0xFF, 0x7F, 0xFF, 0xFC, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0x1F, 0x00,
0x00, 0xC0, 0xF0, 0xFE, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xF8, 0xFF, 0x7F, 0xFF, 0xFC, 0xFF, 0x1F,0x00, 0xFC, 0xFF, 0x0F, 0xE1, 0xE7, 0xE7, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x3F, 0x0F, 0x00, 0x3F, 0x3F, 0x07, 0x03,
0x3F, 0x3F, 0x00, 0x10, 0x3F, 0x1F, 0x00, 0x1F, 0x3F, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E,0x3F, 0x3F, 0x3C, 0x3C, 0x08, 0x3F, 0x3F, 0x03, 0x03, 0x3F, 0x3F, 0x00, 0x3E, 0x3F, 0x0F, 0x00,
0x1F, 0x3F, 0x0F, 0x00, 0x00, 0x1F, 0x3F, 0x3C, 0x3F, 0x0F, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0x00, 0x00, 0xF0, 0xF0, 0x00, 0x00, 0x00, 0xF0,0xF0, 0xF0, 0xF0, 0xF0, 0x70, 0x00, 0xC0, 0xE0, 0xF0, 0xF0, 0xE0, 0x00, 0xF0, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xE0, 0x00, 0x00, 0x80, 0xE0, 0xF0, 0xF0, 0xE0, 0xF0,0x00, 0x00, 0xE0, 0xF0, 0xE0, 0x00, 0xE0, 0xF0, 0x60, 0x00, 0xC0, 0xF0, 0xF0, 0x00, 0x00, 0xE0,
0xF0, 0xF0, 0xF0, 0xE0, 0x00, 0xC0, 0xE0, 0xF0, 0xF0, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF, 0x7F, 0x78, 0x78, 0x00, 0xC0, 0xFF, 0xFF, 0x07,
0x00, 0x00, 0xF8, 0xFF, 0xFF, 0x7E, 0x78, 0x38, 0x00, 0xFE, 0xFF, 0x0F, 0xC0, 0xC3, 0x03, 0x00,0x00, 0xF8, 0xFF, 0x1F, 0x00, 0x00, 0xF9, 0xFF, 0xFE, 0xF0, 0x7F, 0x1F, 0x00, 0xF8, 0xFF, 0xFF,
0x01, 0xE0, 0xFF, 0x7F, 0x00, 0xF0, 0xFF, 0x3F, 0xFF, 0xFF, 0xFF, 0x7F, 0x00, 0xE0, 0xFF, 0xFF,0x03, 0x00, 0xFF, 0xFF, 0x03, 0xC3, 0xC3, 0x01, 0x80, 0x8F, 0xFF, 0xFD, 0xE1, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xF0, 0xF0, 0xF0, 0xE0, 0xE0, 0xE0, 0xFF, 0xFF, 0xFE, 0xFE, 0xE4, 0xE0,0xE7, 0xFF, 0xDF, 0xDE, 0xDE, 0xC0, 0xCF, 0xDF, 0xDE, 0xDE, 0xDE, 0xC0, 0x80, 0x8F, 0x9F, 0x9F,
0x8F, 0x83, 0x80, 0x80, 0x8E, 0x9F, 0x0F, 0x00, 0x00, 0x08, 0x1F, 0x1F, 0x03, 0x1F, 0x3F, 0x18,0x00, 0x03, 0x0F, 0x1F, 0x1F, 0x0F, 0x03, 0x00, 0x00, 0x1F, 0x1F, 0x00, 0x07, 0x1F, 0x1F, 0x00,
0x00, 0x1F, 0x1F, 0x03, 0x00, 0x00, 0x0F, 0x1F, 0x1F, 0x0F, 0x01, 0x00, 0x1F, 0x1F, 0x1F, 0x0F,0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
const unsigned char nokia [] = {
0x00, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0xE0, 0xE0, 0xE0, 0xE0, 0x00, 0x00, 0xC0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0,
0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xC0, 0x80, 0x00, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0x00, 0x00, 0x00,0x00, 0x80, 0xC0, 0xE0, 0xE0, 0xE0, 0xE0, 0x60, 0x20, 0x00, 0x40, 0xE0, 0xE0, 0xE0, 0xE0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xC0, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x0F, 0x3F, 0xFF, 0xFF, 0xFE, 0xF8,
0xF0, 0xC0, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x03, 0x03,0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xF0, 0xF8, 0xFC, 0xFE, 0xFF, 0xDF, 0x0F, 0x07, 0x03, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF,0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xF8, 0xFF, 0xFF, 0x7F, 0x1F, 0x07, 0x1F, 0xFF,
0xFF, 0xFF, 0xF8, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x00, 0x00,0x00, 0x01, 0x07, 0x1F, 0x7F, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x0F, 0x7F, 0xFF,
0xFF, 0xFF, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xFF, 0xFF, 0x7F, 0x1F, 0x00,0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x01, 0x03, 0x07, 0x1F, 0x3F, 0x7F, 0xFE, 0xFC, 0xF8, 0xF0,
0xC0, 0x80, 0xF9, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xE0, 0xFC, 0xFF, 0xFF, 0x7F, 0x1F, 0x1F, 0x1F,0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0xFF, 0xFF, 0xFF, 0xFC, 0xE0, 0x00, 0x00, 0x00, 0xC0, 0xC0,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00,
0x00, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0xC0, 0xC0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0xFF, 0xDF, 0x00, 0x00, 0xF0, 0xFE, 0x06, 0x06, 0xFE, 0x70, 0xFE, 0xFE, 0x06, 0x06, 0xFE,
0x00, 0xFE, 0x1E, 0x02, 0x86, 0xFC, 0x00, 0xFC, 0x66, 0x62, 0x7E, 0x38, 0xF8, 0xFE, 0x06, 0x02,0x02, 0xFF, 0xFF, 0x02, 0x02, 0xFE, 0x00, 0x00, 0xFE, 0x06, 0x06, 0xFE, 0x00, 0xF8, 0xDE, 0x02,
0x06, 0xFE, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x60, 0x60, 0x3F, 0x00, 0xFC, 0x66, 0x62, 0x7E, 0x38,0xF8, 0xFE, 0x02, 0x06, 0xFC, 0x00, 0xFE, 0xFE, 0x02, 0x06, 0xFC, 0x00, 0xFF, 0x80, 0xF0, 0xFE,
0x62, 0x66, 0x7C, 0x00, 0x00, 0x01, 0x07, 0x0C, 0x0C, 0x04, 0x07, 0x0C, 0x0C, 0x07, 0x00, 0x07,0x07, 0x00, 0x00, 0x07, 0x00, 0x07, 0x07, 0x00, 0x01, 0x07, 0x00, 0x07, 0x06, 0x0C, 0x0C, 0x00,
0x01, 0x07, 0x0C, 0x0C, 0x00, 0x03, 0x0F, 0x0C, 0x04, 0x07, 0x00, 0x00, 0x07, 0x00, 0x00, 0x07,0x00, 0x03, 0x27, 0x2C, 0x2E, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x07,
0x0E, 0x0C, 0x0C, 0x00, 0x01, 0x07, 0x0C, 0x0E, 0x07, 0x00, 0x3F, 0x1F, 0x0C, 0x06, 0x03, 0x00,0x07, 0x00, 0x00, 0x07, 0x0C, 0x0C, 0x04, 0x00,
};
const unsigned char arduinox [] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xE0, 0xF0, 0xF0,0xF0, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF0, 0xF0, 0xF0, 0xE0,
0xC0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xC0,0xE0, 0xE0, 0xF0, 0xF0, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF8, 0xF0,
0xF0, 0xF0, 0xE0, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xF0, 0xFC, 0xFE, 0xFF, 0xFF, 0x7F,
0x1F, 0x0F, 0x07, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01,0x03, 0x03, 0x07, 0x0F, 0x0F, 0x3F, 0x7F, 0xFF, 0xFE, 0xFC, 0xF8, 0xF0, 0xF0, 0xF8, 0xFC, 0xFE,
0xFF, 0x7F, 0x3F, 0x1F, 0x0F, 0x07, 0x03, 0x03, 0x01, 0x01, 0x00, 0x00, 0xE0, 0xE0, 0xE0, 0x00,0x00, 0x01, 0x01, 0x03, 0x03, 0x07, 0x0F, 0x1F, 0x7F, 0xFF, 0xFF, 0xFE, 0xFC, 0xF0, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0xFF, 0xFF,0xFF, 0xFF, 0xFF, 0xE0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E, 0x0E,
0x0E, 0x0E, 0x0E, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF,0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0xE0, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x0E, 0x0E, 0x0F,
0x7F, 0x7F, 0x7F, 0x0E, 0x0E, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xE0, 0xFF, 0xFF, 0xFF,0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0x7F, 0xFE, 0xFC, 0xF8, 0xF8, 0xF8, 0xF0,0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF8, 0xF8, 0xFC, 0xFC, 0xFE, 0x7F, 0x7F, 0x3F, 0x1F, 0x0F,
0x0F, 0x07, 0x01, 0x00, 0x00, 0x01, 0x07, 0x0F, 0x0F, 0x1F, 0x3F, 0x7F, 0x7F, 0xFE, 0xFC, 0xFC,0xF8, 0xF8, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF8, 0xF8, 0xF8, 0xFC, 0xFE, 0x7F, 0x7F,
0x3F, 0x1F, 0x0F, 0x07, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00,
0x00, 0xC1, 0xC1, 0xC1, 0x41, 0xC1, 0xC1, 0xC1, 0x01, 0x01, 0x01, 0xC1, 0xC0, 0x40, 0xC0, 0xC0,0xC0, 0x80, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0xC0, 0xC0,
0xC0, 0xC0, 0xC0, 0xC0, 0xC1, 0x01, 0x01, 0xC1, 0xC1, 0xC1, 0x81, 0x01, 0x01, 0xC1, 0xC1, 0x00,0x00, 0x80, 0xC0, 0xC0, 0x40, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x7C, 0x3F, 0x1B, 0x19,0x1F, 0x7E, 0x70, 0x00, 0x00, 0x3F, 0x7F, 0x0C, 0x0C, 0x1C, 0x7F, 0x77, 0x00, 0x00, 0x00, 0x7F,
0x7F, 0x60, 0x60, 0x30, 0x3F, 0x1F, 0x00, 0x00, 0x1F, 0x3F, 0x7F, 0x60, 0x60, 0x7F, 0x3F, 0x1F,0x00, 0x00, 0x60, 0x60, 0x7F, 0x7F, 0x7F, 0x60, 0x60, 0x00, 0x00, 0x3F, 0x7F, 0x03, 0x07, 0x0E,
0x3C, 0x7F, 0x7F, 0x00, 0x00, 0x1F, 0x3F, 0x70, 0x60, 0x60, 0x3F, 0x3F, 0x0F, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
void posmarker(){
LcdWrite( 0, 0x80 | 0); // Column.
LcdWrite( 0, 0x40 |0);} // Row
void LcdClear(void){ for (int index = 0; index < 540; index++) { LcdWrite(LCD_D, 0x00);}}
void LcdWrite(byte dc, byte data)
{ digitalWrite(PIN_DC, dc); digitalWrite(PIN_SCE, LOW); shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
digitalWrite(PIN_SCE, HIGH);}
void initialise(){
pinMode(PIN_SCE, OUTPUT); pinMode(PIN_RESET, OUTPUT); pinMode(PIN_DC, OUTPUT);
pinMode(PIN_SDIN, OUTPUT); pinMode(PIN_SCLK, OUTPUT);
digitalWrite(PIN_RESET, LOW); digitalWrite(PIN_RESET, HIGH);
LcdWrite(0, 0x21); //Tell LCD that extended commands follow
LcdWrite(0, 0x94); //Set LCD Vop (Contrast): Try 0xB1(good @ 3.3V) or 0xBF if your display is too dark
LcdWrite(0, 0x04); //Set Temp coefficent
LcdWrite(0, 0x14); //LCD bias mode 1:48: Try 0x13 or 0x14
LcdWrite(0, 0x20); //We must send 0x20 before modifying the display control mode
LcdWrite(0, 0x0C); //Set display control, normal mode. 0x0D for inverse
}
void setup(){
pinMode(PIN_LCD, OUTPUT);
digitalWrite(PIN_LCD, HIGH);
analogWrite(PIN_LCD, 200);
initialise();
LcdClear();
posmarker();
}
void loop(){
cycle++;if(cycle==5){cycle=1;}
posmarker();
if (cycle==1){for (int index3 = 0 ; index3 < (504) ; index3++){
digitalWrite(PIN_DC,1); digitalWrite(PIN_SCE, LOW); shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST,splash[index3]);
digitalWrite(PIN_SCE, HIGH);} delay(2000);posmarker();}
if (cycle==2){for (int index3 = 0 ; index3 < (504) ; index3++){
digitalWrite(PIN_DC,1); digitalWrite(PIN_SCE, LOW); shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST,nokia[index3]);
digitalWrite(PIN_SCE, HIGH);} delay(2000);posmarker();}
if (cycle==3){for (int index3 = 0 ; index3 < (504) ; index3++){
digitalWrite(PIN_DC,1); digitalWrite(PIN_SCE, LOW); shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST,arduinox[index3]);
digitalWrite(PIN_SCE, HIGH);} delay(3000);posmarker();}
delay(2000);
if (cycle==4){LcdWrite(0, 0x20); LcdWrite(0, 0x0D);
for (int index3 = 0 ; index3 < (504) ; index3++){
digitalWrite(PIN_DC,1); digitalWrite(PIN_SCE, LOW); shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST,arduinox[index3]);
digitalWrite(PIN_SCE, HIGH);} delay(3000);posmarker();}
delay(2000);
for (int index = 0; index < 540; index++) { LcdWrite(LCD_D, 0xFF);delay(1);}
;posmarker();
for (int index = 0; index < 540; index++) { LcdWrite(LCD_D, 0x00);delay(5);}
LcdWrite(0, 0x20); LcdWrite(0, 0x0C);
}

View File

@@ -0,0 +1,520 @@
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <Wire.h>
#include <Adafruit_BMP085.h>
#include <RCSwitch.h>
#include <Narcoleptic.h>
#define LED_PIN (13)
#define DEBUG TRUE
#define SEND_MESSAGE_DELAY 30000 // Ne pas dépasser 32000 !! Delay in ms between each value's extraction
#define SEND_433_PAUSE 160 // 16 multiple
const byte TRANSMITTER_PIN = 9;
// Init RCSwitch
RCSwitch mySwitch = RCSwitch();
//
float temperature = 0.0;
float pressure = 0.0;
float pression = 0.0;
float presiune = 0.0;
// ################# Barometre ####
Adafruit_BMP085 bmp;
// #####################
///////////////// OREGON //////////////////////////////////////
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
#define SEND_HIGH() digitalWrite(TRANSMITTER_PIN, HIGH)
#define SEND_LOW() digitalWrite(TRANSMITTER_PIN, LOW)
// Buffer for Oregon message
#ifdef THN132N
byte OregonMessageBuffer[8];
#else
byte OregonMessageBuffer[9];
#endif
/**
* \brief Send logical "0" over RF
* \details azero bit be represented by an off-to-on transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendZero(void)
{
SEND_HIGH();
delayMicroseconds(TIME);
SEND_LOW();
delayMicroseconds(TWOTIME);
SEND_HIGH();
delayMicroseconds(TIME);
}
/**
* \brief Send logical "1" over RF
* \details a one bit be represented by an on-to-off transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendOne(void)
{
SEND_LOW();
delayMicroseconds(TIME);
SEND_HIGH();
delayMicroseconds(TWOTIME);
SEND_LOW();
delayMicroseconds(TIME);
}
/**
* Send a bits quarter (4 bits = MSB from 8 bits value) over RF
*
* @param data Source data to process and sent
*/
/**
* \brief Send a bits quarter (4 bits = MSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterMSB(const byte data)
{
(bitRead(data, 4)) ? sendOne() : sendZero();
(bitRead(data, 5)) ? sendOne() : sendZero();
(bitRead(data, 6)) ? sendOne() : sendZero();
(bitRead(data, 7)) ? sendOne() : sendZero();
}
/**
* \brief Send a bits quarter (4 bits = LSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterLSB(const byte data)
{
(bitRead(data, 0)) ? sendOne() : sendZero();
(bitRead(data, 1)) ? sendOne() : sendZero();
(bitRead(data, 2)) ? sendOne() : sendZero();
(bitRead(data, 3)) ? sendOne() : sendZero();
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Send a buffer over RF
* \param data Data to send
* \param size size of data to send
*/
void sendData(byte *data, byte size)
{
for(byte i = 0; i < size; ++i)
{
sendQuarterLSB(data[i]);
sendQuarterMSB(data[i]);
}
}
/**
* \brief Send an Oregon message
* \param data The Oregon message
*/
void sendOregon(byte *data, byte size)
{
sendPreamble();
//sendSync();
sendData(data, size);
sendPostamble();
}
/**
* \brief Send preamble
* \details The preamble consists of 16 "1" bits
*/
inline void sendPreamble(void)
{
byte PREAMBLE[]={0xFF,0xFF};
sendData(PREAMBLE, 2);
}
/**
* \brief Send postamble
* \details The postamble consists of 8 "0" bits
*/
inline void sendPostamble(void)
{
#ifdef THN132N
sendQuarterLSB(0x00);
#else
byte POSTAMBLE[]={0x00};
sendData(POSTAMBLE, 1);
#endif
}
/**
* \brief Send sync nibble
* \details The sync is 0xA. It is not use in this version since the sync nibble
* \ is include in the Oregon message to send.
*/
inline void sendSync(void)
{
sendQuarterLSB(0xA);
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Set the sensor type
* \param data Oregon message
* \param type Sensor type
*/
inline void setType(byte *data, byte* type)
{
data[0] = type[0];
data[1] = type[1];
}
/**
* \brief Set the sensor channel
* \param data Oregon message
* \param channel Sensor channel (0x10, 0x20, 0x30)
*/
inline void setChannel(byte *data, byte channel)
{
data[2] = channel;
}
/**
* \brief Set the sensor ID
* \param data Oregon message
* \param ID Sensor unique ID
*/
inline void setId(byte *data, byte ID)
{
data[3] = ID;
}
/**
* \brief Set the sensor battery level
* \param data Oregon message
* \param level Battery level (0 = low, 1 = high)
*/
void setBatteryLevel(byte *data, byte level)
{
if(!level) data[4] = 0x0C;
else data[4] = 0x00;
}
/**
* \brief Set the sensor temperature
* \param data Oregon message
* \param temp the temperature
*/
void setTemperature(byte *data, float temp)
{
// Set temperature sign
if(temp < 0)
{
data[6] = 0x08;
temp *= -1;
}
else
{
data[6] = 0x00;
}
// Determine decimal and float part
int tempInt = (int)temp;
int td = (int)(tempInt / 10);
int tf = (int)round((float)((float)tempInt/10 - (float)td) * 10);
int tempFloat = (int)round((float)(temp - (float)tempInt) * 10);
// Set temperature decimal part
data[5] = (td << 4);
data[5] |= tf;
// Set temperature float part
data[4] |= (tempFloat << 4);
}
/**
* \brief Set the sensor humidity
* \param data Oregon message
* \param hum the humidity
*/
void setHumidity(byte* data, byte hum)
{
data[7] = (hum/10);
data[6] |= (hum - data[7]*10) << 4;
}
/**
* \brief Sum data for checksum
* \param count number of bit to sum
* \param data Oregon message
*/
int Sum(byte count, const byte* data)
{
int s = 0;
for(byte i = 0; i<count;i++)
{
s += (data[i]&0xF0) >> 4;
s += (data[i]&0xF);
}
if(int(count) != count)
s += (data[count]&0xF0) >> 4;
return s;
}
/**
* \brief Calculate checksum
* \param data Oregon message
*/
void calculateAndSetChecksum(byte* data)
{
#ifdef THN132N
int s = ((Sum(6, data) + (data[6]&0xF) - 0xa) & 0xff);
data[6] |= (s&0x0F) << 4; data[7] = (s&0xF0) >> 4;
#else
data[8] = ((Sum(8, data) - 0xa) & 0xFF);
#endif
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
//////////////// FIN OREGON /////////////////////////////////
// =============================================================
void setup() {
mySwitch.enableTransmit(TRANSMITTER_PIN);
Serial.begin(9600);
// Sleep
/* Don't forget to configure the pin! */
pinMode(LED_PIN, OUTPUT);
// TEST SONDE BAROMETRE
//byte ID[] = {0x5A,0x5D};
#ifdef THN132N
// Create the Oregon message for a temperature only sensor (TNHN132N)
byte ID[] = {0xEA,0x4C};
#ifdef DEBUG
Serial.println("Def THN132");
#endif
#else
// Create the Oregon message for a temperature/humidity sensor (THGR2228N)
byte ID[] = {0x1A,0x2D};
#ifdef DEBUG
Serial.println("UnDef THN132");
#endif
#endif
setType(OregonMessageBuffer, ID);
setChannel(OregonMessageBuffer, 0x20);
// ATMEGA 1 = BC
// TEST OREGON BB
// TEST Luminosite BD
// Barometre BE
setId(OregonMessageBuffer, 0xBE); // ID BB BC BE
}
void loop()
{
digitalWrite(13, HIGH);
// Read Vcc value
long currentVcc = 5000; //readVcc();
barometre();
digitalWrite(13, LOW);
if (currentVcc > 5000) {
currentVcc = 5000;
}
#ifdef DEBUG
Serial.println(currentVcc);
#endif
byte ID[] = {0x1A,0x2D};
sendMyOregon( ID, 0x20, 0xBE, temperature, 58, currentVcc);
//sendMyOregon( ID, 0x20, 0xBC,temperature, 52);
//
// // Get Temperature, humidity and battery level from sensors
// // (ie: 1wire DS18B20 for température, ...)
// if (currentVcc < 3800) {
// setBatteryLevel(OregonMessageBuffer, 0); // 0 : low, 1 : high
// } else {
// setBatteryLevel(OregonMessageBuffer, 1); // 0 : low, 1 : high
// }
// // need addaptation here
//// Ajout perso
//
// setTemperature(OregonMessageBuffer,temperature);
//
//
//// setTemperature(OregonMessageBuffer, 11.2);
//
//#ifndef THN132N
// // Set Humidity
// setHumidity(OregonMessageBuffer, 52);
//#endif
//
// // Calculate the checksum
// calculateAndSetChecksum(OregonMessageBuffer);
//
// // Show the Oregon Message
// #ifdef DEBUG
// for (byte i = 0; i < sizeof(OregonMessageBuffer); ++i) {
// Serial.print(OregonMessageBuffer[i] >> 4, HEX);
// Serial.print(OregonMessageBuffer[i] & 0x0F, HEX);
//
// }
// Serial.println("");
// #endif
//
// // Send the Message over RF
// sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
// // Send a "pause"
// SEND_LOW();
// delayMicroseconds(TWOTIME*8);
// // Send a copie of the first message. The v2.1 protocol send the
// // message two time
// sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
//
// Narcoleptic.delay(SEND_433_PAUSE);
//
// // Wait for 30 seconds before send a new message
// SEND_LOW();
// //delay(3000);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
}
void barometre() {
/* See Example: TypeA_WithDIPSwitches */
// mySwitch.switchOn("00001", "10000");
// delay(1000);
// BMP
if (bmp.begin()) {
temperature = bmp.readTemperature();
pressure= bmp.readPressure() / 100.0;
pression = pressure / 101.325;
pression = pression * 0.760 * 100;
// http://en.wikipedia.org/wiki/Atmospheric_pressure#Mean_sea_level_pressure
// Serial.print("Presiure la nivelul marii (calculata) = ");
presiune = bmp.readSealevelPressure(19) / 101.325;
presiune = presiune * 0.760;
#ifdef DEBUG
Serial.print("Temperature="); Serial.println(temperature);
Serial.print("pressure="); Serial.println(pressure);
Serial.print("presiune="); Serial.println(presiune);
#endif
}
}
////--------------------------------------------------------------------------------------------------
//// Read current supply voltage
////--------------------------------------------------------------------------------------------------
// long readVcc() {
// bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
// long result;
// // Read 1.1V reference against Vcc
// #if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
// ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
// #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
// ADMUX = _BV(MUX3) | _BV(MUX2);
// #else
// ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
// #endif
// delay(2); // Wait for Vref to settle
// ADCSRA |= _BV(ADSC); // Convert
// while (bit_is_set(ADCSRA,ADSC));
// result = ADCL;
// result |= ADCH<<8;
// result = 1126400L / result; // Back-calculate Vcc in mV
// // ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
// return result; // Vcc in millivolts
//}
void sendMyOregon(byte messageID[], byte channel, byte id, float temp, byte hum, int currentVcc) {
byte OregonMessageBuffer[9];
// Messages gérés par Domoticz
// 0xEA4C taille 8 bytes température et niveau de batterie
//0x1A2D taille 9 bytes température humidité et niveau de batterie (0 / 1)
//0xF824 3 températures 2 humidité
//0x1984 0x1994 Vent ?
//0x2914 Pluie
setType(OregonMessageBuffer, messageID);
setChannel(OregonMessageBuffer, channel);
// ATMEGA 1 = BC
// TEST OREGON BB
// TEST Luminosite BD
// Barometre BF
setId(OregonMessageBuffer, id); // ID BB BC BF
setBatteryLevel(OregonMessageBuffer, 1); // 0 : low, 1 : high
if (currentVcc < 3800) {
setBatteryLevel(OregonMessageBuffer, 0); // 0 : low, 1 : high
} else {
setBatteryLevel(OregonMessageBuffer, 1); // 0 : low, 1 : high
}
setTemperature(OregonMessageBuffer,temp);
setHumidity(OregonMessageBuffer, hum);
// Calculate the checksum
calculateAndSetChecksum(OregonMessageBuffer);
// Send the Message over RF
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
// Send a "pause"
SEND_LOW();
delayMicroseconds(TWOTIME*8);
// Send a copie of the first message. The v2.1 protocol send the
// message two time
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
}

View File

@@ -0,0 +1,492 @@
/* Ce programme a été élaboré à partir du code de M. Olivier LEBRUN réutilisé en grande partie pour réaliser un encodeur OWL CM180 (Micro+)
/* ainsi qu'à partir du code (+ carte électronique à relier au compteur) de M. Pascal CARDON pour la partie téléinfo
/* Onlinux a fourni des trames du OWL CM180 me permettant de faire les algo d'encodage (il a développer un code de décodage des trames)
/* Je remercie les auteurs. Ci-dessous les liens vers leur site internet.
/*=======================================================================================================================
ONLINUX : Decode and parse the Oregon Scientific V3 radio data transmitted by OWL CM180 Energy sensor (433.92MHz)
References :
http://blog.onlinux.fr
https://github.com/onlinux/OWL-CMR180
http://domotique.web2diz.net/?p=11
http://www.domotique-info.fr/2014/05/recuperer-teleinformation-arduino/
http://connectingstuff.net/blog/encodage-protocoles-oregon-scientific-sur-arduino/
/*=======================================================================================================================
/*
* connectingStuff, Oregon Scientific v2.1 Emitter
* http://connectingstuff.net/blog/encodage-protocoles-oregon-scientific-sur-arduino/
*
* Copyright (C) 2013 olivier.lebrun@gmail.com
*
/*=======================================================================================================================
my_teleinfo
(c) 2012-2013 by
Script name : my_teleinfo
http://www.domotique-info.fr/2014/05/recuperer-teleinformation-arduino/
VERSIONS HISTORY
Version 1.00 30/11/2013 + Original version
Version 1.10 03/05/2015 + Manu : Small ajustment to variabilise the PIN numbers for Transmiter and Teleinfo
See ref here : http://domotique.web2diz.net/?p=11#
montage électronique conforme à http://www.domotique-info.fr/2014/05/recuperer-teleinformation-arduino/
======================================================================================================================*/
#include <SoftwareSerial.h>
// PIN SIETTINGS //
const byte TELEINFO_PIN = 8; //Connexion TELEINFO
const byte TX_PIN = 3; //emetteur 433 MHZ
// PIN SIETTINGS //
const unsigned long TIME = 488;
const unsigned long TWOTIME = TIME*2;
#define SEND_HIGH() digitalWrite(TX_PIN, HIGH)
#define SEND_LOW() digitalWrite(TX_PIN, LOW)
byte OregonMessageBuffer[13]; // OWL180
//*********************************************************
SoftwareSerial* mySerial;
char HHPHC;
int ISOUSC; // intensité souscrite
int IINST; // intensité instantanée en A
int IMAX; // intensité maxi en A
int PAPP; // puissance apparente en VA
unsigned long HCHC; // compteur Heures Creuses en W
unsigned long HCHP; // compteur Heures Pleines en W
String PTEC; // Régime actuel : HPJB, HCJB, HPJW, HCJW, HPJR, HCJR
String ADCO; // adresse compteur
String OPTARIF; // option tarifaire
String MOTDETAT; // status word
String pgmVersion; // TeleInfo program version
boolean ethernetIsOK;
boolean teleInfoReceived;
char chksum(char *buff, uint8_t len);
boolean handleBuffer(char *bufferTeleinfo, int sequenceNumnber);
char version[17] = "TeleInfo V 1.00";
unsigned long PAPP_arrondi; // PAPP*497/500/16 arrondi
unsigned long chksum_CM180;
unsigned long long HCP;
//********** debug
// char buffer[100];// à virer ***************
//**********************************************************************
/**
* \brief Send logical "0" over RF
* \details azero bit be represented by an off-to-on transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendZero(void)
{
SEND_LOW();
delayMicroseconds(TIME);
SEND_HIGH();
delayMicroseconds(TIME);
}
/**
* \brief Send logical "1" over RF
* \details a one bit be represented by an on-to-off transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendOne(void)
{
SEND_HIGH();
delayMicroseconds(TIME);
SEND_LOW();
delayMicroseconds(TIME);
}
/**
* \brief Send a buffer over RF
* \param data Data to send
* \param size size of data to send
*/
void sendData(byte *data, byte size)
{
for(byte i = 0; i < size; ++i)
{
(bitRead(data[i], 0)) ? sendOne() : sendZero();
(bitRead(data[i], 1)) ? sendOne() : sendZero();
(bitRead(data[i], 2)) ? sendOne() : sendZero();
(bitRead(data[i], 3)) ? sendOne() : sendZero();
(bitRead(data[i], 4)) ? sendOne() : sendZero();
(bitRead(data[i], 5)) ? sendOne() : sendZero();
(bitRead(data[i], 6)) ? sendOne() : sendZero();
(bitRead(data[i], 7)) ? sendOne() : sendZero();
}
}
/**
* \brief Send an Oregon message
* \param data The Oregon message
*/
void sendOregon(byte *data, byte size)
{
sendPreamble();
sendData(data,size);
sendPostamble();
}
/**
* \brief Send preamble
* \details The preamble consists of 10 X "1" bits (minimum)
*/
inline void sendPreamble(void)
{
for(byte i = 0; i < 10; ++i) //OWL CM180
{
sendOne();
}
}
/**
* \brief Send postamble
*/
inline void sendPostamble(void)
{
for(byte i = 0; i <4 ; ++i) //OWL CM180
{
sendZero() ;
}
SEND_LOW();
delayMicroseconds(TIME);
}
//=================================================================================================================
// Basic constructor
//=================================================================================================================
void TeleInfo(String version)
{
// Serial.begin(1200,SERIAL_7E1);
mySerial = new SoftwareSerial(TELEINFO_PIN, 9); // RX, TX
mySerial->begin(1200);
pgmVersion = version;
// variables initializations
ADCO = "270622224349";
OPTARIF = "----";
ISOUSC = 0;
HCHC = 0L; // compteur Heures Creuses en W
HCHP = 0L; // compteur Heures Pleines en W
PTEC = "----"; // Régime actuel : HPJB, HCJB, HPJW, HCJW, HPJR, HCJR
HHPHC = '-';
IINST = 0; // intensité instantanée en A
IMAX = 0; // intensité maxi en A
PAPP = 0; // puissance apparente en VA
MOTDETAT = "------";
}
//=================================================================================================================
// Capture des trames de Teleinfo
//=================================================================================================================
boolean readTeleInfo(boolean ethernetIsConnected)
{
#define startFrame 0x02
#define endFrame 0x03
#define startLine 0x0A
#define endLine 0x0D
#define maxFrameLen 280
int comptChar=0; // variable de comptage des caractères reçus
char charIn=0; // variable de mémorisation du caractère courant en réception
char bufferTeleinfo[21] = "";
int bufferLen = 0;
int checkSum;
ethernetIsOK = ethernetIsConnected;
int sequenceNumnber= 0; // number of information group
//--- wait for starting frame character
while (charIn != startFrame)
{ // "Start Text" STX (002 h) is the beginning of the frame
if (mySerial->available())
charIn = mySerial->read()& 0x7F; // Serial.read() vide buffer au fur et à mesure
} // fin while (tant que) pas caractère 0x02
// while (charIn != endFrame and comptChar<=maxFrameLen)
while (charIn != endFrame)
{ // tant que des octets sont disponibles en lecture : on lit les caractères
// if (Serial.available())
if (mySerial->available())
{
charIn = mySerial->read()& 0x7F;
// incrémente le compteur de caractère reçus
comptChar++;
if (charIn == startLine)
bufferLen = 0;
bufferTeleinfo[bufferLen] = charIn;
// on utilise une limite max pour éviter String trop long en cas erreur réception
// ajoute le caractère reçu au String pour les N premiers caractères
if (charIn == endLine)
{
checkSum = bufferTeleinfo[bufferLen -1];
if (chksum(bufferTeleinfo, bufferLen) == checkSum)
{// we clear the 1st character
strncpy(&bufferTeleinfo[0], &bufferTeleinfo[1], bufferLen -3);
bufferTeleinfo[bufferLen -3] = 0x00;
sequenceNumnber++;
if (! handleBuffer(bufferTeleinfo, sequenceNumnber))
{
Serial.println(F("Sequence error ..."));
return false;
}
}
else
{
Serial.println(F("Checksum error ..."));
return false;
}
}
else
bufferLen++;
}
if (comptChar > maxFrameLen)
{
Serial.println(F("Overflow error ..."));
return false;
}
}
return true;
}
//=================================================================================================================
// Frame parsing
//=================================================================================================================
//void handleBuffer(char *bufferTeleinfo, uint8_t len)
boolean handleBuffer(char *bufferTeleinfo, int sequenceNumnber)
{
// create a pointer to the first char after the space
char* resultString = strchr(bufferTeleinfo,' ') + 1;
boolean sequenceIsOK;
switch(sequenceNumnber)
{
case 1:
if (sequenceIsOK = bufferTeleinfo[0]=='A')
ADCO = String(resultString);
break;
case 2:
if (sequenceIsOK = bufferTeleinfo[0]=='O')
OPTARIF = String(resultString);
break;
case 3:
if (sequenceIsOK = bufferTeleinfo[1]=='S')
ISOUSC = atol(resultString);
break;
case 4:
if (sequenceIsOK = bufferTeleinfo[3]=='C')
HCHC = atol(resultString);
break;
case 5:
if (sequenceIsOK = bufferTeleinfo[3]=='P')
HCHP = atol(resultString);
break;
case 6:
if (sequenceIsOK = bufferTeleinfo[1]=='T')
PTEC = String(resultString);
break;
case 7:
if (sequenceIsOK = bufferTeleinfo[1]=='I')
IINST =atol(resultString);
break;
case 8:
if (sequenceIsOK = bufferTeleinfo[1]=='M')
IMAX =atol(resultString);
break;
case 9:
if (sequenceIsOK = bufferTeleinfo[1]=='A')
PAPP =atol(resultString);
break;
case 10:
if (sequenceIsOK = bufferTeleinfo[1]=='H')
HHPHC = resultString[0];
break;
case 11:
if (sequenceIsOK = bufferTeleinfo[1]=='O')
MOTDETAT = String(resultString);
break;
}
#ifdef debug
if(!sequenceIsOK)
{
Serial.print(F("Out of sequence ..."));
Serial.println(bufferTeleinfo);
}
#endif
return sequenceIsOK;
}
//=================================================================================================================
// Calculates teleinfo Checksum
//=================================================================================================================
char chksum(char *buff, uint8_t len)
{
int i;
char sum = 0;
for (i=1; i<(len-2); i++)
sum = sum + buff[i];
sum = (sum & 0x3F) + 0x20;
return(sum);
}
//=================================================================================================================
// This function displays the TeleInfo Internal counters
// It's usefull for debug purpose
//=================================================================================================================
void displayTeleInfo()
{
/*
ADCO 270622224349 B
OPTARIF HC.. <
ISOUSC 30 9
HCHC 014460852 $
HCHP 012506372 -
PTEC HP..
IINST 002 Y
IMAX 035 G
PAPP 00520 (
HHPHC C .
MOTDETAT 000000 B
*/
Serial.print(F(" "));
Serial.println();
Serial.print(F("ADCO "));
Serial.println(ADCO);
Serial.print(F("OPTARIF "));
Serial.println(OPTARIF);
Serial.print(F("ISOUSC "));
Serial.println(ISOUSC);
Serial.print(F("HCHC "));
Serial.println(HCHC);
Serial.print(F("HCHP "));
Serial.println(HCHP);
Serial.print(F("PTEC "));
Serial.println(PTEC);
Serial.print(F("IINST "));
Serial.println(IINST);
Serial.print(F("IMAX "));
Serial.println(IMAX);
Serial.print(F("PAPP "));
Serial.println(PAPP);
Serial.print(F("HHPHC "));
Serial.println(HHPHC);
Serial.print(F("MOTDETAT "));
Serial.println(MOTDETAT);
}
void encodeur_OWL_CM180()
{
if (PTEC.substring(1,2)=="C")
{
HCP=(HCHC*223666LL)/1000LL;
}
else
{
HCP=(HCHP*223666LL)/1000LL;
}
OregonMessageBuffer[0] =0x62; // imposé
OregonMessageBuffer[1] =0x80; // GH G= non décodé par RFXCOLM, H = Count
//OregonMessageBuffer[2] =0x3C; // IJ ID compteur : "L IJ 2" soit (L & 1110 )*16*16*16+I*16*16+J*16+2
// si heure creuse compteur 3D, si HP compteur 3C
if (PTEC.substring(1,2)=="C")
{
OregonMessageBuffer[2] =0x3D;
// Serial.print(F("HEURE CREUSE 0x3D")); //débug *******************************
}
else
{
OregonMessageBuffer[2] =0x3C;
}
//OregonMessageBuffer[3] =0xE1; // KL K sert pour puissance instantanée, L sert pour identifiant compteur
PAPP_arrondi=long(long(PAPP)*497/500/16);
// améliore un peu la précision de la puissance apparente encodée (le CM180 transmet la PAPP * 497/500/16)
if ((float(PAPP)*497/500/16-PAPP_arrondi)>0.5)
{
++PAPP_arrondi;
}
OregonMessageBuffer[3]=(PAPP_arrondi&0x0F)<<4;
//OregonMessageBuffer[4] =0x00; // MN puissance instantée = (P MN K)*16 soit : (P*16*16*16 + M*16*16 +N*16+K)*16*500/497. attention RFXCOM corrige cette valeur en multipliant par 16 puis 500/497.
OregonMessageBuffer[4]=(PAPP_arrondi>>4)&0xFF;
//OregonMessageBuffer[5] =0xCD; // OP Total conso : YZ WX UV ST QR O : Y*16^10 + Z*16^9..R*16 + O
OregonMessageBuffer[5] =((PAPP_arrondi>>12)&0X0F)+((HCP&0x0F)<<4);
//OregonMessageBuffer[6] =0x97; // QR sert total conso
OregonMessageBuffer[6] =(HCP>>4)&0xFF;
//OregonMessageBuffer[7] =0xCE; // ST sert total conso
OregonMessageBuffer[7] =(HCP>>12)&0xFF; // ST sert total conso
//OregonMessageBuffer[8] =0x12; // UV sert total conso
OregonMessageBuffer[8] =(HCP>>20)&0xFF; // UV sert total conso
//OregonMessageBuffer[9] =0x00; // WX sert total conso
OregonMessageBuffer[9] =(HCP>>28)&0xFF;
//OregonMessageBuffer[10] =0x00; //YZ sert total conso
OregonMessageBuffer[10] =(HCP>>36)&0xFF;
chksum_CM180= 0;
for (byte i=0; i<11; i++)
{
chksum_CM180 += long(OregonMessageBuffer[i]&0x0F) + long(OregonMessageBuffer[i]>>4) ;
}
chksum_CM180 -=2; // = =b*16^2 + d*16+ a ou [b d a]
//OregonMessageBuffer[11] =0xD0; //ab sert CHECKSUM somme(nibbles ci-dessuus)=b*16^2 + d*16+ a + 2
OregonMessageBuffer[11] =((chksum_CM180&0x0F)<<4) + ((chksum_CM180>>8)&0x0F);
//OregonMessageBuffer[12] =0xF6; //cd d sert checksum, a non décodé par RFXCOM
OregonMessageBuffer[12] =(int(chksum_CM180>>4)&0x0F); //C = 0 mais inutilisé
}
//************************************************************************************
void setup() {
Serial.begin(115200); // pour la console, enlever les barres de commentaires ci dessous pour displayTeleInfo()
TeleInfo(version);
}
void loop() {
teleInfoReceived=readTeleInfo(true);
if (teleInfoReceived)
{
encodeur_OWL_CM180();
mySerial->end(); //NECESSAIRE !! arrête les interruptions de softwareserial (lecture du port téléinfo) pour émission des trames OWL
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer)); // Send the Message over RF
mySerial->begin(1200); //NECESSAIRE !! relance les interuptions pour la lecture du port téléinfo
displayTeleInfo(); // console pour voir les trames téléinfo
// ajout d'un delais de 12s apres chaque trame envoyés pour éviter d'envoyer
// en permanence des informations à domoticz et de créer des interférances
delay(12000);
}
}

View File

@@ -0,0 +1,447 @@
/*
* connectingStuff, Oregon Scientific v2.1 Emitter
* http://connectingstuff.net/blog/encodage-protocoles-oregon-scientific-sur-arduino
* and
* http://blog.idleman.fr/raspberry-pi-18-construire-une-sonde-de-temperature-radio-pour-7e/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Narcoleptic.h>
#define THN132N
const byte TEMPERATURE_1_PIN = 3; //A5;
const byte LUMINOSITE_PIN=A1;
const byte TRANSMITTER_PIN = 9;
const byte LED_PIN = 13;
#define DEBUG TRUE
#define SEND_MESSAGE_DELAY 30000 // Ne pas dépasser 32000 !! Delay in ms between each value's extraction
#define SEND_433_PAUSE 160 // 16 multiple
// On crée une instance de la classe oneWire pour communiquer avec le materiel on wire (dont le capteur ds18b20)
OneWire oneWire(TEMPERATURE_1_PIN);
//On passe la reference onewire à la classe DallasTemperature qui vas nous permettre de relever la temperature simplement
DallasTemperature sensors(&oneWire);
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
#define SEND_HIGH() digitalWrite(TRANSMITTER_PIN, HIGH)
#define SEND_LOW() digitalWrite(TRANSMITTER_PIN, LOW)
// Buffer for Oregon message
#ifdef THN132N
byte OregonMessageBuffer[8];
#else
byte OregonMessageBuffer[9];
#endif
/**
* \brief Send logical "0" over RF
* \details azero bit be represented by an off-to-on transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendZero(void)
{
SEND_HIGH();
delayMicroseconds(TIME);
SEND_LOW();
delayMicroseconds(TWOTIME);
SEND_HIGH();
delayMicroseconds(TIME);
}
/**
* \brief Send logical "1" over RF
* \details a one bit be represented by an on-to-off transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendOne(void)
{
SEND_LOW();
delayMicroseconds(TIME);
SEND_HIGH();
delayMicroseconds(TWOTIME);
SEND_LOW();
delayMicroseconds(TIME);
}
/**
* Send a bits quarter (4 bits = MSB from 8 bits value) over RF
*
* @param data Source data to process and sent
*/
/**
* \brief Send a bits quarter (4 bits = MSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterMSB(const byte data)
{
(bitRead(data, 4)) ? sendOne() : sendZero();
(bitRead(data, 5)) ? sendOne() : sendZero();
(bitRead(data, 6)) ? sendOne() : sendZero();
(bitRead(data, 7)) ? sendOne() : sendZero();
}
/**
* \brief Send a bits quarter (4 bits = LSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterLSB(const byte data)
{
(bitRead(data, 0)) ? sendOne() : sendZero();
(bitRead(data, 1)) ? sendOne() : sendZero();
(bitRead(data, 2)) ? sendOne() : sendZero();
(bitRead(data, 3)) ? sendOne() : sendZero();
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Send a buffer over RF
* \param data Data to send
* \param size size of data to send
*/
void sendData(byte *data, byte size)
{
for(byte i = 0; i < size; ++i)
{
sendQuarterLSB(data[i]);
sendQuarterMSB(data[i]);
}
}
/**
* \brief Send an Oregon message
* \param data The Oregon message
*/
void sendOregon(byte *data, byte size)
{
sendPreamble();
//sendSync();
sendData(data, size);
sendPostamble();
}
/**
* \brief Send preamble
* \details The preamble consists of 16 "1" bits
*/
inline void sendPreamble(void)
{
byte PREAMBLE[]={0xFF,0xFF};
sendData(PREAMBLE, 2);
}
/**
* \brief Send postamble
* \details The postamble consists of 8 "0" bits
*/
inline void sendPostamble(void)
{
#ifdef THN132N
sendQuarterLSB(0x00);
#else
byte POSTAMBLE[]={0x00};
sendData(POSTAMBLE, 1);
#endif
}
/**
* \brief Send sync nibble
* \details The sync is 0xA. It is not use in this version since the sync nibble
* \ is include in the Oregon message to send.
*/
inline void sendSync(void)
{
sendQuarterLSB(0xA);
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Set the sensor type
* \param data Oregon message
* \param type Sensor type
*/
inline void setType(byte *data, byte* type)
{
data[0] = type[0];
data[1] = type[1];
}
/**
* \brief Set the sensor channel
* \param data Oregon message
* \param channel Sensor channel (0x10, 0x20, 0x30)
*/
inline void setChannel(byte *data, byte channel)
{
data[2] = channel;
}
/**
* \brief Set the sensor ID
* \param data Oregon message
* \param ID Sensor unique ID
*/
inline void setId(byte *data, byte ID)
{
data[3] = ID;
}
/**
* \brief Set the sensor battery level
* \param data Oregon message
* \param level Battery level (0 = low, 1 = high)
*/
void setBatteryLevel(byte *data, byte level)
{
if(!level) data[4] = 0x0C;
else data[4] = 0x00;
}
/**
* \brief Set the sensor temperature
* \param data Oregon message
* \param temp the temperature
*/
void setTemperature(byte *data, float temp)
{
// Set temperature sign
if(temp < 0)
{
data[6] = 0x08;
temp *= -1;
}
else
{
data[6] = 0x00;
}
// Determine decimal and float part
int tempInt = (int)temp;
int td = (int)(tempInt / 10);
int tf = (int)round((float)((float)tempInt/10 - (float)td) * 10);
int tempFloat = (int)round((float)(temp - (float)tempInt) * 10);
// Set temperature decimal part
data[5] = (td << 4);
data[5] |= tf;
// Set temperature float part
data[4] |= (tempFloat << 4);
}
/**
* \brief Set the sensor humidity
* \param data Oregon message
* \param hum the humidity
*/
void setHumidity(byte* data, byte hum)
{
data[7] = (hum/10);
data[6] |= (hum - data[7]*10) << 4;
Serial.print("Hum=" + hum);
}
/**
* \brief Sum data for checksum
* \param count number of bit to sum
* \param data Oregon message
*/
int Sum(byte count, const byte* data)
{
int s = 0;
for(byte i = 0; i<count;i++)
{
s += (data[i]&0xF0) >> 4;
s += (data[i]&0xF);
}
if(int(count) != count)
s += (data[count]&0xF0) >> 4;
return s;
}
/**
* \brief Calculate checksum
* \param data Oregon message
*/
void calculateAndSetChecksum(byte* data)
{
#ifdef THN132N
int s = ((Sum(6, data) + (data[6]&0xF) - 0xa) & 0xff);
data[6] |= (s&0x0F) << 4; data[7] = (s&0xF0) >> 4;
#else
data[8] = ((Sum(8, data) - 0xa) & 0xFF);
#endif
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
void setup()
{
pinMode(TRANSMITTER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
#ifdef DEBUG
Serial.begin(9600);
Serial.println("\n[Oregon V2.1 encoder]");
#endif
SEND_LOW();
//On initialise le capteur de temperature
sensors.begin();
#ifdef THN132N
// Create the Oregon message for a temperature only sensor (TNHN132N)
byte ID[] = {0xEA,0x4C};
#ifdef DEBUG
Serial.println("Def THN132");
#endif
#else
// Create the Oregon message for a temperature/humidity sensor (THGR2228N)
byte ID[] = {0x1A,0x2D};
#ifdef DEBUG
Serial.println("UnDef THN132");
#endif
#endif
setType(OregonMessageBuffer, ID);
setChannel(OregonMessageBuffer, 0x20);
// ATMEGA 1 = BC
// TEST OREGON BB
// TEST Luminosite BD
setId(OregonMessageBuffer, 0xBC); // ID BB BC BD
Narcoleptic.delay(1000);
}
void loop()
{
digitalWrite(13, HIGH);
// Read Vcc value
long currentVcc = readVcc();
digitalWrite(13, LOW);
if (currentVcc > 5000) {
currentVcc = 5000;
}
#ifdef DEBUG
Serial.println(currentVcc);
#endif
// Get Temperature, humidity and battery level from sensors
// (ie: 1wire DS18B20 for température, ...)
if (currentVcc < 3800) {
setBatteryLevel(OregonMessageBuffer, 0); // 0 : low, 1 : high
} else {
setBatteryLevel(OregonMessageBuffer, 1); // 0 : low, 1 : high
}
// need addaptation here
// Ajout perso
//Lancement de la commande de récuperation de la temperature
sensors.requestTemperatures();
//Serial.println(sensors.getTempCByIndex(0));
//if (LUMINOSITE_PIN != 0) {
//setTemperature(OregonMessageBuffer,analogRead(LUMINOSITE_PIN));
//} else {
setTemperature(OregonMessageBuffer,sensors.getTempCByIndex(0));
//}
// setTemperature(OregonMessageBuffer, 11.2);
#ifndef THN132N
// Set Humidity
setHumidity(OregonMessageBuffer, 52);
#endif
// Calculate the checksum
calculateAndSetChecksum(OregonMessageBuffer);
// Show the Oregon Message
#ifdef DEBUG
for (byte i = 0; i < sizeof(OregonMessageBuffer); ++i) {
Serial.print(OregonMessageBuffer[i] >> 4, HEX);
Serial.print(OregonMessageBuffer[i] & 0x0F, HEX);
}
Serial.println("");
#endif
// Send the Message over RF
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
// Send a "pause"
SEND_LOW();
delayMicroseconds(TWOTIME*8);
// Send a copie of the first message. The v2.1 protocol send the
// message two time
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
Narcoleptic.delay(SEND_433_PAUSE);
// Wait for 30 seconds before send a new message
SEND_LOW();
//delay(3000);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
}
//--------------------------------------------------------------------------------------------------
// Read current supply voltage
//--------------------------------------------------------------------------------------------------
long readVcc() {
bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
long result;
// Read 1.1V reference against Vcc
#if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
#endif
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate Vcc in mV
ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
return result; // Vcc in millivolts
}

View File

@@ -0,0 +1,450 @@
/*
* connectingStuff, Oregon Scientific v2.1 Emitter
* http://connectingstuff.net/blog/encodage-protocoles-oregon-scientific-sur-arduino
* and
* http://blog.idleman.fr/raspberry-pi-18-construire-une-sonde-de-temperature-radio-pour-7e/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Narcoleptic.h>
#define THN132N
const byte TEMPERATURE_1_PIN = 3; //A5;
const byte LUMINOSITE_PIN=A1;
const byte TRANSMITTER_PIN = 9;
const byte LED_PIN = 13;
#define DEBUG TRUE
#define SEND_MESSAGE_DELAY 30000 // Ne pas dépasser 32000 !! Delay in ms between each value's extraction
#define SEND_433_PAUSE 160 // 16 multiple
// On crée une instance de la classe oneWire pour communiquer avec le materiel on wire (dont le capteur ds18b20)
OneWire oneWire(TEMPERATURE_1_PIN);
//On passe la reference onewire à la classe DallasTemperature qui vas nous permettre de relever la temperature simplement
DallasTemperature sensors(&oneWire);
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
#define SEND_HIGH() digitalWrite(TRANSMITTER_PIN, HIGH)
#define SEND_LOW() digitalWrite(TRANSMITTER_PIN, LOW)
// Buffer for Oregon message
#ifdef THN132N
byte OregonMessageBuffer[8];
#else
byte OregonMessageBuffer[9];
#endif
/**
* \brief Send logical "0" over RF
* \details azero bit be represented by an off-to-on transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendZero(void)
{
SEND_HIGH();
delayMicroseconds(TIME);
SEND_LOW();
delayMicroseconds(TWOTIME);
SEND_HIGH();
delayMicroseconds(TIME);
}
/**
* \brief Send logical "1" over RF
* \details a one bit be represented by an on-to-off transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendOne(void)
{
SEND_LOW();
delayMicroseconds(TIME);
SEND_HIGH();
delayMicroseconds(TWOTIME);
SEND_LOW();
delayMicroseconds(TIME);
}
/**
* Send a bits quarter (4 bits = MSB from 8 bits value) over RF
*
* @param data Source data to process and sent
*/
/**
* \brief Send a bits quarter (4 bits = MSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterMSB(const byte data)
{
(bitRead(data, 4)) ? sendOne() : sendZero();
(bitRead(data, 5)) ? sendOne() : sendZero();
(bitRead(data, 6)) ? sendOne() : sendZero();
(bitRead(data, 7)) ? sendOne() : sendZero();
}
/**
* \brief Send a bits quarter (4 bits = LSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterLSB(const byte data)
{
(bitRead(data, 0)) ? sendOne() : sendZero();
(bitRead(data, 1)) ? sendOne() : sendZero();
(bitRead(data, 2)) ? sendOne() : sendZero();
(bitRead(data, 3)) ? sendOne() : sendZero();
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Send a buffer over RF
* \param data Data to send
* \param size size of data to send
*/
void sendData(byte *data, byte size)
{
for(byte i = 0; i < size; ++i)
{
sendQuarterLSB(data[i]);
sendQuarterMSB(data[i]);
}
}
/**
* \brief Send an Oregon message
* \param data The Oregon message
*/
void sendOregon(byte *data, byte size)
{
sendPreamble();
//sendSync();
sendData(data, size);
sendPostamble();
}
/**
* \brief Send preamble
* \details The preamble consists of 16 "1" bits
*/
inline void sendPreamble(void)
{
byte PREAMBLE[]={0xFF,0xFF};
sendData(PREAMBLE, 2);
}
/**
* \brief Send postamble
* \details The postamble consists of 8 "0" bits
*/
inline void sendPostamble(void)
{
#ifdef THN132N
sendQuarterLSB(0x00);
#else
byte POSTAMBLE[]={0x00};
sendData(POSTAMBLE, 1);
#endif
}
/**
* \brief Send sync nibble
* \details The sync is 0xA. It is not use in this version since the sync nibble
* \ is include in the Oregon message to send.
*/
inline void sendSync(void)
{
sendQuarterLSB(0xA);
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Set the sensor type
* \param data Oregon message
* \param type Sensor type
*/
inline void setType(byte *data, byte* type)
{
data[0] = type[0];
data[1] = type[1];
}
/**
* \brief Set the sensor channel
* \param data Oregon message
* \param channel Sensor channel (0x10, 0x20, 0x30)
*/
inline void setChannel(byte *data, byte channel)
{
data[2] = channel;
}
/**
* \brief Set the sensor ID
* \param data Oregon message
* \param ID Sensor unique ID
*/
inline void setId(byte *data, byte ID)
{
data[3] = ID;
}
/**
* \brief Set the sensor battery level
* \param data Oregon message
* \param level Battery level (0 = low, 1 = high)
*/
void setBatteryLevel(byte *data, byte level)
{
if(!level) data[4] = 0x0C;
else data[4] = 0x00;
}
/**
* \brief Set the sensor temperature
* \param data Oregon message
* \param temp the temperature
*/
void setTemperature(byte *data, float temp)
{
// Set temperature sign
if(temp < 0)
{
data[6] = 0x08;
temp *= -1;
}
else
{
data[6] = 0x00;
}
// Determine decimal and float part
int tempInt = (int)temp;
int td = (int)(tempInt / 10);
int tf = (int)round((float)((float)tempInt/10 - (float)td) * 10);
int tempFloat = (int)round((float)(temp - (float)tempInt) * 10);
// Set temperature decimal part
data[5] = (td << 4);
data[5] |= tf;
// Set temperature float part
data[4] |= (tempFloat << 4);
}
/**
* \brief Set the sensor humidity
* \param data Oregon message
* \param hum the humidity
*/
void setHumidity(byte* data, byte hum)
{
data[7] = (hum/10);
data[6] |= (hum - data[7]*10) << 4;
Serial.print("Hum=" + hum);
}
/**
* \brief Sum data for checksum
* \param count number of bit to sum
* \param data Oregon message
*/
int Sum(byte count, const byte* data)
{
int s = 0;
for(byte i = 0; i<count;i++)
{
s += (data[i]&0xF0) >> 4;
s += (data[i]&0xF);
}
if(int(count) != count)
s += (data[count]&0xF0) >> 4;
return s;
}
/**
* \brief Calculate checksum
* \param data Oregon message
*/
void calculateAndSetChecksum(byte* data)
{
#ifdef THN132N
int s = ((Sum(6, data) + (data[6]&0xF) - 0xa) & 0xff);
data[6] |= (s&0x0F) << 4; data[7] = (s&0xF0) >> 4;
#else
data[8] = ((Sum(8, data) - 0xa) & 0xFF);
#endif
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
void setup()
{
pinMode(TRANSMITTER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
#ifdef DEBUG
Serial.begin(9600);
Serial.println("\n[Oregon V2.1 encoder]");
#endif
SEND_LOW();
//On initialise le capteur de temperature
sensors.begin();
#ifdef THN132N
// Create the Oregon message for a temperature only sensor (TNHN132N)
byte ID[] = {0xEA,0x4C};
#ifdef DEBUG
Serial.println("Def THN132");
#endif
#else
// Create the Oregon message for a temperature/humidity sensor (THGR2228N)
byte ID[] = {0x1A,0x2D};
#ifdef DEBUG
Serial.println("UnDef THN132");
#endif
#endif
setType(OregonMessageBuffer, ID);
setChannel(OregonMessageBuffer, 0x20);
// ATMEGA 1 = BC
// TEST OREGON BB
// TEST Luminosite BD
setId(OregonMessageBuffer, 0xBE); // ID BB BC BD
Narcoleptic.delay(1000);
}
void loop()
{
digitalWrite(13, HIGH);
// Read Vcc value
long currentVcc = readVcc();
digitalWrite(13, LOW);
if (currentVcc > 5000) {
currentVcc = 5000;
}
#ifdef DEBUG
Serial.println(currentVcc);
#endif
// Get Temperature, humidity and battery level from sensors
// (ie: 1wire DS18B20 for température, ...)
if (currentVcc < 3800) {
setBatteryLevel(OregonMessageBuffer, 0); // 0 : low, 1 : high
} else {
setBatteryLevel(OregonMessageBuffer, 1); // 0 : low, 1 : high
}
// need addaptation here
// Ajout perso
//Lancement de la commande de récuperation de la temperature
sensors.requestTemperatures();
//Serial.println(sensors.getTempCByIndex(0));
//if (LUMINOSITE_PIN != 0) {
//setTemperature(OregonMessageBuffer,analogRead(LUMINOSITE_PIN));
//} else {
setTemperature(OregonMessageBuffer,sensors.getTempCByIndex(0));
//}
// setTemperature(OregonMessageBuffer, 11.2);
#ifndef THN132N
// Set Humidity
setHumidity(OregonMessageBuffer, 52);
#endif
// Calculate the checksum
calculateAndSetChecksum(OregonMessageBuffer);
// Show the Oregon Message
#ifdef DEBUG
for (byte i = 0; i < sizeof(OregonMessageBuffer); ++i) {
Serial.print(OregonMessageBuffer[i] >> 4, HEX);
Serial.print(OregonMessageBuffer[i] & 0x0F, HEX);
}
Serial.println("");
#endif
// Send the Message over RF
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
// Send a "pause"
SEND_LOW();
delayMicroseconds(TWOTIME*8);
// Send a copie of the first message. The v2.1 protocol send the
// message two time
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
Narcoleptic.delay(SEND_433_PAUSE);
// Wait for 30 seconds before send a new message
SEND_LOW();
//delay(3000);
// disable ADC
//ADCSRA = 0;
Narcoleptic.delay(SEND_MESSAGE_DELAY);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
}
//--------------------------------------------------------------------------------------------------
// Read current supply voltage
//--------------------------------------------------------------------------------------------------
long readVcc() {
bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
long result;
// Read 1.1V reference against Vcc
#if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
#endif
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate Vcc in mV
ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
return result; // Vcc in millivolts
}

View File

@@ -0,0 +1,493 @@
/*
* connectingStuff, Oregon Scientific v2.1 Emitter
* http://connectingstuff.net/blog/encodage-protocoles-oregon-scientific-sur-arduino
* and
* http://blog.idleman.fr/raspberry-pi-18-construire-une-sonde-de-temperature-radio-pour-7e/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <OneWire.h>
#include <DallasTemperature.h>
#include <avr/sleep.h>
#include <avr/power.h> // Power management
#include <avr/wdt.h>
//#define THN132N
const byte TEMPERATURE_1_PIN = 3; //A5;
const byte LUMINOSITE_PIN=A1;
const byte TRANSMITTER_PIN = 9;
const byte LED_PIN = 13;
#define DEBUG TRUE
// On crée une instance de la classe oneWire pour communiquer avec le materiel on wire (dont le capteur ds18b20)
OneWire oneWire(TEMPERATURE_1_PIN);
//On passe la reference onewire à la classe DallasTemperature qui vas nous permettre de relever la temperature simplement
DallasTemperature sensors(&oneWire);
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
#define SEND_HIGH() digitalWrite(TRANSMITTER_PIN, HIGH)
#define SEND_LOW() digitalWrite(TRANSMITTER_PIN, LOW)
// Buffer for Oregon message
#ifdef THN132N
byte OregonMessageBuffer[8];
#else
byte OregonMessageBuffer[9];
#endif
/**
* \brief Send logical "0" over RF
* \details azero bit be represented by an off-to-on transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendZero(void)
{
SEND_HIGH();
delayMicroseconds(TIME);
SEND_LOW();
delayMicroseconds(TWOTIME);
SEND_HIGH();
delayMicroseconds(TIME);
}
/**
* \brief Send logical "1" over RF
* \details a one bit be represented by an on-to-off transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendOne(void)
{
SEND_LOW();
delayMicroseconds(TIME);
SEND_HIGH();
delayMicroseconds(TWOTIME);
SEND_LOW();
delayMicroseconds(TIME);
}
/**
* Send a bits quarter (4 bits = MSB from 8 bits value) over RF
*
* @param data Source data to process and sent
*/
/**
* \brief Send a bits quarter (4 bits = MSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterMSB(const byte data)
{
(bitRead(data, 4)) ? sendOne() : sendZero();
(bitRead(data, 5)) ? sendOne() : sendZero();
(bitRead(data, 6)) ? sendOne() : sendZero();
(bitRead(data, 7)) ? sendOne() : sendZero();
}
/**
* \brief Send a bits quarter (4 bits = LSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterLSB(const byte data)
{
(bitRead(data, 0)) ? sendOne() : sendZero();
(bitRead(data, 1)) ? sendOne() : sendZero();
(bitRead(data, 2)) ? sendOne() : sendZero();
(bitRead(data, 3)) ? sendOne() : sendZero();
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Send a buffer over RF
* \param data Data to send
* \param size size of data to send
*/
void sendData(byte *data, byte size)
{
for(byte i = 0; i < size; ++i)
{
sendQuarterLSB(data[i]);
sendQuarterMSB(data[i]);
}
}
/**
* \brief Send an Oregon message
* \param data The Oregon message
*/
void sendOregon(byte *data, byte size)
{
sendPreamble();
//sendSync();
sendData(data, size);
sendPostamble();
}
/**
* \brief Send preamble
* \details The preamble consists of 16 "1" bits
*/
inline void sendPreamble(void)
{
byte PREAMBLE[]={0xFF,0xFF};
sendData(PREAMBLE, 2);
}
/**
* \brief Send postamble
* \details The postamble consists of 8 "0" bits
*/
inline void sendPostamble(void)
{
#ifdef THN132N
sendQuarterLSB(0x00);
#else
byte POSTAMBLE[]={0x00};
sendData(POSTAMBLE, 1);
#endif
}
/**
* \brief Send sync nibble
* \details The sync is 0xA. It is not use in this version since the sync nibble
* \ is include in the Oregon message to send.
*/
inline void sendSync(void)
{
sendQuarterLSB(0xA);
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Set the sensor type
* \param data Oregon message
* \param type Sensor type
*/
inline void setType(byte *data, byte* type)
{
data[0] = type[0];
data[1] = type[1];
}
/**
* \brief Set the sensor channel
* \param data Oregon message
* \param channel Sensor channel (0x10, 0x20, 0x30)
*/
inline void setChannel(byte *data, byte channel)
{
data[2] = channel;
}
/**
* \brief Set the sensor ID
* \param data Oregon message
* \param ID Sensor unique ID
*/
inline void setId(byte *data, byte ID)
{
data[3] = ID;
}
/**
* \brief Set the sensor battery level
* \param data Oregon message
* \param level Battery level (0 = low, 1 = high)
*/
void setBatteryLevel(byte *data, byte level)
{
if(!level) data[4] = 0x0C;
else data[4] = 0x00;
}
/**
* \brief Set the sensor temperature
* \param data Oregon message
* \param temp the temperature
*/
void setTemperature(byte *data, float temp)
{
// Set temperature sign
if(temp < 0)
{
data[6] = 0x08;
temp *= -1;
}
else
{
data[6] = 0x00;
}
// Determine decimal and float part
int tempInt = (int)temp;
int td = (int)(tempInt / 10);
int tf = (int)round((float)((float)tempInt/10 - (float)td) * 10);
int tempFloat = (int)round((float)(temp - (float)tempInt) * 10);
// Set temperature decimal part
data[5] = (td << 4);
data[5] |= tf;
// Set temperature float part
data[4] |= (tempFloat << 4);
}
/**
* \brief Set the sensor humidity
* \param data Oregon message
* \param hum the humidity
*/
void setHumidity(byte* data, byte hum)
{
data[7] = (hum/10);
data[6] |= (hum - data[7]*10) << 4;
#ifdef DEBUG
Serial.print("Hum=" + hum);
#endif
}
/**
* \brief Sum data for checksum
* \param count number of bit to sum
* \param data Oregon message
*/
int Sum(byte count, const byte* data)
{
int s = 0;
for(byte i = 0; i<count;i++)
{
s += (data[i]&0xF0) >> 4;
s += (data[i]&0xF);
}
if(int(count) != count)
s += (data[count]&0xF0) >> 4;
return s;
}
/**
* \brief Calculate checksum
* \param data Oregon message
*/
void calculateAndSetChecksum(byte* data)
{
#ifdef THN132N
int s = ((Sum(6, data) + (data[6]&0xF) - 0xa) & 0xff);
data[6] |= (s&0x0F) << 4; data[7] = (s&0xF0) >> 4;
#else
data[8] = ((Sum(8, data) - 0xa) & 0xFF);
#endif
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
void setup()
{
pinMode(TRANSMITTER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
#ifdef DEBUG
Serial.begin(115200);
Serial.println("\n[Oregon V2.1 encoder]");
#endif
SEND_LOW();
//On initialise le capteur de temperature
sensors.begin();
#ifdef THN132N
// Create the Oregon message for a temperature only sensor (TNHN132N)
byte ID[] = {0xEA,0x4C};
#ifdef DEBUG
Serial.println("Def THN132");
#endif
#else
// Create the Oregon message for a temperature/humidity sensor (THGR2228N)
byte ID[] = {0x1A,0x2D};
#ifdef DEBUG
Serial.println("UnDef THN132");
#endif
#endif
setType(OregonMessageBuffer, ID);
setChannel(OregonMessageBuffer, 0x20);
// ATMEGA 1 = BC
// TEST OREGON BB
// TEST Luminosite BD
setId(OregonMessageBuffer, 0xBD); // ID BB BC BD
delay(1000);
}
void loop()
{
digitalWrite(LED_PIN, HIGH);
// Read Vcc value
long currentVcc = readVcc();
digitalWrite(LED_PIN, LOW);
if (currentVcc > 5000) {
currentVcc = 5000;
}
#ifdef DEBUG
Serial.println(currentVcc);
#endif
// Get Temperature, humidity and battery level from sensors
// (ie: 1wire DS18B20 for température, ...)
if (currentVcc < 3000) {
setBatteryLevel(OregonMessageBuffer, 0); // 0 : low, 1 : high
} else {
setBatteryLevel(OregonMessageBuffer, 1); // 0 : low, 1 : high
}
// need addaptation here
// Ajout perso
//Lancement de la commande de récuperation de la temperature
sensors.requestTemperatures();
//Serial.println(sensors.getTempCByIndex(0));
//if (LUMINOSITE_PIN != 0) {
//setTemperature(OregonMessageBuffer,analogRead(LUMINOSITE_PIN));
//} else {
setTemperature(OregonMessageBuffer,15); //sensors.getTempCByIndex(0));
//}
// setTemperature(OregonMessageBuffer, 11.2);
#ifndef THN132N
// Set Humidity
setHumidity(OregonMessageBuffer, 52);
#endif
// Calculate the checksum
calculateAndSetChecksum(OregonMessageBuffer);
// Show the Oregon Message
#ifdef DEBUG
for (byte i = 0; i < sizeof(OregonMessageBuffer); ++i) {
Serial.print(OregonMessageBuffer[i] >> 4, HEX);
Serial.print(OregonMessageBuffer[i] & 0x0F, HEX);
}
Serial.println("");
#endif
// Send the Message over RF
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
// Send a "pause"
SEND_LOW();
delayMicroseconds(TWOTIME*8);
// Send a copie of the first message. The v2.1 protocol send the
// message two time
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
delay(1000);
// Wait for 30 seconds before send a new message
SEND_LOW();
//delay(3000);
// disable ADC
//ADCSRA = 0;
// sleep for a total of 64 seconds (8 x 8)
for (int i = 0; i < 8; i++) {
myWatchdogEnable ();
}
}
//--------------------------------------------------------------------------------------------------
// Read current supply voltage
//--------------------------------------------------------------------------------------------------
long readVcc() {
bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
long result;
// Read 1.1V reference against Vcc
#if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
#endif
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate Vcc in mV
ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
return result; // Vcc in millivolts
}
// watchdog interrupt
ISR (WDT_vect)
{
wdt_disable(); // disable watchdog
} // end of WDT_vect
void myWatchdogEnable()
{
// clear various "reset" flags
MCUSR = 0;
// allow changes, disable reset
WDTCSR = bit (WDCE) | bit (WDE);
// set interrupt mode and an interval
WDTCSR = bit (WDIE) | bit (WDP3) | bit (WDP0); // set WDIE, and 8 seconds delay
wdt_reset(); // pat the dog
byte old_ADCSRA = ADCSRA;
// disable ADC to save power
ADCSRA = 0;
// slow clock to divide by 256
// clock_prescale_set (clock_div_256);
// ready to sleep
set_sleep_mode (SLEEP_MODE_PWR_DOWN);
sleep_enable();
// turn off brown-out enable in software
MCUCR = bit (BODS) | bit (BODSE);
MCUCR = bit (BODS);
sleep_cpu ();
// cancel sleep as a precaution
sleep_disable();
power_all_enable (); // enable modules again
// reenable ADC
ADCSRA = old_ADCSRA;
}

View File

@@ -0,0 +1,491 @@
/*
* connectingStuff, Oregon Scientific v2.1 Emitter
* http://connectingstuff.net/blog/encodage-protocoles-oregon-scientific-sur-arduino
* and
* http://blog.idleman.fr/raspberry-pi-18-construire-une-sonde-de-temperature-radio-pour-7e/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <OneWire.h>
#include <DallasTemperature.h>
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
#define THN132N
const byte TEMPERATURE_1_PIN = 3; //A5;
const byte LUMINOSITE_PIN=A1;
const byte TRANSMITTER_PIN = 9;
const byte LED_PIN = 13;
#define DEBUG TRUE
#define SEND_MESSAGE_DELAY 30000 // Ne pas dépasser 32000 !! Delay in ms between each value's extraction
#define SEND_433_PAUSE 160 // 16 multiple
// On crée une instance de la classe oneWire pour communiquer avec le materiel on wire (dont le capteur ds18b20)
OneWire oneWire(TEMPERATURE_1_PIN);
//On passe la reference onewire à la classe DallasTemperature qui vas nous permettre de relever la temperature simplement
DallasTemperature sensors(&oneWire);
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
#define SEND_HIGH() digitalWrite(TRANSMITTER_PIN, HIGH)
#define SEND_LOW() digitalWrite(TRANSMITTER_PIN, LOW)
// Buffer for Oregon message
#ifdef THN132N
byte OregonMessageBuffer[8];
#else
byte OregonMessageBuffer[9];
#endif
/**
* \brief Send logical "0" over RF
* \details azero bit be represented by an off-to-on transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendZero(void)
{
SEND_HIGH();
delayMicroseconds(TIME);
SEND_LOW();
delayMicroseconds(TWOTIME);
SEND_HIGH();
delayMicroseconds(TIME);
}
/**
* \brief Send logical "1" over RF
* \details a one bit be represented by an on-to-off transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendOne(void)
{
SEND_LOW();
delayMicroseconds(TIME);
SEND_HIGH();
delayMicroseconds(TWOTIME);
SEND_LOW();
delayMicroseconds(TIME);
}
/**
* Send a bits quarter (4 bits = MSB from 8 bits value) over RF
*
* @param data Source data to process and sent
*/
/**
* \brief Send a bits quarter (4 bits = MSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterMSB(const byte data)
{
(bitRead(data, 4)) ? sendOne() : sendZero();
(bitRead(data, 5)) ? sendOne() : sendZero();
(bitRead(data, 6)) ? sendOne() : sendZero();
(bitRead(data, 7)) ? sendOne() : sendZero();
}
/**
* \brief Send a bits quarter (4 bits = LSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterLSB(const byte data)
{
(bitRead(data, 0)) ? sendOne() : sendZero();
(bitRead(data, 1)) ? sendOne() : sendZero();
(bitRead(data, 2)) ? sendOne() : sendZero();
(bitRead(data, 3)) ? sendOne() : sendZero();
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Send a buffer over RF
* \param data Data to send
* \param size size of data to send
*/
void sendData(byte *data, byte size)
{
for(byte i = 0; i < size; ++i)
{
sendQuarterLSB(data[i]);
sendQuarterMSB(data[i]);
}
}
/**
* \brief Send an Oregon message
* \param data The Oregon message
*/
void sendOregon(byte *data, byte size)
{
sendPreamble();
//sendSync();
sendData(data, size);
sendPostamble();
}
/**
* \brief Send preamble
* \details The preamble consists of 16 "1" bits
*/
inline void sendPreamble(void)
{
byte PREAMBLE[]={0xFF,0xFF};
sendData(PREAMBLE, 2);
}
/**
* \brief Send postamble
* \details The postamble consists of 8 "0" bits
*/
inline void sendPostamble(void)
{
#ifdef THN132N
sendQuarterLSB(0x00);
#else
byte POSTAMBLE[]={0x00};
sendData(POSTAMBLE, 1);
#endif
}
/**
* \brief Send sync nibble
* \details The sync is 0xA. It is not use in this version since the sync nibble
* \ is include in the Oregon message to send.
*/
inline void sendSync(void)
{
sendQuarterLSB(0xA);
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Set the sensor type
* \param data Oregon message
* \param type Sensor type
*/
inline void setType(byte *data, byte* type)
{
data[0] = type[0];
data[1] = type[1];
}
/**
* \brief Set the sensor channel
* \param data Oregon message
* \param channel Sensor channel (0x10, 0x20, 0x30)
*/
inline void setChannel(byte *data, byte channel)
{
data[2] = channel;
}
/**
* \brief Set the sensor ID
* \param data Oregon message
* \param ID Sensor unique ID
*/
inline void setId(byte *data, byte ID)
{
data[3] = ID;
}
/**
* \brief Set the sensor battery level
* \param data Oregon message
* \param level Battery level (0 = low, 1 = high)
*/
void setBatteryLevel(byte *data, byte level)
{
if(!level) data[4] = 0x0C;
else data[4] = 0x00;
}
/**
* \brief Set the sensor temperature
* \param data Oregon message
* \param temp the temperature
*/
void setTemperature(byte *data, float temp)
{
// Set temperature sign
if(temp < 0)
{
data[6] = 0x08;
temp *= -1;
}
else
{
data[6] = 0x00;
}
// Determine decimal and float part
int tempInt = (int)temp;
int td = (int)(tempInt / 10);
int tf = (int)round((float)((float)tempInt/10 - (float)td) * 10);
int tempFloat = (int)round((float)(temp - (float)tempInt) * 10);
// Set temperature decimal part
data[5] = (td << 4);
data[5] |= tf;
// Set temperature float part
data[4] |= (tempFloat << 4);
}
/**
* \brief Set the sensor humidity
* \param data Oregon message
* \param hum the humidity
*/
void setHumidity(byte* data, byte hum)
{
data[7] = (hum/10);
data[6] |= (hum - data[7]*10) << 4;
Serial.print("Hum=" + hum);
}
/**
* \brief Sum data for checksum
* \param count number of bit to sum
* \param data Oregon message
*/
int Sum(byte count, const byte* data)
{
int s = 0;
for(byte i = 0; i<count;i++)
{
s += (data[i]&0xF0) >> 4;
s += (data[i]&0xF);
}
if(int(count) != count)
s += (data[count]&0xF0) >> 4;
return s;
}
/**
* \brief Calculate checksum
* \param data Oregon message
*/
void calculateAndSetChecksum(byte* data)
{
#ifdef THN132N
int s = ((Sum(6, data) + (data[6]&0xF) - 0xa) & 0xff);
data[6] |= (s&0x0F) << 4; data[7] = (s&0xF0) >> 4;
#else
data[8] = ((Sum(8, data) - 0xa) & 0xFF);
#endif
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
void setup()
{
pinMode(TRANSMITTER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
#ifdef DEBUG
Serial.begin(115200);
Serial.println("\n[Oregon V2.1 encoder]");
#endif
SEND_LOW();
//On initialise le capteur de temperature
sensors.begin();
#ifdef THN132N
// Create the Oregon message for a temperature only sensor (TNHN132N)
byte ID[] = {0xEA,0x4C};
#ifdef DEBUG
Serial.println("Def THN132");
#endif
#else
// Create the Oregon message for a temperature/humidity sensor (THGR2228N)
byte ID[] = {0x1A,0x2D};
#ifdef DEBUG
Serial.println("UnDef THN132");
#endif
#endif
setType(OregonMessageBuffer, ID);
setChannel(OregonMessageBuffer, 0x20);
// ATMEGA 1 = BC
// TEST OREGON BB
// TEST Luminosite BD
setId(OregonMessageBuffer, 0xBC); // ID BB BC BD
// Narcoleptic.delay(1000);
delay(1000);
}
void loop()
{
digitalWrite(13, HIGH);
// Read Vcc value
long currentVcc = readVcc();
digitalWrite(13, LOW);
if (currentVcc > 5000) {
currentVcc = 5000;
}
#ifdef DEBUG
Serial.println(currentVcc);
#endif
// Get Temperature, humidity and battery level from sensors
// (ie: 1wire DS18B20 for température, ...)
if (currentVcc < 3800) {
setBatteryLevel(OregonMessageBuffer, 0); // 0 : low, 1 : high
} else {
setBatteryLevel(OregonMessageBuffer, 1); // 0 : low, 1 : high
}
// need addaptation here
// Ajout perso
//Lancement de la commande de récuperation de la temperature
sensors.requestTemperatures();
//Serial.println(sensors.getTempCByIndex(0));
//if (LUMINOSITE_PIN != 0) {
//setTemperature(OregonMessageBuffer,analogRead(LUMINOSITE_PIN));
//} else {
setTemperature(OregonMessageBuffer,sensors.getTempCByIndex(0));
//}
// setTemperature(OregonMessageBuffer, 11.2);
#ifndef THN132N
// Set Humidity
setHumidity(OregonMessageBuffer, 52);
#endif
// Calculate the checksum
calculateAndSetChecksum(OregonMessageBuffer);
// Show the Oregon Message
#ifdef DEBUG
for (byte i = 0; i < sizeof(OregonMessageBuffer); ++i) {
Serial.print(OregonMessageBuffer[i] >> 4, HEX);
Serial.print(OregonMessageBuffer[i] & 0x0F, HEX);
}
Serial.println("");
#endif
// Send the Message over RF
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
// Send a "pause"
SEND_LOW();
delayMicroseconds(TWOTIME*8);
// Send a copie of the first message. The v2.1 protocol send the
// message two time
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
delay(200);
// Narcoleptic.delay(SEND_433_PAUSE);
// Wait for 30 seconds before send a new message
SEND_LOW();
//delay(3000);
// Narcoleptic.delay(SEND_MESSAGE_DELAY);
// Narcoleptic.delay(SEND_MESSAGE_DELAY);
digitalWrite (LED_PIN, HIGH); // awake
delay (2000); // ie. do stuff here
digitalWrite (LED_PIN, LOW); // asleep
// sleep for a total of 20 seconds
for (int i = 0; i<5; i++) {
myWatchdogEnable (0b100001); // 8 seconds
}
}
//--------------------------------------------------------------------------------------------------
// Read current supply voltage
//--------------------------------------------------------------------------------------------------
long readVcc() {
bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
long result;
// Read 1.1V reference against Vcc
#if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
#endif
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate Vcc in mV
ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
return result; // Vcc in millivolts
}
// watchdog interrupt
ISR(WDT_vect)
{
wdt_disable(); // disable watchdog
}
void myWatchdogEnable(const byte interval)
{
MCUSR = 0; // reset various flags
WDTCSR |= 0b00011000; // see docs, set WDCE, WDE
WDTCSR = 0b01000000 | interval; // set WDIE, and appropriate delay
wdt_reset();
set_sleep_mode (SLEEP_MODE_PWR_DOWN);
sleep_mode(); // now goes to Sleep and waits for the interrupt
}
void enterSleep(void) {
ADCSRA &= ~(1<<ADEN); // disable ADC
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // the lowest power consumption
sleep_enable();
sleep_cpu(); // Now enter sleep mode.
// The program will continue from here after the WDT timeout.
sleep_disable(); // First thing to do is disable sleep.
power_all_enable(); // Re-enable the peripherals.
ADCSRA |= 1<<ADEN; // enable ADC
}

View File

@@ -0,0 +1,440 @@
/*
* connectingStuff, Oregon Scientific v2.1 Emitter
* http://connectingstuff.net/blog/encodage-protocoles-oregon-scientific-sur-arduino
* and
* http://blog.idleman.fr/raspberry-pi-18-construire-une-sonde-de-temperature-radio-pour-7e/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <OneWire.h>
#define THN132N
const byte TRANSMITTER_PIN = 9;
const byte LED_PIN = 13;
#define DEBUG TRUE
#define SEND_MESSAGE_DELAY 22500 // Ne pas dépasser 32000 !! Delay in ms between each value's extraction
#define SEND_433_PAUSE 160 // 16 multiple
// On crée une instance de la classe oneWire pour communiquer avec le materiel on wire (dont le capteur ds18b20)
OneWire oneWire(TRANSMITTER_PIN);
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
#define SEND_HIGH() digitalWrite(TRANSMITTER_PIN, HIGH)
#define SEND_LOW() digitalWrite(TRANSMITTER_PIN, LOW)
// Buffer for Oregon message
#ifdef THN132N
byte OregonMessageBuffer[8];
#else
byte OregonMessageBuffer[9];
#endif
/**
* \brief Send logical "0" over RF
* \details azero bit be represented by an off-to-on transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendZero(void)
{
SEND_HIGH();
delayMicroseconds(TIME);
SEND_LOW();
delayMicroseconds(TWOTIME);
SEND_HIGH();
delayMicroseconds(TIME);
}
/**
* \brief Send logical "1" over RF
* \details a one bit be represented by an on-to-off transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendOne(void)
{
SEND_LOW();
delayMicroseconds(TIME);
SEND_HIGH();
delayMicroseconds(TWOTIME);
SEND_LOW();
delayMicroseconds(TIME);
}
/**
* Send a bits quarter (4 bits = MSB from 8 bits value) over RF
*
* @param data Source data to process and sent
*/
/**
* \brief Send a bits quarter (4 bits = MSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterMSB(const byte data)
{
(bitRead(data, 4)) ? sendOne() : sendZero();
(bitRead(data, 5)) ? sendOne() : sendZero();
(bitRead(data, 6)) ? sendOne() : sendZero();
(bitRead(data, 7)) ? sendOne() : sendZero();
}
/**
* \brief Send a bits quarter (4 bits = LSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterLSB(const byte data)
{
(bitRead(data, 0)) ? sendOne() : sendZero();
(bitRead(data, 1)) ? sendOne() : sendZero();
(bitRead(data, 2)) ? sendOne() : sendZero();
(bitRead(data, 3)) ? sendOne() : sendZero();
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Send a buffer over RF
* \param data Data to send
* \param size size of data to send
*/
void sendData(byte *data, byte size)
{
for(byte i = 0; i < size; ++i)
{
sendQuarterLSB(data[i]);
sendQuarterMSB(data[i]);
}
}
/**
* \brief Send an Oregon message
* \param data The Oregon message
*/
void sendOregon(byte *data, byte size)
{
sendPreamble();
//sendSync();
sendData(data, size);
sendPostamble();
}
/**
* \brief Send preamble
* \details The preamble consists of 16 "1" bits
*/
inline void sendPreamble(void)
{
byte PREAMBLE[]={0xFF,0xFF};
sendData(PREAMBLE, 2);
}
/**
* \brief Send postamble
* \details The postamble consists of 8 "0" bits
*/
inline void sendPostamble(void)
{
#ifdef THN132N
sendQuarterLSB(0x00);
#else
byte POSTAMBLE[]={0x00};
sendData(POSTAMBLE, 1);
#endif
}
/**
* \brief Send sync nibble
* \details The sync is 0xA. It is not use in this version since the sync nibble
* \ is include in the Oregon message to send.
*/
inline void sendSync(void)
{
sendQuarterLSB(0xA);
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Set the sensor type
* \param data Oregon message
* \param type Sensor type
*/
inline void setType(byte *data, byte* type)
{
data[0] = type[0];
data[1] = type[1];
}
/**
* \brief Set the sensor channel
* \param data Oregon message
* \param channel Sensor channel (0x10, 0x20, 0x30)
*/
inline void setChannel(byte *data, byte channel)
{
data[2] = channel;
}
/**
* \brief Set the sensor ID
* \param data Oregon message
* \param ID Sensor unique ID
*/
inline void setId(byte *data, byte ID)
{
data[3] = ID;
}
/**
* \brief Set the sensor battery level
* \param data Oregon message
* \param level Battery level (0 = low, 1 = high)
*/
void setBatteryLevel(byte *data, byte level)
{
if(!level) data[4] = 0x0C;
else data[4] = 0x00;
}
/**
* \brief Set the sensor temperature
* \param data Oregon message
* \param temp the temperature
*/
void setTemperature(byte *data, float temp)
{
// Set temperature sign
if(temp < 0)
{
data[6] = 0x08;
temp *= -1;
}
else
{
data[6] = 0x00;
}
// Determine decimal and float part
int tempInt = (int)temp;
int td = (int)(tempInt / 10);
int tf = (int)round((float)((float)tempInt/10 - (float)td) * 10);
int tempFloat = (int)round((float)(temp - (float)tempInt) * 10);
// Set temperature decimal part
data[5] = (td << 4);
data[5] |= tf;
// Set temperature float part
data[4] |= (tempFloat << 4);
}
/**
* \brief Set the sensor humidity
* \param data Oregon message
* \param hum the humidity
*/
void setHumidity(byte* data, byte hum)
{
data[7] = (hum/10);
data[6] |= (hum - data[7]*10) << 4;
//Serial.print("Hum=" + hum);
}
/**
* \brief Sum data for checksum
* \param count number of bit to sum
* \param data Oregon message
*/
int Sum(byte count, const byte* data)
{
int s = 0;
for(byte i = 0; i<count;i++)
{
s += (data[i]&0xF0) >> 4;
s += (data[i]&0xF);
}
if(int(count) != count)
s += (data[count]&0xF0) >> 4;
return s;
}
/**
* \brief Calculate checksum
* \param data Oregon message
*/
void calculateAndSetChecksum(byte* data)
{
#ifdef THN132N
int s = ((Sum(6, data) + (data[6]&0xF) - 0xa) & 0xff);
data[6] |= (s&0x0F) << 4; data[7] = (s&0xF0) >> 4;
#else
data[8] = ((Sum(8, data) - 0xa) & 0xFF);
#endif
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
void setup()
{
pinMode(TRANSMITTER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
#ifdef DEBUG
Serial.begin(9600);
Serial.println("\n[Oregon V2.1 encoder]");
#endif
SEND_LOW();
#ifdef THN132N
// Create the Oregon message for a temperature only sensor (TNHN132N)
byte ID[] = {0xEA,0x4C};
#ifdef DEBUG
Serial.println("Def THN132");
#endif
#else
// Create the Oregon message for a temperature/humidity sensor (THGR2228N)
byte ID[] = {0x1A,0x2D};
#ifdef DEBUG
Serial.println("UnDef THN132");
#endif
#endif
setType(OregonMessageBuffer, ID);
setChannel(OregonMessageBuffer, 0x20);
// ATMEGA 1 = BC
// TEST OREGON BB
// TEST Luminosite BD
setId(OregonMessageBuffer, 0xBD); // ID BB BC BD
//Narcoleptic.delay(1000);
}
void loop()
{
digitalWrite(13, HIGH);
int lum = analogRead(1);
#ifdef DEBUG
// Serial.println(currentVcc);
Serial.println(lum);
#endif
// Get Temperature, humidity and battery level from sensors
// (ie: 1wire DS18B20 for température, ...)
// Read Vcc value
// LA LECTURE DE LA TENSION FAIT PLANTER LES PORTS ANALOGIQUES ????
long currentVcc = readVcc();
digitalWrite(13, LOW);
if (currentVcc > 5000) {
currentVcc = 5000;
}
if (currentVcc < 3800) {
setBatteryLevel(OregonMessageBuffer, 0); // 0 : low, 1 : high
} else {
setBatteryLevel(OregonMessageBuffer, 1); // 0 : low, 1 : high
}
// need addaptation here
// Ajout perso
//Serial.println(sensors.getTempCByIndex(0));
setTemperature(OregonMessageBuffer,lum / 10);
// setTemperature(OregonMessageBuffer, 11.2);
#ifndef THN132N
// Set Humidity
setHumidity(OregonMessageBuffer, 52);
#endif
// Calculate the checksum
calculateAndSetChecksum(OregonMessageBuffer);
// Show the Oregon Message
#ifdef DEBUG
for (byte i = 0; i < sizeof(OregonMessageBuffer); ++i) {
Serial.print(OregonMessageBuffer[i] >> 4, HEX);
Serial.print(OregonMessageBuffer[i] & 0x0F, HEX);
}
Serial.println("");
#endif
// Send the Message over RF
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
// Send a "pause"
SEND_LOW();
delayMicroseconds(TWOTIME*8);
// Send a copie of the first message. The v2.1 protocol send the
// message two time
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
//Narcoleptic.delay(SEND_433_PAUSE);
// Wait for 30 seconds before send a new message
SEND_LOW();
delay (3000);
}
//--------------------------------------------------------------------------------------------------
// Read current supply voltage
//--------------------------------------------------------------------------------------------------
long readVcc() {
bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
long result;
// Read 1.1V reference against Vcc
#if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
#endif
// ADCSRB = 0;
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate Vcc in mV
// ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
// analogReference(DEFAULT);
return result; // Vcc in millivolts
}

View File

@@ -0,0 +1,451 @@
/*
* connectingStuff, Oregon Scientific v2.1 Emitter
* http://connectingstuff.net/blog/encodage-protocoles-oregon-scientific-sur-arduino
* and
* http://blog.idleman.fr/raspberry-pi-18-construire-une-sonde-de-temperature-radio-pour-7e/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Narcoleptic.h>
#define THN132N
const byte TEMPERATURE_1_PIN = A0;
const byte LUMINOSITE_PIN=A1;
const byte TRANSMITTER_PIN = 9;
const byte LED_PIN = 13;
#define DEBUG TRUE
#define SEND_MESSAGE_DELAY 2500 // Ne pas dépasser 32000 !! Delay in ms between each value's extraction
#define SEND_433_PAUSE 160 // 16 multiple
// On crée une instance de la classe oneWire pour communiquer avec le materiel on wire (dont le capteur ds18b20)
OneWire oneWire(TEMPERATURE_1_PIN);
//On passe la reference onewire à la classe DallasTemperature qui vas nous permettre de relever la temperature simplement
DallasTemperature sensors(&oneWire);
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
#define SEND_HIGH() digitalWrite(TRANSMITTER_PIN, HIGH)
#define SEND_LOW() digitalWrite(TRANSMITTER_PIN, LOW)
// Buffer for Oregon message
#ifdef THN132N
byte OregonMessageBuffer[8];
#else
byte OregonMessageBuffer[9];
#endif
/**
* \brief Send logical "0" over RF
* \details azero bit be represented by an off-to-on transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendZero(void)
{
SEND_HIGH();
delayMicroseconds(TIME);
SEND_LOW();
delayMicroseconds(TWOTIME);
SEND_HIGH();
delayMicroseconds(TIME);
}
/**
* \brief Send logical "1" over RF
* \details a one bit be represented by an on-to-off transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendOne(void)
{
SEND_LOW();
delayMicroseconds(TIME);
SEND_HIGH();
delayMicroseconds(TWOTIME);
SEND_LOW();
delayMicroseconds(TIME);
}
/**
* Send a bits quarter (4 bits = MSB from 8 bits value) over RF
*
* @param data Source data to process and sent
*/
/**
* \brief Send a bits quarter (4 bits = MSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterMSB(const byte data)
{
(bitRead(data, 4)) ? sendOne() : sendZero();
(bitRead(data, 5)) ? sendOne() : sendZero();
(bitRead(data, 6)) ? sendOne() : sendZero();
(bitRead(data, 7)) ? sendOne() : sendZero();
}
/**
* \brief Send a bits quarter (4 bits = LSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterLSB(const byte data)
{
(bitRead(data, 0)) ? sendOne() : sendZero();
(bitRead(data, 1)) ? sendOne() : sendZero();
(bitRead(data, 2)) ? sendOne() : sendZero();
(bitRead(data, 3)) ? sendOne() : sendZero();
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Send a buffer over RF
* \param data Data to send
* \param size size of data to send
*/
void sendData(byte *data, byte size)
{
for(byte i = 0; i < size; ++i)
{
sendQuarterLSB(data[i]);
sendQuarterMSB(data[i]);
}
}
/**
* \brief Send an Oregon message
* \param data The Oregon message
*/
void sendOregon(byte *data, byte size)
{
sendPreamble();
//sendSync();
sendData(data, size);
sendPostamble();
}
/**
* \brief Send preamble
* \details The preamble consists of 16 "1" bits
*/
inline void sendPreamble(void)
{
byte PREAMBLE[]={0xFF,0xFF};
sendData(PREAMBLE, 2);
}
/**
* \brief Send postamble
* \details The postamble consists of 8 "0" bits
*/
inline void sendPostamble(void)
{
#ifdef THN132N
sendQuarterLSB(0x00);
#else
byte POSTAMBLE[]={0x00};
sendData(POSTAMBLE, 1);
#endif
}
/**
* \brief Send sync nibble
* \details The sync is 0xA. It is not use in this version since the sync nibble
* \ is include in the Oregon message to send.
*/
inline void sendSync(void)
{
sendQuarterLSB(0xA);
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Set the sensor type
* \param data Oregon message
* \param type Sensor type
*/
inline void setType(byte *data, byte* type)
{
data[0] = type[0];
data[1] = type[1];
}
/**
* \brief Set the sensor channel
* \param data Oregon message
* \param channel Sensor channel (0x10, 0x20, 0x30)
*/
inline void setChannel(byte *data, byte channel)
{
data[2] = channel;
}
/**
* \brief Set the sensor ID
* \param data Oregon message
* \param ID Sensor unique ID
*/
inline void setId(byte *data, byte ID)
{
data[3] = ID;
}
/**
* \brief Set the sensor battery level
* \param data Oregon message
* \param level Battery level (0 = low, 1 = high)
*/
void setBatteryLevel(byte *data, byte level)
{
if(!level) data[4] = 0x0C;
else data[4] = 0x00;
}
/**
* \brief Set the sensor temperature
* \param data Oregon message
* \param temp the temperature
*/
void setTemperature(byte *data, float temp)
{
// Set temperature sign
if(temp < 0)
{
data[6] = 0x08;
temp *= -1;
}
else
{
data[6] = 0x00;
}
// Determine decimal and float part
int tempInt = (int)temp;
int td = (int)(tempInt / 10);
int tf = (int)round((float)((float)tempInt/10 - (float)td) * 10);
int tempFloat = (int)round((float)(temp - (float)tempInt) * 10);
// Set temperature decimal part
data[5] = (td << 4);
data[5] |= tf;
// Set temperature float part
data[4] |= (tempFloat << 4);
}
/**
* \brief Set the sensor humidity
* \param data Oregon message
* \param hum the humidity
*/
void setHumidity(byte* data, byte hum)
{
data[7] = (hum/10);
data[6] |= (hum - data[7]*10) << 4;
Serial.print("Hum=" + hum);
}
/**
* \brief Sum data for checksum
* \param count number of bit to sum
* \param data Oregon message
*/
int Sum(byte count, const byte* data)
{
int s = 0;
for(byte i = 0; i<count;i++)
{
s += (data[i]&0xF0) >> 4;
s += (data[i]&0xF);
}
if(int(count) != count)
s += (data[count]&0xF0) >> 4;
return s;
}
/**
* \brief Calculate checksum
* \param data Oregon message
*/
void calculateAndSetChecksum(byte* data)
{
#ifdef THN132N
int s = ((Sum(6, data) + (data[6]&0xF) - 0xa) & 0xff);
data[6] |= (s&0x0F) << 4; data[7] = (s&0xF0) >> 4;
#else
data[8] = ((Sum(8, data) - 0xa) & 0xFF);
#endif
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
void setup()
{
pinMode(TRANSMITTER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(LUMINOSITE_PIN, INPUT);
#ifdef DEBUG
Serial.begin(115200);
Serial.println("\n[Oregon V2.1 encoder]");
#endif
SEND_LOW();
//On initialise le capteur de temperature
sensors.begin();
#ifdef THN132N
// Create the Oregon message for a temperature only sensor (TNHN132N)
byte ID[] = {0xEA,0x4C};
#ifdef DEBUG
Serial.println("Def THN132");
#endif
#else
// Create the Oregon message for a temperature/humidity sensor (THGR2228N)
byte ID[] = {0x1A,0x2D};
#ifdef DEBUG
Serial.println("UnDef THN132");
#endif
#endif
setType(OregonMessageBuffer, ID);
setChannel(OregonMessageBuffer, 0x20);
// ATMEGA 1 = BC
// TEST OREGON BB
// TEST Luminosite BD
setId(OregonMessageBuffer, 0xBD); // ID BB BC BD
Narcoleptic.delay(1000);
}
void loop()
{
digitalWrite(13, HIGH);
// Read Vcc value
long currentVcc = readVcc();
digitalWrite(13, LOW);
if (currentVcc > 5000) {
currentVcc = 5000;
}
#ifdef DEBUG
Serial.println(currentVcc);
#endif
// Get Temperature, humidity and battery level from sensors
// (ie: 1wire DS18B20 for température, ...)
if (currentVcc < 3800) {
setBatteryLevel(OregonMessageBuffer, 0); // 0 : low, 1 : high
} else {
setBatteryLevel(OregonMessageBuffer, 1); // 0 : low, 1 : high
}
// need addaptation here
// Ajout perso
//Lancement de la commande de récuperation de la temperature
sensors.requestTemperatures();
//Serial.println(sensors.getTempCByIndex(0));
if (LUMINOSITE_PIN != 0) {
#ifdef DEBUG
Serial.println(analogRead(LUMINOSITE_PIN));
#endif
setTemperature(OregonMessageBuffer,analogRead(LUMINOSITE_PIN));
} else {
setTemperature(OregonMessageBuffer,sensors.getTempCByIndex(0));
}
// setTemperature(OregonMessageBuffer, 11.2);
#ifndef THN132N
// Set Humidity
setHumidity(OregonMessageBuffer, 52);
#endif
// Calculate the checksum
calculateAndSetChecksum(OregonMessageBuffer);
// Show the Oregon Message
#ifdef DEBUG
for (byte i = 0; i < sizeof(OregonMessageBuffer); ++i) {
Serial.print(OregonMessageBuffer[i] >> 4, HEX);
Serial.print(OregonMessageBuffer[i] & 0x0F, HEX);
}
Serial.println("");
#endif
// Send the Message over RF
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
// Send a "pause"
SEND_LOW();
delayMicroseconds(TWOTIME*8);
// Send a copie of the first message. The v2.1 protocol send the
// message two time
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
Narcoleptic.delay(SEND_433_PAUSE);
// Wait for 30 seconds before send a new message
SEND_LOW();
//delay(3000);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
}
//--------------------------------------------------------------------------------------------------
// Read current supply voltage
//--------------------------------------------------------------------------------------------------
long readVcc() {
bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
long result;
// Read 1.1V reference against Vcc
#if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
#endif
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate Vcc in mV
ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
return result; // Vcc in millivolts
}

View File

@@ -0,0 +1,636 @@
/*
* connectingStuff, Oregon Scientific v2.1 Emitter
* http://connectingstuff.net/blog/encodage-protocoles-oregon-scientific-sur-arduino
* and
* http://blog.idleman.fr/raspberry-pi-18-construire-une-sonde-de-temperature-radio-pour-7e/
*
* This program is free software; you can redistribute it and/or
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// ------------------------------
// Radio
// ------------------------------
#include <OneWire.h>
const byte ALIM_TRANSMITTER_PIN = 8;
const byte TRANSMITTER_PIN = 9;
const byte LED_PIN = 13;
#define DEBUG TRUE
#define SEND_MESSAGE_DELAY 22500 // Ne pas dépasser 32000 !! Delay in ms between each value's extraction
#define SEND_433_PAUSE 160 // 16 multiple
// On crée une instance de la classe oneWire pour communiquer avec le materiel on wire (dont le capteur ds18b20)
OneWire oneWire(TRANSMITTER_PIN);
// Buffer for Oregon message
#ifdef THN132N
byte OregonMessageBuffer[8];
#else
byte OregonMessageBuffer[9];
#endif
// ------------------------------
// Energie
// ------------------------------
#include "EmonLib.h" // Include Emon Library
EnergyMonitor emon1; // Create an instance
EnergyMonitor emon2;
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
#define SEND_HIGH() digitalWrite(TRANSMITTER_PIN, HIGH)
#define SEND_LOW() digitalWrite(TRANSMITTER_PIN, LOW)
// ----------------------------
// Smooth
// ----------------------------
const int numReadings = 10;
const int numIndex = 2;
float last_values[numIndex][numReadings];
int readIndex[numIndex];
long total[numIndex];
int boucle = 0;
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(3, 2); // RX | TX
// ----------------------------
// Dimmer
// ----------------------------
//#include <RBDdimmer.h>
//#define outputPin 6
//#define zerocross D2 // for boards with CHANGEBLE input pins
//#define pas 5
//dimmerLamp dimmer(outputPin); //initialase port for dimmer for ESP8266, ESP32, Arduino due boards
//// To set dimmer off ==> dimmer.setPower(128);
//// value 0 = On
// ----------------------------
// Interruption
// ----------------------------
const byte interruptPin = 3;
volatile byte backlight_status = LOW;
// ----------------------------
// Screen LCD
// ----------------------------
#include <LiquidCrystal_I2C.h>
#include "LowPower.h"
#define I2C_SLAVE_ADDRESS 0x0B // 12 pour l'esclave 2 et ainsi de suite
#define PAYLOAD_SIZE 2
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
// ----------------------------
// Timer
// ----------------------------
//#include "PinChangeInterrupt.h"
//
//#include <MsTimer2.h> // inclusion de la librairie Timer2
//#define pinBlink 7
/**
* \brief Send logical "0" over RF
* \details azero bit be represented by an off-to-on transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendZero(void)
{
SEND_HIGH();
delayMicroseconds(TIME);
SEND_LOW();
delayMicroseconds(TWOTIME);
SEND_HIGH();
delayMicroseconds(TIME);
}
/**
* \brief Send logical "1" over RF
* \details a one bit be represented by an on-to-off transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendOne(void)
{
SEND_LOW();
delayMicroseconds(TIME);
SEND_HIGH();
delayMicroseconds(TWOTIME);
SEND_LOW();
delayMicroseconds(TIME);
}
/**
* Send a bits quarter (4 bits = MSB from 8 bits value) over RF
*
* @param data Source data to process and sent
*/
/**
* \brief Send a bits quarter (4 bits = MSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterMSB(const byte data)
{
(bitRead(data, 4)) ? sendOne() : sendZero();
(bitRead(data, 5)) ? sendOne() : sendZero();
(bitRead(data, 6)) ? sendOne() : sendZero();
(bitRead(data, 7)) ? sendOne() : sendZero();
}
/**
* \brief Send a bits quarter (4 bits = LSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterLSB(const byte data)
{
(bitRead(data, 0)) ? sendOne() : sendZero();
(bitRead(data, 1)) ? sendOne() : sendZero();
(bitRead(data, 2)) ? sendOne() : sendZero();
(bitRead(data, 3)) ? sendOne() : sendZero();
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Send a buffer over RF
* \param data Data to send
* \param size size of data to send
*/
void sendData(byte *data, byte size)
{
for(byte i = 0; i < size; ++i)
{
sendQuarterLSB(data[i]);
sendQuarterMSB(data[i]);
}
}
/**
* \brief Send an Oregon message
* \param data The Oregon message
*/
void sendOregon(byte *data, byte size)
{
sendPreamble();
//sendSync();
sendData(data, size);
sendPostamble();
}
/**
* \brief Send preamble
* \details The preamble consists of 16 "1" bits
*/
inline void sendPreamble(void)
{
byte PREAMBLE[]={0xFF,0xFF};
sendData(PREAMBLE, 2);
}
/**
* \brief Send postamble
* \details The postamble consists of 8 "0" bits
*/
inline void sendPostamble(void)
{
#ifdef THN132N
sendQuarterLSB(0x00);
#else
byte POSTAMBLE[]={0x00};
sendData(POSTAMBLE, 1);
#endif
}
/**
* \brief Send sync nibble
* \details The sync is 0xA. It is not use in this version since the sync nibble
* \ is include in the Oregon message to send.
*/
inline void sendSync(void)
{
sendQuarterLSB(0xA);
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Set the sensor type
* \param data Oregon message
* \param type Sensor type
*/
inline void setType(byte *data, byte* type)
{
data[0] = type[0];
data[1] = type[1];
}
/**
* \brief Set the sensor channel
* \param data Oregon message
* \param channel Sensor channel (0x10, 0x20, 0x30)
*/
inline void setChannel(byte *data, byte channel)
{
data[2] = channel;
}
/**
* \brief Set the sensor ID
* \param data Oregon message
* \param ID Sensor unique ID
*/
inline void setId(byte *data, byte ID)
{
data[3] = ID;
}
/**
* \brief Set the sensor battery level
* \param data Oregon message
* \param level Battery level (0 = low, 1 = high)
*/
void setBatteryLevel(byte *data, byte level)
{
if(!level) data[4] = 0x0C;
else data[4] = 0x00;
}
/**
* \brief Set the sensor temperature
* \param data Oregon message
* \param temp the temperature
*/
void setTemperature(byte *data, float temp)
{
// Set temperature sign
if(temp < 0)
{
data[6] = 0x08;
temp *= -1;
}
else
{
data[6] = 0x00;
}
// Determine decimal and float part
int tempInt = (int)temp;
int td = (int)(tempInt / 10);
int tf = (int)round((float)((float)tempInt/10 - (float)td) * 10);
int tempFloat = (int)round((float)(temp - (float)tempInt) * 10);
// Set temperature decimal part
data[5] = (td << 4);
data[5] |= tf;
// Set temperature float part
data[4] |= (tempFloat << 4);
}
/**
* \brief Set the sensor humidity
* \param data Oregon message
* \param hum the humidity
*/
void setHumidity(byte* data, byte hum)
{
data[7] = (hum/10);
data[6] |= (hum - data[7]*10) << 4;
//Serial.print("Hum=" + hum);
}
/**
* \brief Sum data for checksum
* \param count number of bit to sum
* \param data Oregon message
*/
int Sum(byte count, const byte* data)
{
int s = 0;
for(byte i = 0; i<count;i++)
{
s += (data[i]&0xF0) >> 4;
s += (data[i]&0xF);
}
if(int(count) != count)
s += (data[count]&0xF0) >> 4;
return s;
}
/**
* \brief Calculate checksum
* \param data Oregon message
*/
void calculateAndSetChecksum(byte* data)
{
#ifdef THN132N
int s = ((Sum(6, data) + (data[6]&0xF) - 0xa) & 0xff);
data[6] |= (s&0x0F) << 4; data[7] = (s&0xF0) >> 4;
#else
data[8] = ((Sum(8, data) - 0xa) & 0xFF);
#endif
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
float puissance_reelle1;
void setup()
{
lcd.init(); // initialize the lcd
delay(200);
lcd.noBacklight();
lcd.setCursor(0,0);
lcd.print("Screen Ok");
Serial.begin(9600);
// Screen
Serial.println("Screen init...");
delay(200);
pinMode(TRANSMITTER_PIN, OUTPUT);
pinMode(ALIM_TRANSMITTER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("[Oregon V2.1 encoder]");
//analogReference(EXTERNAL);
// float vcc = readVcc() / 1000.0;
// Serial.print(vcc);
emon1.voltage(A2, 320 , 2.6); // Voltage: input pin, calibration, phase_shift
emon1.current(A1, 30); // Current: input pin, calibration.
//emon2.voltage(A2, 320, 7); // Voltage: input pin, calibration, phase_shift
emon2.current(A0, 5);
SEND_LOW();
// Interruption
// pinMode(interruptPin, INPUT_PULLUP);
// attachInterrupt(digitalPinToInterrupt(interruptPin), onEvent, CHANGE);
// pinMode(pinBlink, INPUT_PULLUP);
// attachPCINT(digitalPinToPCINT(pinBlink), onEvent, CHANGE);
//
// Serial.println(F("Interruption attachée"));
// delay(200);
//
////
// // Timer
// MsTimer2::set(12000, InterruptTimer2); // période 1000ms
// Serial.println(F("Timer démarré"));
// delay(200);
// Dimmer
// Serial.println("Dimmer Program is starting...");
// delay(1000);
// dimmer.begin(NORMAL_MODE, ON); //dimmer initialisation: name.begin(MODE, STATE)
// Serial.println("Set value");
// dimmer.setPower(50); // setPower(0-100%);
// lcd.clear();
// lcd.setCursor(0,0);
// lcd.print("Dimmer set to 0");
// delay(200);
}
void loop()
{
// if (backlight_status) {
// lcd.backlight();
// }
// else {
// lcd.noBacklight();
// }
double Irms[2];
boucle ++;
for (int bcl = 1; bcl <=2; bcl++) {
digitalWrite(13, HIGH);
digitalWrite(8, HIGH);
if (bcl == 1) {
emon1.calcVI(20,200); // 1 Demande a Emonlib de tout calculer, (puissance relle, volts moyen, ampère moyen et facteur de puissance)
//Irms[0] = emon1.calcIrms(5440) * 230; //emon1.apparentPower);
Irms[0] = emon1.apparentPower;
puissance_reelle1 = emon1.realPower; // 1 creation de la variable flottante "puissance reelle" qui existe dans la librairie sous "emon1.realPower"
float verif_voltage = emon1.Vrms; // 1 creation de la variable "volts moyen" (mesurable avec un voltmètre pour l'etalonnage)
float verif_ampere = emon1.Irms; // 1 creation de la variable "Ampères Moyen" (mesurable avec une pince ampèremétrique pour l'etalonnage))
float Cos_phi = emon1.powerFactor;
Serial.print(verif_voltage); // 1 envoyer vers l'ordinateur la valeur "verif_voltage (Vrms)"
Serial.print(" V "); // 1 envoyer vers l'ordinateur le caractère "V"
Serial.print(verif_ampere); // 1 envoyer vers l'ordinateur la valeur "verif_voltage (Vrms)"
Serial.print(" A "); // 1 envoyer vers l'ordinateur le caractère "A"
Serial.print(emon1.realPower);
Serial.print(" Wr ");
Serial.print(emon1.apparentPower); // Calculate Irms only
Serial.print(" Wcap ");
Serial.print(Irms[0]); // Calculate Irms only
Serial.print(" Wc ");
// Serial.print(emon1.apparentPower);
// Serial.print(" Wa ");
// Serial.print(Cos_phi); // 1 envoyer vers l'ordinateur la valeur "verif_voltage (Vrms)"
// Serial.print(" cos ");
}
else {
//emon2.calcVI(20,200);
Irms[1] = emon2.calcIrms(5440) * 230; //smooth(1,emon2.realPower); //apparentPower;
//Irms = emon2.apparentPower;
// Serial.print(1,emon2.realPower);
// Serial.print(" Wsr ");
// Serial.print(emon2.apparentPower);
// Serial.print(" Wsap ");
Serial.print(Irms[1]); // Calculate Irms only
Serial.println(" Ws ");
//emon2.serialprint();
String json = "/json.htm?type=command&param=udevice&idx=892&nvalue=0&svalue=0;0;0;0;" + String(Irms[1]) + ";0";
ESPserial.print(json);
}
if (boucle > 5) {
if (bcl == 1) {
sendMessage(0xBD, Irms[0]);
delay(500);
sendMessage(0xBF, puissance_reelle1);
}
else {
sendMessage(0xBE, Irms[1]);
}
delay (300);
}
digitalWrite(8, LOW);
digitalWrite(13, LOW);
if (boucle < 10) {
delay (200);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Calibration :" + String(boucle));
}
else {
boucle = 50; //max(50, boucle);
lcd.clear();
// dimmer.setPower(50 + (boucle * 10)% 50);
lcd.setCursor(0,0);
lcd.print("Cso:" + String(Irms[0], 0) + " R " + String(emon1.realPower, 0));
lcd.setCursor(0,1);
lcd.print("Sol:" + String(Irms[1],0) + " V " + String(emon1.Vrms, 1));
delay (300);
}
}
}
void sendMessage(byte ID, double Irms)
{
// LA LECTURE DE LA TENSION FAIT PLANTER LES PORTS ANALOGIQUES ????
long currentVcc = 5000; //readVcc();
// Create the Oregon message for a temperature/humidity sensor (THGR2228N)
byte TYPE[] = {0x1A,0x2D};
setType(OregonMessageBuffer, TYPE);
setChannel(OregonMessageBuffer, 0x20);
setId(OregonMessageBuffer, ID);
if (currentVcc > 5000) {
currentVcc = 5000;
}
if (currentVcc < 3800) {
setBatteryLevel(OregonMessageBuffer, 0); // 0 : low, 1 : high
} else {
setBatteryLevel(OregonMessageBuffer, 1); // 0 : low, 1 : high
}
if (int(Irms / 100) == 0 && Irms < 0) {
setTemperature(OregonMessageBuffer, -0.1);
}
else {
setTemperature(OregonMessageBuffer,(int)(Irms / 100));
}
// Set
// Serial.print(Irms);
// Serial.print(" ");
//
// Serial.print((int) Irms / 100);
// Serial.print(" " );
// Serial.println((int) Irms % 100);
setHumidity(OregonMessageBuffer, abs(int(Irms) % 100));
// Calculate the checksum
calculateAndSetChecksum(OregonMessageBuffer);
// Show the Oregon Message
// for (byte i = 0; i < sizeof(OregonMessageBuffer); ++i) {
// Serial.print(OregonMessageBuffer[i] >> 4, HEX);
// Serial.print(OregonMessageBuffer[i] & 0x0F, HEX);
//
// }
// Serial.println("");
// Send the Message over RF
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
// Send a "pause"
SEND_LOW();
delayMicroseconds(TWOTIME*8);
// Send a copie of the first message. The v2.1 protocol send the
// message two time
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
SEND_LOW();
}
//
//void onEvent() {
// backlight_status = !backlight_status;
// Serial.print(F("Switch LED 13 : "));
// if(backlight_status){
// Serial.println(F("ON"));
// }else{
// Serial.println(F("OFF"));
// }
// MsTimer2::start(); // active Timer 2
//
//}
//
//void InterruptTimer2() { // debut de la fonction d'interruption Timer2
//
// digitalWrite(LED_PIN, HIGH);
// Serial.println(F("Timer interruption"));
// backlight_status = LOW;
//
// delayMicroseconds(300); // la fonction delayMicroseconds ne bloque pas les interruptions
// digitalWrite(LED_PIN, LOW);
//
// MsTimer2::stop(); // active Timer 2
//
// //output = !output;
//
//
//}
float smooth(int index, float last_value) { /* function smooth */
////Perform average on sensor last_values
float average;
// subtract the last reading:
total[index] = total[index] - last_values[index][readIndex[index]];
// read the sensor:
last_values[index][readIndex[index]] = last_value;
// add value to total:
total[index] = total[index] + last_values[index][readIndex[index]];
// handle index
readIndex[index] = readIndex[index] + 1;
if (readIndex[index] >= numReadings) {
readIndex[index] = 0;
}
float tot = 0;
for (int j = 0; j< numReadings; j++) {
tot +=last_values[index][j];
}
//Serial.println("");
// calculate the average:
average = tot / numReadings; //al[index] / numReadings;
return average;
}

View File

@@ -0,0 +1,204 @@
/*
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 11. If you're unsure what
pin the on-board LED is connected to on your Arduino model, check
the documentation at http://arduino.cc
This example code is in the public domain.
modified 8 May 2014
by Scott Fitzgerald
*/
#include <RCSwitch.h>
#include <Narcoleptic.h>
#define SEND_MESSAGE_DELAY 30000 // Ne pas dépasser 32000 !! Delay in ms between each value's extraction
#define SEND_433_PAUSE 160 // 16 multiple
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
#define RADIATEUR_POWER 11
#define RADIATEUR_PILOTE 12
#define TEMPERATURE_EXTINCTION 1900
//1900
#define TEMPERATURE_HORS_GEL 1850
#define TEMPERATURE_CHAUFFE 1750
//#define DEBUG true
boolean started = false;
int id = 0;
RCSwitch mySwitch = RCSwitch();
// Cas
// 12 = Courant général 0 éteint 1 allumé
// 11 = Mode radiateur 0 hors gel 1 confort
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 11 as an output.
pinMode(RADIATEUR_POWER, OUTPUT);
pinMode(RADIATEUR_PILOTE, OUTPUT);
pinMode(13, OUTPUT);
digitalWrite(RADIATEUR_POWER, HIGH);
digitalWrite(RADIATEUR_PILOTE, HIGH);
#ifdef DEBUG
Serial.begin(9600);
#endif
mySwitch.enableReceive(0); // Receiver on inerrupt 0 => that is pin #2
}
void loop() {
if (mySwitch.available()) {
int value = mySwitch.getReceivedValue();
if (value == 0) {
#ifdef DEBUG
Serial.print("Unknown encoding");
#endif
} else {
long data = mySwitch.getReceivedValue();
//Serial.print("Received ");
//Serial.println( data );
// Serial.print(" / ");
// Serial.print( mySwitch.getReceivedBitlength() );
// Serial.print("bit ");
// Serial.print("Protocol: ");
// Serial.println( mySwitch.getReceivedProtocol() );
//Serial.println("");
//delay(1000); // wait for a second
if (data == 111269) {
started = true;
// id = 0;
#ifdef DEBUG
Serial.println("started");
#endif
while (data == 111269) {
data = mySwitch.getReceivedValue();
}
}
if (data == 962111) {
started = false;
id = 0;
#ifdef DEBUG
Serial.println("En pause");
#endif
while (data == 962111) {
data = mySwitch.getReceivedValue();
}
mySwitch.resetAvailable();
// On se met en pause
mySwitch.disableReceive();
delayMicroseconds(TWOTIME*8);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
mySwitch.enableReceive(0);
//Serial.println("Arret");
} else if (data == 1969 || data == 2069 || data == 2169 || data == 2269 || data == 2369) {
//Serial.print("id=");
//Serial.println(data);
// if (id == 0) {
id = data;
// } else {
// started = false;
// id = 0;
// }
} else {
if (started && id == 1969) {
long currentVcc = readVcc();
digitalWrite(13, HIGH);
#ifdef DEBUG
Serial.print("Demarré ");
Serial.print("id=");
Serial.print(id);
Serial.print(" data=");
Serial.println(data);
#endif
// Supérieur à 19° STOP
if (data >= TEMPERATURE_EXTINCTION) {
digitalWrite(RADIATEUR_POWER, HIGH);
digitalWrite(RADIATEUR_PILOTE, HIGH);
// Supérieur à 18 ==> Veille
} else if (data >= TEMPERATURE_HORS_GEL) {
digitalWrite(RADIATEUR_POWER, HIGH);
digitalWrite(RADIATEUR_PILOTE, LOW);
} else if (data < TEMPERATURE_CHAUFFE) {
digitalWrite(RADIATEUR_POWER, LOW);
digitalWrite(RADIATEUR_PILOTE, LOW);
}
// Reset pour éviter la modification plusieurs fois
started = false;
id = 0;
if (currentVcc <= 3500) {
delay(5);
digitalWrite(13, LOW);
delay(5);
digitalWrite(13, HIGH);
delay(5);
} else if (currentVcc < 3200) {
delay(5);
digitalWrite(13, LOW);
delay(5);
digitalWrite(13, HIGH);
delay(5);
digitalWrite(13, LOW);
delay(5);
digitalWrite(13, HIGH);
delay(5);
} else {
delay(5);
}
digitalWrite(13, LOW);
}
}
}
mySwitch.resetAvailable();
}
}
//--------------------------------------------------------------------------------------------------
// Read current supply voltage
//--------------------------------------------------------------------------------------------------
long readVcc() {
bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
long result;
// Read 1.1V reference against Vcc
#if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
#endif
// ADCSRB = 0;
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate Vcc in mV
// ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
// analogReference(DEFAULT);
return result; // Vcc in millivolts
}

View File

@@ -0,0 +1,223 @@
/*
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 11. If you're unsure what
pin the on-board LED is connected to on your Arduino model, check
the documentation at http://arduino.cc
This example code is in the public domain.
modified 8 May 2014
by Scott Fitzgerald
*/
#include <RCSwitch.h>
#include <Narcoleptic.h>
#define SEND_MESSAGE_DELAY 30000 // Ne pas dépasser 32000 !! Delay in ms between each value's extraction
#define SEND_433_PAUSE 160 // 16 multiple
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
#define RADIATEUR_POWER 11
#define RADIATEUR_PILOTE 12
#define TEMPERATURE_EXTINCTION 1900
//1900
#define TEMPERATURE_HORS_GEL 1850
#define TEMPERATURE_CHAUFFE 1750
//#define DEBUG true
boolean started = false;
int id = 0;
// Cas
// 12 = Courant général 0 éteint 1 allumé
// 11 = Mode radiateur 0 hors gel 1 confort
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 11 as an output.
pinMode(RADIATEUR_POWER, OUTPUT);
pinMode(RADIATEUR_PILOTE, OUTPUT);
pinMode(13, OUTPUT);
digitalWrite(RADIATEUR_POWER, HIGH);
digitalWrite(RADIATEUR_PILOTE, HIGH);
#ifdef DEBUG
Serial.begin(9600);
#endif
}
void loop() {
listen();
delayMicroseconds(TWOTIME*8);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
}
void listen() {
RCSwitch mySwitch = RCSwitch();
mySwitch.enableReceive(0); // Receiver on inerrupt 0 => that is pin #2
Narcoleptic.delay(TWOTIME*8);
boolean sleep = false;
while (!sleep) {
if (!mySwitch.available()) {
Narcoleptic.delay(1000);
// digitalWrite(13, HIGH);
// delay(5);
// digitalWrite(13, LOW);
// delay(5);
} else {
int value = mySwitch.getReceivedValue();
if (value == 0) {
#ifdef DEBUG
Serial.print("Unknown encoding");
#endif
} else {
long data = mySwitch.getReceivedValue();
//Serial.print("Received ");
//Serial.println( data );
// Serial.print(" / ");
// Serial.print( mySwitch.getReceivedBitlength() );
// Serial.print("bit ");
// Serial.print("Protocol: ");
// Serial.println( mySwitch.getReceivedProtocol() );
//Serial.println("");
//delay(1000); // wait for a second
if (data == 111269) {
started = true;
// id = 0;
#ifdef DEBUG
Serial.println("started");
#endif
while (data == 111269) {
data = mySwitch.getReceivedValue();
}
}
if (data == 962111) {
started = false;
id = 0;
#ifdef DEBUG
Serial.println("En pause");
#endif
while (data == 962111) {
data = mySwitch.getReceivedValue();
}
mySwitch.resetAvailable();
// On se met en pause
sleep = true;
break;
//Serial.println("Arret");
} else if (data == 1969 || data == 2069 || data == 2169 || data == 2269 || data == 2369) {
//Serial.print("id=");
//Serial.println(data);
// if (id == 0) {
id = data;
// } else {
// started = false;
// id = 0;
// }
} else {
if (started && id == 1969) {
long currentVcc = readVcc();
digitalWrite(13, HIGH);
#ifdef DEBUG
Serial.print("Demarré ");
Serial.print("id=");
Serial.print(id);
Serial.print(" data=");
Serial.println(data);
#endif
// Supérieur à 19° STOP
if (data >= TEMPERATURE_EXTINCTION) {
digitalWrite(RADIATEUR_POWER, HIGH);
digitalWrite(RADIATEUR_PILOTE, HIGH);
// Supérieur à 18 ==> Veille
} else if (data >= TEMPERATURE_HORS_GEL) {
digitalWrite(RADIATEUR_POWER, HIGH);
digitalWrite(RADIATEUR_PILOTE, LOW);
} else if (data < TEMPERATURE_CHAUFFE) {
digitalWrite(RADIATEUR_POWER, LOW);
digitalWrite(RADIATEUR_PILOTE, LOW);
}
// Reset pour éviter la modification plusieurs fois
started = false;
id = 0;
if (currentVcc <= 3500) {
delay(5);
digitalWrite(13, LOW);
delay(5);
digitalWrite(13, HIGH);
delay(5);
} else if (currentVcc < 3200) {
delay(5);
digitalWrite(13, LOW);
delay(5);
digitalWrite(13, HIGH);
delay(5);
digitalWrite(13, LOW);
delay(5);
digitalWrite(13, HIGH);
delay(5);
} else {
delay(10);
}
digitalWrite(13, LOW);
}
}
}
mySwitch.resetAvailable();
}
}
}
//--------------------------------------------------------------------------------------------------
// Read current supply voltage
//--------------------------------------------------------------------------------------------------
long readVcc() {
bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
long result;
// Read 1.1V reference against Vcc
#if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
#endif
// ADCSRB = 0;
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate Vcc in mV
// ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
// analogReference(DEFAULT);
return result; // Vcc in millivolts
}

View File

@@ -0,0 +1,192 @@
/*
Servo Receive Demo
Hacked from http://code.google.com/p/rc-switch/ by @justy
*/
#include <RCSwitch.h>
float temp = 0.0;
float bar = 0.0;
float hum = 0.0;
float lum = 0.0;
boolean yaduboulot = false;
long id = 0;
float tmp = 0;
#define ENABLE_Sniffer true
RCSwitch mySwitch = RCSwitch(); // Create an instance of RCSwitch
void setup() {
Serial.begin(9600);
// ********* IMPORTANT ***********
mySwitch.enableReceive(0); // Receiver on inerrupt 0 => that is pin #2
}
void loop() {
if (mySwitch.available()) {
//clear;
long value = mySwitch.getReceivedValue();
if (value == 0) {
Serial.print("Unknown encoding");
}
else {
if (ENABLE_Sniffer) {
Serial.print("Received ");
Serial.print( value );
Serial.print(" / ");
Serial.print( mySwitch.getReceivedBitlength() );
Serial.print("bit ");
Serial.print("Protocol: ");
Serial.println( mySwitch.getReceivedProtocol() );
}
switch (value) {
case 111269:
printf("Debut de message %i \n", value);
id = 0;
tmp = 0;
break;
case 1969:
case 2069:
case 2169:
case 2269:
case 2369:
id = value;
tmp = 0;
break;
case 962111:
id = 0;
tmp = 0;
break;
default :
tmp = value;
printf("valeur recue = %i id=%i\n", tmp, id);
break;
}
Serial.print(" id=");
Serial.print(id);
Serial.print(" value=");
Serial.print(tmp);
Serial.println("");
char buf[7];
char nom[200] = "curl \"http://localhost:8080/json.htm?type=command&param=udevice&"; //idx=107&svalue=";
boolean envoi = false;
if (tmp != 0) {
if (id == 1969 && tmp < 10000 ) {
// sprintf(buf,"%.2f", tmp / 100.0);
toString(&buf[0], tmp / 100.0);
strcat(nom, "idx=122&svalue=");
temp = tmp / 100.0;
envoi = true;
} else if (id == 2069 && tmp < 12000 && tmp > 7000) {
// sprintf(buf,"%.2f", tmp / 10.0);
toString(&buf[0], tmp / 10.0);
strcat(nom, "idx=121&svalue=");
bar = tmp / 10.0;
envoi = true;
} else if (id == 2169 && tmp < 12000 && tmp > 7000) {
// sprintf(buf,"%.2f", tmp / 10.0);
toString(&buf[0], tmp / 10.0) ;
strcat(nom, "idx=123&svalue=");
envoi = true;
} else if (id == 2269 && tmp < 1024) {
// sprintf(buf,"%.2f", tmp);
toString(&buf[0], tmp);
strcat(nom, "idx=158&svalue=");
lum = tmp;
envoi = true;
} else if (id == 2369 && tmp < 100 && tmp > 20) {
// sprintf(buf,"%.2f", tmp);
toString(&buf[0], tmp);
//strcat(nom, "idx=158&svalue=");
hum = tmp;
} else if (id == 331969 && tmp > 0) {
sprintf(buf,"%.2f;%.2f", tmp, tmp);
strcat(nom, "idx=166&svalue=");
strcat(nom,buf);
strcat(nom,"\"");
printf("%s\n",nom);
// FIXME std::system(nom);
envoi=false;
}
if (envoi) {
strcat(nom,buf);
strcat(nom,"\"");
printf("%s\n",nom);
Serial.println(nom);
// FIXME std::system(nom);
}
}
}
char buf[8];
if (/*lum > 0 &&*/ bar > 0 && temp > 0 && hum > 0) {
// /json.htm?type=command&param=udevice&idx=IDX&nvalue=0&svalue=TEMP;HUM;HUM_STAT;BAR;BAR_FOR
char nom[200] = "curl \"http://localhost:8080/json.htm?type=command&param=udevice&idx=160&svalue=";
// Température
// sprintf(buf,"%.2f;", temp);
toString(&buf[0], temp);
strcat(nom, buf); //strcat(nom, ";");
// Humidité
//sprintf(buf,"%.2f;", hum);
toString(&buf[0], hum);
strcat(nom, buf); //strcat(nom, ";");
// Hum stat
//sprintf(buf,"%.2f;", hum);
toString(&buf[0], hum);
strcat(nom, buf); //strcat(nom, ";");
// Bar
// sprintf(buf,"%.2f;", bar);
toString(&buf[0], bar);
strcat(nom, buf); //strcat(nom, ";");
// Bar Forecast
// sprintf(buf,"%.2f", bar);
toString(&buf[0], bar);
strcat(nom, buf); //strcat(nom, ";");
// Fin de chaine
strcat(nom,"\"");
//Commande
printf("%s\n",nom);
// Exec
//FIXME std::system(nom);
Serial.println(nom);
lum = 0;
hum = 0;
bar = 0;
temp = 0;
}
// Prepare for more input
mySwitch.resetAvailable();
}
delay(100);
}
void toString(char *p, float f) {
int i = ((int) f);
p += sprintf(p, "%i", i);
p += sprintf(p, ".%i", ((int) ((f - i) * 100)));
// etc
}

View File

@@ -0,0 +1,290 @@
/*
*/
#include <RCSwitch.h>
#include <Wire.h>
char last_message[200] = "";
char previous[100] = "";
float temp = 0.0;
float bar = 0.0;
float hum = 0.0;
float lum = 0.0;
boolean yaduboulot = false;
long id = 0;
float tmp = 0;
int val = 0;
int boucle = 0;
int boucle2 = 0;
#define ENABLE_Sniffer true
// I2C
#define SLAVE_ADDRESS 0x12
int dataReceived = 0;
RCSwitch mySwitch = RCSwitch(); // Create an instance of RCSwitch
void setup() {
Serial.begin(9600);
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
// ********* IMPORTANT ***********
mySwitch.enableReceive(0); // Receiver on inerrupt 0 => that is pin #2
// I2C
Wire.begin(SLAVE_ADDRESS);
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
blink();
}
void loop() {
if (mySwitch.available()) {
if (strlen(last_message) > 180) {
strcpy(last_message,"");
}
// printf("", last_message);
//clear;
long value = mySwitch.getReceivedValue();
if (value <= 0) {
Serial.print("Unknown encoding");
}
else {
if (ENABLE_Sniffer) {
Serial.print("Received ");
Serial.print( value );
// Serial.print(" / ");
// Serial.print( mySwitch.getReceivedBitlength() );
// Serial.print("bit ");
// Serial.print("Protocol: ");
// Serial.println( mySwitch.getReceivedProtocol() );
}
switch (value) {
case 111269:
Serial.println(printf("Debut de message %i \n", value));
id = 0;
tmp = 0;
strcpy(last_message,"");
val =0;
break;
case 1969:
case 2069:
case 2169:
case 2269:
case 2369:
id = value;
tmp = 0;
break;
case 962111:
id = 0;
tmp = 0;
break;
default :
tmp = value;
Serial.println(printf("valeur recue = %i id=%i\n", tmp, id));
break;
}
Serial.println(printf("valeur recue = %i id=%i\n", tmp, id));
if (ENABLE_Sniffer) {
Serial.print(" id=");
Serial.print(id);
Serial.print(" value=");
Serial.print(tmp);
Serial.println("");
}
char buf[7];
//char nom[200] = "curl \"http://localhost:8080/json.htm?type=command&param=udevice&"; //idx=107&svalue=";
char nom[100] = "";
boolean envoi = false;
if (tmp != 0) {
if (id == 1969 && tmp < 10000 ) {
// sprintf(buf,"%.2f", tmp / 100.0);
toString(&buf[0], tmp / 100.0);
strcat(nom, "idx=122&svalue=");
temp = tmp / 100.0;
envoi = true;
} else if (id == 2069 && tmp < 12000 && tmp > 7000) {
// sprintf(buf,"%.2f", tmp / 10.0);
toString(&buf[0], tmp / 10.0);
strcat(nom, "idx=121&svalue=");
bar = tmp / 10.0;
envoi = true;
} else if (id == 2169 && tmp < 12000 && tmp > 7000) {
// sprintf(buf,"%.2f", tmp / 10.0);
toString(&buf[0], tmp / 10.0) ;
strcat(nom, "idx=123&svalue=");
envoi = true;
} else if (id == 2269 && tmp < 1024) {
// sprintf(buf,"%.2f", tmp);
toString(&buf[0], tmp);
strcat(nom, "idx=158&svalue=");
lum = tmp;
envoi = true;
} else if (id == 2369 && tmp < 100 && tmp > 20) {
// sprintf(buf,"%.2f", tmp);
toString(&buf[0], tmp);
//strcat(nom, "idx=158&svalue=");
hum = tmp;
} else if (id == 331969 && tmp > 0) {
Serial.println(sprintf(buf,"%.2f;%.2f", tmp, tmp));
strcat(nom, "idx=166&svalue=");
strcat(nom,buf);
strcat(nom,"\"");
printf("%s\n",nom);
// FIXME std::system(nom);
envoi=false;
}
if (envoi) {
strcat(nom,buf);
//strcat(nom,"\"");
Serial.println(printf("%s\n",nom));
if (ENABLE_Sniffer) {
Serial.print("previous=");
Serial.print(previous);
Serial.print(" nom=");
Serial.println(nom);
}
if (strcmp(previous, nom) != 0) {
//char last_message[200] = "value=";
strcat(last_message, nom);
strcat(last_message, "|");
if (ENABLE_Sniffer) {
Serial.println(last_message);
}
strcpy(previous, nom);
blink();
}
// FIXME std::system(nom);
}
}
}
char buf[8];
if (/*lum > 0 &&*/ bar > 0 && temp > 0 && hum > 0) {
// /json.htm?type=command&param=udevice&idx=IDX&nvalue=0&svalue=TEMP;HUM;HUM_STAT;BAR;BAR_FOR
//char nom[200] = "curl \"http://localhost:8080/json.htm?type=command&param=udevice&idx=160&svalue=";
char nom[200] = "idx=160&svalue=";
// Température
// sprintf(buf,"%.2f;", temp);
toString(&buf[0], temp);
strcat(nom, buf); strcat(nom, ";");
// Humidité
//sprintf(buf,"%.2f;", hum);
toString(&buf[0], hum);
strcat(nom, buf); strcat(nom, ";");
// Hum stat
//sprintf(buf,"%.2f;", hum);
toString(&buf[0], hum);
strcat(nom, buf); strcat(nom, ";");
// Bar
// sprintf(buf,"%.2f;", bar);
toString(&buf[0], bar);
strcat(nom, buf); strcat(nom, ";");
// Bar Forecast
// sprintf(buf,"%.2f", bar);
toString(&buf[0], bar);
strcat(nom, buf); strcat(nom, ";");
// Fin de chaine
//strcat(nom,"\"");
//Commande
Serial.println(printf("%s\n",nom));
// Exec
//FIXME std::system(nom);
// Serial.println(nom);
lum = 0;
hum = 0;
bar = 0;
temp = 0;
strcat(last_message, nom);
strcat(last_message, "|");
if (ENABLE_Sniffer) {
Serial.println(last_message);
}
blink();
}
// Prepare for more input
mySwitch.resetAvailable();
}
delay(100);
boucle++;
boucle2++;
if (boucle > 10) {
Serial.print(".");
boucle = 0;
}
if (boucle2 > 800) {
Serial.println();
boucle2 = 0;
}
}
void toString(char *p, float f) {
Serial.print("To String");
int i = ((int) f);
p += sprintf(p, "%i", i);
p += sprintf(p, ".%i", ((int) ((f - i) * 100)));
Serial.println(p);
// etc
}
// I2C
void receiveData(int byteCount){
while(Wire.available()) {
dataReceived = Wire.read();
Serial.print("Donnee recue : ");
Serial.println(dataReceived);
if (dataReceived == 3) {
val = 0;
}
blink();
}
}
void sendData(){
// Wire.beginTransmission(SLAVE_ADDRESS); // transmit to device #44 (0x2c)
// device address is specified in datasheet
Wire.write(last_message[val]);
//Wire.endTransmission();
val++;
if (val > strlen(last_message)) {
val = 0;
}
}
void blink() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(50); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(50);
}

View File

@@ -0,0 +1,290 @@
/*
*/
#include <RCSwitch.h>
#include <Wire.h>
char last_message[200] = "";
char previous[100] = "";
float temp = 0.0;
float bar = 0.0;
float hum = 0.0;
float lum = 0.0;
boolean yaduboulot = false;
long id = 0;
float tmp = 0;
int val = 0;
int boucle = 0;
int boucle2 = 0;
#define ENABLE_Sniffer true
// I2C
#define SLAVE_ADDRESS 0x12
int dataReceived = 0;
RCSwitch mySwitch = RCSwitch(); // Create an instance of RCSwitch
void setup() {
Serial.begin(9600);
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
// ********* IMPORTANT ***********
mySwitch.enableReceive(0); // Receiver on inerrupt 0 => that is pin #2
// I2C
Wire.begin(SLAVE_ADDRESS);
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
blink();
}
void loop() {
if (mySwitch.available()) {
if (strlen(last_message) > 180) {
strcpy(last_message,"");
}
// printf("", last_message);
//clear;
long value = mySwitch.getReceivedValue();
if (value <= 0) {
Serial.print("Unknown encoding");
}
else {
if (ENABLE_Sniffer) {
Serial.print("Received ");
Serial.print( value );
// Serial.print(" / ");
// Serial.print( mySwitch.getReceivedBitlength() );
// Serial.print("bit ");
// Serial.print("Protocol: ");
// Serial.println( mySwitch.getReceivedProtocol() );
}
switch (value) {
case 111269:
Serial.println(printf("Debut de message %i \n", value));
id = 0;
tmp = 0;
strcpy(last_message,"");
val =0;
break;
case 1969:
case 2069:
case 2169:
case 2269:
case 2369:
id = value;
tmp = 0;
break;
case 962111:
id = 0;
tmp = 0;
break;
default :
tmp = value;
Serial.println(printf("valeur recue = %i id=%i\n", tmp, id));
break;
}
Serial.println(printf("valeur recue = %i id=%i\n", tmp, id));
if (ENABLE_Sniffer) {
Serial.print(" id=");
Serial.print(id);
Serial.print(" value=");
Serial.print(tmp);
Serial.println("");
}
char buf[7];
//char nom[200] = "curl \"http://localhost:8080/json.htm?type=command&param=udevice&"; //idx=107&svalue=";
char nom[100] = "";
boolean envoi = false;
if (tmp != 0) {
if (id == 1969 && tmp < 10000 ) {
// sprintf(buf,"%.2f", tmp / 100.0);
toString(&buf[0], tmp / 100.0);
strcat(nom, "idx=122&svalue=");
temp = tmp / 100.0;
envoi = true;
} else if (id == 2069 && tmp < 12000 && tmp > 7000) {
// sprintf(buf,"%.2f", tmp / 10.0);
toString(&buf[0], tmp / 10.0);
strcat(nom, "idx=121&svalue=");
bar = tmp / 10.0;
envoi = true;
} else if (id == 2169 && tmp < 12000 && tmp > 7000) {
// sprintf(buf,"%.2f", tmp / 10.0);
toString(&buf[0], tmp / 10.0) ;
strcat(nom, "idx=123&svalue=");
envoi = true;
} else if (id == 2269 && tmp < 1024) {
// sprintf(buf,"%.2f", tmp);
toString(&buf[0], tmp);
strcat(nom, "idx=158&svalue=");
lum = tmp;
envoi = true;
} else if (id == 2369 && tmp < 100 && tmp > 20) {
// sprintf(buf,"%.2f", tmp);
toString(&buf[0], tmp);
//strcat(nom, "idx=158&svalue=");
hum = tmp;
} else if (id == 331969 && tmp > 0) {
Serial.println(sprintf(buf,"%.2f;%.2f", tmp, tmp));
strcat(nom, "idx=166&svalue=");
strcat(nom,buf);
strcat(nom,"\"");
printf("%s\n",nom);
// FIXME std::system(nom);
envoi=false;
}
if (envoi) {
strcat(nom,buf);
//strcat(nom,"\"");
Serial.println(printf("%s\n",nom));
if (ENABLE_Sniffer) {
Serial.print("previous=");
Serial.print(previous);
Serial.print(" nom=");
Serial.println(nom);
}
if (strcmp(previous, nom) != 0) {
//char last_message[200] = "value=";
strcat(last_message, nom);
strcat(last_message, "|");
if (ENABLE_Sniffer) {
Serial.println(last_message);
}
strcpy(previous, nom);
blink();
}
// FIXME std::system(nom);
}
}
}
char buf[8];
if (/*lum > 0 &&*/ bar > 0 && temp > 0 && hum > 0) {
// /json.htm?type=command&param=udevice&idx=IDX&nvalue=0&svalue=TEMP;HUM;HUM_STAT;BAR;BAR_FOR
//char nom[200] = "curl \"http://localhost:8080/json.htm?type=command&param=udevice&idx=160&svalue=";
char nom[200] = "idx=160&svalue=";
// Température
// sprintf(buf,"%.2f;", temp);
toString(&buf[0], temp);
strcat(nom, buf); strcat(nom, ";");
// Humidité
//sprintf(buf,"%.2f;", hum);
toString(&buf[0], hum);
strcat(nom, buf); strcat(nom, ";");
// Hum stat
//sprintf(buf,"%.2f;", hum);
toString(&buf[0], hum);
strcat(nom, buf); strcat(nom, ";");
// Bar
// sprintf(buf,"%.2f;", bar);
toString(&buf[0], bar);
strcat(nom, buf); strcat(nom, ";");
// Bar Forecast
// sprintf(buf,"%.2f", bar);
toString(&buf[0], bar);
strcat(nom, buf); strcat(nom, ";");
// Fin de chaine
//strcat(nom,"\"");
//Commande
Serial.println(printf("%s\n",nom));
// Exec
//FIXME std::system(nom);
// Serial.println(nom);
lum = 0;
hum = 0;
bar = 0;
temp = 0;
strcat(last_message, nom);
strcat(last_message, "|");
if (ENABLE_Sniffer) {
Serial.println(last_message);
}
blink();
}
// Prepare for more input
mySwitch.resetAvailable();
}
delay(100);
boucle++;
boucle2++;
if (boucle > 10) {
Serial.print(".");
boucle = 0;
}
if (boucle2 > 800) {
Serial.println();
boucle2 = 0;
}
}
void toString(char *p, float f) {
Serial.print("To String");
int i = ((int) f);
p += sprintf(p, "%i", i);
p += sprintf(p, ".%i", ((int) ((f - i) * 100)));
Serial.println(p);
// etc
}
// I2C
void receiveData(int byteCount){
while(Wire.available()) {
dataReceived = Wire.read();
Serial.print("Donnee recue : ");
Serial.println(dataReceived);
if (dataReceived == 3) {
val = 0;
}
blink();
}
}
void sendData(){
// Wire.beginTransmission(SLAVE_ADDRESS); // transmit to device #44 (0x2c)
// device address is specified in datasheet
Wire.write(last_message[val]);
//Wire.endTransmission();
val++;
if (val > strlen(last_message)) {
val = 0;
}
}
void blink() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(50); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(50);
}

View File

@@ -0,0 +1,168 @@
// EmonLibrary examples openenergymonitor.org, Licence GNU GPL V3
#include "EmonLib.h" // Include Emon Library
EnergyMonitor emon_conso; // Create an instance
EnergyMonitor emon_solar;
#define NB_MESURES 50
int lectures = -10;
double sum_conso = 0;
double sum_solar = 0;
double last_conso_value = 0;
double last_solar_value = 0;
const int buttonPin = 2; // the number of the pushbutton pin
boolean isDark = false;
#include <Wire.h>
//#include <LiquidCrystal_I2C.h>
#include "LowPower.h"
#define I2C_SLAVE_ADDRESS 0x0B // 12 pour l'esclave 2 et ainsi de suite
#define PAYLOAD_SIZE 2
//LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
#include <ezButton.h>
ezButton button(7); // create ezButton object that attach to pin 7;
void setup()
{
Serial.begin(9600);
emon_conso.current(0, 60); // Current: input pin, calibration.
emon_solar.current(1, 60);
Wire.begin(I2C_SLAVE_ADDRESS);
Serial.begin(9600);
Serial.println("Slave -------------------------------------I am Slave1");
delay(1000);
Wire.onRequest(requestEvents);
Wire.onReceive(receiveEvents);
pinMode(buttonPin, INPUT);
pinMode(6, OUTPUT);
// lcd.init(); // initialize the lcd
delay(500);
}
int bcl = 0;
void loop()
{
if (isDark) {
Serial.println("Slave Dark, go to sleep");
delay(100);
LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
//LowPower.idle(SLEEP_8S, ADC_OFF, TIMER2_OFF, TIMER1_OFF, TIMER0_OFF, SPI_OFF, USART0_OFF, TWI_OFF);
}
button.loop(); // MUST call the loop() function first
int btnState = button.getState();
//Serial.println(btnState);
double Irms_conso = emon_conso.calcIrms(1480); // Calculate Irms_conso only
double Irms_solar = emon_solar.calcIrms(1480); // Calculate Irms_conso only
lectures ++;
delay(10);
if (lectures > 0) {
sum_conso += Irms_conso;
sum_solar += Irms_solar;
if (lectures == NB_MESURES) {
last_conso_value = sum_conso / lectures;
last_solar_value = sum_solar / lectures;
lectures = -10;
sum_conso = 0;
sum_solar = 0;
//delay(2000);
}
}
// Serial.println("Slave Conso :" + String(bcl) + " " + String(sum_conso / lectures));
// Serial.println("Slave Solaire:" + String(sum_solar / lectures));
bcl ++;
// // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
// if (btnState == 0) {
// // digitalWrite(6, HIGH);
//
// lcd.backlight();
//// for(int i=1024; i>0; i-=25){
//// analogWrite(6, i);
//// delay(500);
//// lcd.clear();
//// lcd.setCursor(0,0);
//// lcd.print("i " + String(i));
//// }
// }
// else {
// lcd.noBacklight();
// // digitalWrite(6, LOW);
// }
// //lcd.backlight();
// if (lectures > 0) {
// lcd.clear();
// lcd.setCursor(0,0);
// lcd.print("Conso :" + String(bcl) + " " + String(sum_conso / lectures));
// lcd.setCursor(0,1);
// lcd.print("Solaire:" + String(sum_solar / lectures));
// }
}
void requestEvents()
{
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(100); // wait for a second
Serial.println(F("---> received request"));
Serial.print(F("sending value : "));
char TempString[10]; // Hold The Convert Data
dtostrf(last_conso_value,2,2,TempString);
Serial.println(TempString);
Wire.write(TempString);
Wire.write(";");
dtostrf(last_solar_value,2,2,TempString);
Serial.println(TempString);
Wire.write(TempString);
Wire.write("\n");
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000);
}
void receiveEvents(int numBytes)
{
Serial.println(F("---> received events"));
// int n = Wire.read();
// Serial.print(numBytes);
// Serial.println(F("bytes received"));
// Serial.print(F("received value : "));
// Serial.println(n);
String data = "";
while(Wire.available()) // loop through all but the last
{
char c = Wire.read(); // receive byte as a character
Serial.print(c); // print the character
data = data + c;
}
if (data == "jour") {
isDark = false;
}
if (data == "nuit") {
isDark = true;
}
}

View File

@@ -0,0 +1,140 @@
// EmonLibrary examples openenergymonitor.org, Licence GNU GPL V3
#include "EmonLib.h" // Include Emon Library
EnergyMonitor emon_conso; // Create an instance
EnergyMonitor emon_solar;
#define NB_MESURES 50
const uint16_t port = 81;
const char * host = "192.168.1.3"; // ip or dns
int lectures = -10;
double sum_conso = 0;
double sum_solar = 0;
double last_conso_value = 0;
double last_solar_value = 0;
/*
* Displays text sent over the serial port (e.g. from the Serial Monitor) on
* an attached LCD.
* YWROBOT
*Compatible with the Arduino IDE 1.0
*Library version:1.1
*/
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define I2C_SLAVE_ADDRESS 0x0B // 12 pour l'esclave 2 et ainsi de suite
#define PAYLOAD_SIZE 2
int n = 0;
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
void setup()
{
lcd.init(); // initialize the lcd
lcd.backlight();
Serial.begin(9600);
emon_conso.current(0, 60); // Current: input pin, calibration.
emon_solar.current(1, 60);
Wire.begin(I2C_SLAVE_ADDRESS);
Serial.begin(9600);
Serial.println("-------------------------------------I am Slave1");
delay(1000);
Wire.onRequest(requestEvents);
Wire.onReceive(receiveEvents);
delay(500);
}
void loop()
{
double Irms_conso = emon_conso.calcIrms(1480); // Calculate Irms_conso only
double Irms_solar = emon_solar.calcIrms(1480); // Calculate Irms_conso only
lectures ++;
//
// Serial.print(Irms_conso*230.0); // Apparent power
// Serial.print(" ");
// Serial.println(Irms_conso); // Irms_conso
//
// Serial.print(Irms_solar*230.0); // Apparent power
// Serial.print(" ");
// Serial.println(Irms_solar);
delay(10);
if (lectures > 0) {
sum_conso += Irms_conso;
sum_solar += Irms_solar;
if (lectures == NB_MESURES) {
last_conso_value = sum_conso / lectures;
last_solar_value = sum_solar / lectures;
// envoieDomoticz("1053",String(sum_conso / lectures)); // intensite
// delay(500);
// envoieDomoticz("1086",String(sum_solar / lectures)); // intensite
lectures = -10;
sum_conso = 0;
sum_solar = 0;
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Conso :" + String(last_conso_value));
lcd.setCursor(0,1);
lcd.print("Solaire:" + String(last_solar_value));
delay(2000);
}
}
if (Serial.available() > 0) {
// read the incoming byte:
int incomingByte = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte, DEC);
}
while(Serial.available () > 0){
Serial.read();
}
Serial.flush();
// read all the available characters
// display each character to the LCD
}
void requestEvents()
{
Serial.println(F("---> received request"));
Serial.print(F("sending value : "));
char TempString[10]; // Hold The Convert Data
dtostrf(last_conso_value,2,2,TempString);
Serial.println(TempString);
Wire.write(TempString);
Wire.write(";");
dtostrf(last_solar_value,2,2,TempString);
Serial.println(TempString);
Wire.write(TempString);
Wire.write("\n");
}
void receiveEvents(int numBytes)
{
Serial.println(F("---> received events"));
n = Wire.read();
Serial.print(numBytes);
Serial.println(F("bytes received"));
Serial.print(F("received value : "));
Serial.println(n);
}

151
ATMEGA_SERIAL/ATMEGA_SERIAL.ino Executable file
View File

@@ -0,0 +1,151 @@
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <Wire.h>
#include <Adafruit_BMP085.h>
#define LED_PIN (13)
//
float temperature = 0.0;
float pressure = 0.0;
float pression = 0.0;
float presiune = 0.0;
int sensorValue = 0;
int sensorValue2 = 0;
int sensorValue3 = 0;
int distance = 0;
//const int TrigPin = 2;
//const int EchoPin = 3;
// ################# Barometre ####
Adafruit_BMP085 bmp;
// #####################
// =============================================================
/******************************************************************/
void reSetup() {
// pinMode(TrigPin, OUTPUT);
// pinMode(EchoPin, INPUT);
Serial.begin(115200);
// Sleep
/* Don't forget to configure the pin! */
pinMode(LED_PIN, OUTPUT);
}
void setup() {
reSetup();
/*** Configure the timer.***/
}
void loop()
{
digitalWrite(LED_PIN, HIGH);
barometre();
readSensors();
//readPresence();
sendAll();
digitalWrite(LED_PIN, LOW);
delay(2000);
}
void sendAll() {
sendValues("TEMPERATURE", temperature * 100);
sendValues("PRESSION", (int) (pression * 10));
sendValues("PRESSURE", (int) (pressure * 10));
sendValues("SENSOR_1", sensorValue);
sendValues("SENSOR_2", sensorValue2);
sendValues("SENSOR_3", (int) (sensorValue3 / 10.24));
//sendValues("DISTANCE", distance);
}
void barometre() {
/* See Example: TypeA_WithDIPSwitches */
// mySwitch.switchOn("00001", "10000");
// delay(1000);
// BMP
if (bmp.begin()) {
temperature = bmp.readTemperature();
pressure= bmp.readPressure() / 100.0;
pression = pressure / 101.325;
pression = pression * 0.760 * 100;
// http://en.wikipedia.org/wiki/Atmospheric_pressure#Mean_sea_level_pressure
// Serial.print("Presiure la nivelul marii (calculata) = ");
presiune = bmp.readSealevelPressure() / 101.325;
presiune = presiune * 0.760;
}
}
//void readPresence() {
// digitalWrite(TrigPin, LOW); //Low high and low level take a short time to TrigPin pulse
// delayMicroseconds(2);
// digitalWrite(TrigPin, HIGH);
// delayMicroseconds(10);
// digitalWrite(TrigPin, LOW);
//
// float cm = pulseIn(EchoPin, HIGH) / 58.0; //Echo time conversion into cm
// cm = (int(cm * 100.0)) / 100.0; //Keep two decimal places
//
// distance = cm * 100;
//
//}
void readSensors() {
// ##########################################"
// Analogic read
// ------------------------------------------
sensorValue = analogRead(A0);
sensorValue2 = analogRead(A1);
sensorValue3 = analogRead(A2);
// int sensorValue4 = digitalRead(10);
//vol = (float)sensorValue / 1024 * 5.0;
// ##########################################
}
void sendValues(String id, int value) {
Serial.print(id);
Serial.print("=");
Serial.println(value);
// mySwitch.switchOn(buf,buf2);
// mySwitch.switchOn(id, value);
// delay(1000);
}

View File

@@ -0,0 +1,28 @@
#include<avr/io.h>
#define USART_BAUDRATE 9600
#define BAUD_PRESCALE (((F_CPU/(USART_BAUDRATE*16UL)))-1)
int main(void){
char recieved_byte;
UCSR0B |= (1<<RXEN0) | (1<<TXEN0);
UCSR0C |= (1<<UCSZ00) | (1<<UCSZ01);
UBRR0H = (BAUD_PRESCALE >> 8);
UBRR0L = BAUD_PRESCALE;
for(;;){
// wait until a byte is ready to read
while( ( UCSR0A & ( 1 << RXC0 ) ) == 0 ){}
// grab the byte from the serial port
recieved_byte = UDR0;
// wait until the port is ready to be written to
while( ( UCSR0A & ( 1 << UDRE0 ) ) == 0 ){}
// write the byte to the serial port
UDR0 = recieved_byte;
}
return 0; /* never reached */
}

View File

@@ -0,0 +1,208 @@
/*
Title: SerialCom.c
Date Created: 6/9/2009
Last Modified: 6/9/2009
Target: Atmel ATmega168
Environment: AVR-GCC
Note: the makefile is expecting a '168 with a 16 MHz crystal.
Adapted from the Arduino sketch "Serial Call and Response," by Tom Igoe.
// This program sends an ASCII A (byte of value 65) on startup
// and repeats that until it gets some data in.
// Then it waits for a byte in the serial port, and
// sends three (faked) sensor values whenever it gets a byte in.
Written by Windell Oskay, http://www.evilmadscientist.com/
Copyright 2009 Windell H. Oskay
Distributed under the terms of the GNU General Public License, please see below.
Additional license terms may be available; please contact us for more information.
More information about this project is at
http://www.evilmadscientist.com/article.php/peggy
-------------------------------------------------
USAGE: How to compile and install
A makefile is provided to compile and install this program using AVR-GCC and avrdude.
To use it, follow these steps:
1. Update the header of the makefile as needed to reflect the type of AVR programmer that you use.
2. Open a terminal window and move into the directory with this file and the makefile.
3. At the terminal enter
make clean <return>
make all <return>
make program <return>
4. Make sure that avrdude does not report any errors. If all goes well, the last few lines output by avrdude
should look something like this:
avrdude: verifying ...
avrdude: XXXX bytes of flash verified
avrdude: safemode: lfuse reads as E2
avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FF
avrdude: safemode: Fuses OK
avrdude done. Thank you.
If you a different programming environment, make sure that you copy over
the fuse settings from the makefile.
-------------------------------------------------
This code should be relatively straightforward, so not much documentation is provided. If you'd like to ask
questions, suggest improvements, or report success, please use the evilmadscientist forum:
http://www.evilmadscientist.com/forum/
-------------------------------------------------
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <avr/io.h>
#define F_CPU 16000000 // 16 MHz oscillator.
#define BaudRate 9600
#define MYUBRR (F_CPU / 16 / BaudRate ) - 1
void delayLong() {
unsigned int delayvar;
delayvar = 0;
while (delayvar <= 65500U) {
asm("nop");
delayvar++;
}
}
unsigned char serialCheckRxComplete(void)
{
return( UCSR0A & _BV(RXC0)) ; // nonzero if serial data is available to read.
}
unsigned char serialCheckTxReady(void)
{
return( UCSR0A & _BV(UDRE0) ) ; // nonzero if transmit register is ready to receive new data.
}
unsigned char serialRead(void)
{
while (serialCheckRxComplete() == 0) // While data is NOT available to read
{;;}
return UDR0;
}
void serialWrite(unsigned char DataOut)
{
while (serialCheckTxReady() == 0) // while NOT ready to transmit
{;;}
UDR0 = DataOut;
}
void establishContact() {
while (serialCheckRxComplete() == 0) {
serialWrite('A');
// serialWrite(65U);
delayLong();
delayLong();
delayLong();
delayLong();
delayLong();
delayLong();
delayLong();
}
}
int main (void)
{
//Interrupts are not needed in this program. You can optionally disable interrupts.
//asm("cli"); // DISABLE global interrupts.
DDRD = _BV(1);
DDRB = _BV(0) | _BV(1) | _BV(3) | _BV(5);
//Serial Initialization
/*Set baud rate */
UBRR0H = (unsigned char)(MYUBRR>>8);
UBRR0L = (unsigned char) MYUBRR;
/* Enable receiver and transmitter */
UCSR0B = (1<<RXEN0)|(1<<TXEN0);
/* Frame format: 8data, No parity, 1stop bit */
UCSR0C = (3<<UCSZ00);
int firstSensor = 0; // first analog sensor
int secondSensor = 0; // second analog sensor
int thirdSensor = 0; // digital sensor
int inByte = 0; // incoming serial byte
PORTB |= _BV(1); // Turn on LED @ PB1
establishContact(); // send a byte to establish contact until Processing responds
PORTB &= 253U; // Turn off LED
for (;;) // main loop
{
if (serialCheckRxComplete()) {
PORTB |= _BV(1); // Turn on LED @ PB1
inByte = serialRead();
// Simulated data!
firstSensor++;
secondSensor = firstSensor * firstSensor;
thirdSensor = firstSensor + secondSensor;
serialWrite(firstSensor & 255U);
serialWrite(secondSensor & 255U);
serialWrite(thirdSensor & 255U);
PORTB &= 253U; // Turn off LED
}
} //End main loop.
return 0;
}

View File

@@ -0,0 +1,91 @@
/*
* Commande d'un servo moteur en plusieurs séquences.
* Clignotement de la Led onBoar:
* - rapide en début de programme.
* - lente en entre les séquences.
* - fixe en fin de programme
*
* Commande servo à l'aide de servo.h et
* seulement sur les pin 9 ou pin 10.
*
*/
#include <Servo.h>
Servo monServo;
int pos = 0;
const int pinLed = 13; // Led sur le board
const long blinkTimeMs = 2000; // temps de clignotement de la led (2 sec)
const int FAST = 50; // interval entre deux clignotement (rapide)
const int SLOW = 150; // interval entre deux clignotement (lent)
const int FIXED = -1; // valeur spécial pour éclairage continu
void setup(){
pinMode( pinLed, OUTPUT );
// Attacher la pin 9 à l'objet servo.
// ATTN: le code initialise l'angle à 90 degrés par défaut.
monServo.attach(9);
// remettre l'angle à 0 degrés
monServo.write( 0 );
}
void loop(){
// Faire clignoter led 13 sur le board.
// Démarrage de séquence --> clignotement rapide
blinkBoardLed( FAST );
// Passer de 0 a 180° par angle de 10 degré
for( int iAngle=0; iAngle<= 360; iAngle+=10 )
{
monServo.write(iAngle);
delay( 250 );
}
// Clignotement lent entre deux séquences
blinkBoardLed( SLOW );
// Angle décroissant progressif
for( int iAngle = 360; iAngle>=0; iAngle-- )
{
monServo.write( iAngle );
delay( 10 );
}
// Clignotement lent entre deux séquences
blinkBoardLed( SLOW );
// Angle arbitraire de 45 degrés
monServo.write( 0 );
// Find de séquence -> eclairage fixe
blinkBoardLed( FIXED );
}
/* Fait clignoter la led 13 sur le board pendant 2 secondes
*
* interval: Interval de clignotement. -1 pour fixe.
*/
void blinkBoardLed( int interval ){
long startMillis = millis();
// temps que pas 2 sec d'écoulée
while( (millis() - startMillis) < blinkTimeMs ) {
switch( interval ){
case -1 : // Cas spécial, allumage fixe
digitalWrite( pinLed, HIGH );
delay( blinkTimeMs ); // attendre le temps total
digitalWrite( pinLed, LOW );
break;
default:
// faire clignoter
digitalWrite( pinLed, HIGH );
delay( interval );
digitalWrite( pinLed, LOW );
delay( interval );
} // eof Case
} // eof While
}

View File

@@ -0,0 +1,39 @@
Servo myservo;
int pos = 90; // initial position
int sens1 = A1; // photoresistor 1 pin
int sens2 = A0; //photoresistor 2 pin
int tolerance = 2;
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
pinMode(sens1, INPUT);
pinMode(sens2, INPUT);
myservo.write(pos);
delay(2000); // a 2 seconds delay while we position the solar panel
}
void loop()
{
int val1 = analogRead(sens1); // read the value of sensor 1
int val2 = analogRead(sens2); // read the value of sensor 2
if((abs(val1 - val2) <= tolerance) || (abs(val2 - val1) <= tolerance)) {
//do nothing if the difference between values is within the tolerance limit
} else {
if(val1 > val2)
{
pos = --pos;
}
if(val1 < val2)
{
pos = ++pos;
}
}
if(pos > 170) { pos = 170; } // reset to 180 if it goes higher
if(pos < 0) { pos = 0; } // reset to 0 if it goes lower
myservo.write(pos); // write the position to servo
delay(50);
}

372
ATMEGA_SLEEP/ATMEGA_SLEEP.ino Executable file
View File

@@ -0,0 +1,372 @@
/*
6-13-2011
Low Power Testing
Spark Fun Electronics 2011
Nathan Seidle
This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license).
This code is written to control a 7 segment display with as little power as possible, waking up only
when the external button is hit or when the 32kHz oscillator rolls over every 8 seconds.
Make sure to turn off Brown out detect (uses ~16uA).
6-23-2011: Down to 38uA!
6-29-2011: 17uA, not sure why.
7-2-2011: Currently (hah!) at 1.13uA
7-4-2011: Let's wake up every 8 seconds instead of every 1 to save even more power
Since we don't display seconds, this should be fine
Let's reduce the system clock to 8MHz/256 so that when servicing Timer2 int, we run even lower
We are now at ~1.05uA on average
*/
#include <avr/sleep.h> //Needed for sleep_mode
#include <avr/power.h> //Needed for powering down perihperals such as the ADC/TWI and Timers
#define TRUE 1
#define FALSE 0
int show_the_time = FALSE;
//For testing
long seconds = 2317;
int minutes = 58;
int hours = 12;
int digit1 = 11; //PWM, Display pin 1
int digit2 = 10; //PWM, Display pin 2
int digit3 = 9; //PWM, Display pin 6
int digit4 = 6; //PWM, Display pin 8
int segA = A1; //Display pin 14
int segB = 3; //Display pin 16
int segC = 4; //Display pin 13
int segD = 5; //Display pin 3
int segE = A0; //Display pin 5
int segF = 7; //Display pin 11
int segG = 8; //Display pin 15
//The very important 32.686kHz interrupt handler
SIGNAL(TIMER2_OVF_vect){
//seconds++;
seconds += 8; //We sleep for 8 seconds instead of 1 to save more power
//We don't update minutes and hours here to save power
//Instead, we update the minutes and hours when you hit the display button
}
//The interrupt occurs when you push the button
SIGNAL(INT0_vect){
//When you hit the button, we will need to display the time
if(show_the_time == FALSE) show_the_time = TRUE;
}
void setup() {
//To reduce power, setup all pins as inputs with no pullups
for(int x = 1 ; x < 18 ; x++){
pinMode(x, INPUT);
digitalWrite(x, LOW);
}
pinMode(2, INPUT); //This is the main button, tied to INT0
digitalWrite(2, HIGH); //Enable internal pull up on button
//These pins are used to control the display
pinMode(segA, OUTPUT);
pinMode(segB, OUTPUT);
pinMode(segC, OUTPUT);
pinMode(segD, OUTPUT);
pinMode(segE, OUTPUT);
pinMode(segF, OUTPUT);
pinMode(segG, OUTPUT);
//These are PWM pins
pinMode(digit1, OUTPUT);
pinMode(digit2, OUTPUT);
pinMode(digit3, OUTPUT);
pinMode(digit4, OUTPUT);
//Power down various bits of hardware to lower power usage
set_sleep_mode(SLEEP_MODE_PWR_SAVE);
sleep_enable();
//Shut off ADC, TWI, SPI, Timer0, Timer1
ADCSRA &= ~(1<<ADEN); //Disable ADC
ACSR = (1<<ACD); //Disable the analog comparator
DIDR0 = 0x3F; //Disable digital input buffers on all ADC0-ADC5 pins
DIDR1 = (1<<AIN1D)|(1<<AIN0D); //Disable digital input buffer on AIN1/0
power_twi_disable();
power_spi_disable();
power_usart0_disable();
power_timer0_disable(); //Needed for delay_ms
power_timer1_disable();
//power_timer2_disable(); //Needed for asynchronous 32kHz operation
//Setup TIMER2
TCCR2A = 0x00;
//TCCR2B = (1<<CS22)|(1<<CS20); //Set CLK/128 or overflow interrupt every 1s
TCCR2B = (1<<CS22)|(1<<CS21)|(1<<CS20); //Set CLK/1024 or overflow interrupt every 8s
ASSR = (1<<AS2); //Enable asynchronous operation
TIMSK2 = (1<<TOIE2); //Enable the timer 2 interrupt
//Setup external INT0 interrupt
EICRA = (1<<ISC01); //Interrupt on falling edge
EIMSK = (1<<INT0); //Enable INT0 interrupt
//System clock futzing
//CLKPR = (1<<CLKPCE); //Enable clock writing
//CLKPR = (1<<CLKPS3); //Divid the system clock by 256
//Serial.begin(9600);
//Serial.println("32kHz Testing:");
sei(); //Enable global interrupts
}
void loop() {
sleep_mode(); //Stop everything and go to sleep. Wake up if the Timer2 buffer overflows or if you hit the button
if(show_the_time == TRUE) {
//Update the minutes and hours variables
minutes += seconds / 60; //Example: seconds = 2317, minutes = 58 + 38 = 96
seconds %= 60; //seconds = 37
hours += minutes / 60; //12 + (96 / 60) = 13
minutes %= 60; //minutes = 36
//Here is where we assume 12 hour display
while(hours > 12)
hours -= 12;
//while(hours > 24) hours -= 24;
/*Serial.print(hours, DEC);
Serial.print(":");
Serial.print(minutes, DEC);
Serial.print(":");
Serial.println(seconds, DEC);*/
for(int x = 0 ; x < 500 ; x++)
displayNumber(1234);
digitalWrite(A5, HIGH);
fake_msdelay(100); //Small debounce
digitalWrite(A5, LOW);
show_the_time = FALSE;
}
}
//This is a not-so-accurate delay routine
//Calling fake_msdelay(100) will delay for about 100ms
//Assumes 8MHz clock
void fake_msdelay(int x){
for( ; x > 0 ; x--)
fake_usdelay(1000);
}
//This is a not-so-accurate delay routine
//Calling fake_usdelay(100) will delay for about 100us
//Assumes 8MHz clock
void fake_usdelay(int x){
for( ; x > 0 ; x--) {
__asm__("nop\n\t");
__asm__("nop\n\t");
__asm__("nop\n\t");
__asm__("nop\n\t");
__asm__("nop\n\t");
__asm__("nop\n\t");
__asm__("nop\n\t");
}
}
//Given a number, we display 10:22
//After running through the 4 numbers, the display is left turned off
void displayNumber(int toDisplay) {
#define DISPLAY_BRIGHTNESS 500
//Display brightness
//Each digit is on for a certain amount of microseconds
//Then it is off until we have reached a total of 20ms for the function call
//Let's assume each digit is on for 1000us
//If each digit is on for 1ms, there are 4 digits, so the display is off for 16ms.
//That's a ratio of 1ms to 16ms or 6.25% on time (PWM).
//Let's define a variable called brightness that varies from:
//5000 blindingly bright (15.7mA current draw per digit)
//2000 shockingly bright (11.4mA current draw per digit)
//1000 pretty bright (5.9mA)
//500 normal (3mA)
//200 dim but readable (1.4mA)
//50 dim but readable (0.56mA)
//5 dim but readable (0.31mA)
//1 dim but readable in dark (0.28mA)
#define DIGIT_ON HIGH
#define DIGIT_OFF LOW
//long beginTime = millis();
for(int digit = 4 ; digit > 0 ; digit--) {
//Turn on a digit for a short amount of time
switch(digit) {
case 1:
digitalWrite(digit1, DIGIT_ON);
break;
case 2:
digitalWrite(digit2, DIGIT_ON);
break;
case 3:
digitalWrite(digit3, DIGIT_ON);
break;
case 4:
digitalWrite(digit4, DIGIT_ON);
break;
}
//Turn on the right segments for this digit
lightNumber(toDisplay % 10);
toDisplay /= 10;
//delayMicroseconds(DISPLAY_BRIGHTNESS); //Display this digit for a fraction of a second (between 1us and 5000us, 500 is pretty good)
fake_usdelay(1500); //Display this digit for a fraction of a second (between 1us and 5000us, 500 is pretty good)
//Turn off all segments
lightNumber(10);
//Turn off all digits
digitalWrite(digit1, DIGIT_OFF);
digitalWrite(digit2, DIGIT_OFF);
digitalWrite(digit3, DIGIT_OFF);
digitalWrite(digit4, DIGIT_OFF);
}
//while( (millis() - beginTime) < 10) ; //Wait for 20ms to pass before we paint the display again
fake_msdelay(1);
}
//Given a number, turns on those segments
//If number == 10, then turn off number
void lightNumber(int numberToDisplay) {
#define SEGMENT_ON LOW
#define SEGMENT_OFF HIGH
switch (numberToDisplay){
case 0:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_OFF);
break;
case 1:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;
case 2:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_OFF);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_ON);
break;
case 3:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_ON);
break;
case 4:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;
case 5:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;
case 6:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;
case 7:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;
case 8:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;
case 9:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;
case 10:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_OFF);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;
}
}

View File

@@ -0,0 +1,65 @@
#include <avr/sleep.h>
#include <avr/power.h> // Power management
#include <avr/wdt.h>
const byte LED = 13;
// watchdog interrupt
ISR (WDT_vect)
{
wdt_disable(); // disable watchdog
} // end of WDT_vect
void myWatchdogEnable()
{
// clear various "reset" flags
MCUSR = 0;
// allow changes, disable reset
WDTCSR = bit (WDCE) | bit (WDE);
// set interrupt mode and an interval
WDTCSR = bit (WDIE) | bit (WDP3) | bit (WDP0); // set WDIE, and 8 seconds delay
wdt_reset(); // pat the dog
byte old_ADCSRA = ADCSRA;
// disable ADC to save power
ADCSRA = 0;
// slow clock to divide by 256
// clock_prescale_set (clock_div_256);
// ready to sleep
set_sleep_mode (SLEEP_MODE_PWR_DOWN);
sleep_enable();
// turn off brown-out enable in software
MCUCR = bit (BODS) | bit (BODSE);
MCUCR = bit (BODS);
sleep_cpu ();
// cancel sleep as a precaution
sleep_disable();
power_all_enable (); // enable modules again
// reenable ADC
ADCSRA = old_ADCSRA;
}
void setup () {
Serial.begin(9600);
}
void loop ()
{
pinMode (LED, OUTPUT);
digitalWrite (LED, HIGH);
pinMode (LED, INPUT);
delay (100);
digitalWrite (LED, LOW);
delay(10);
// sleep for a total of n x 8 seconds
for (int i = 0; i < 8; i++) {
myWatchdogEnable ();
}
}

View File

@@ -0,0 +1,134 @@
#include <avr/sleep.h>
#include <avr/power.h> // Power management
#include <avr/wdt.h>
#include <Wire.h>
#include <RCSwitch.h>
const byte LED = 13;
const byte LUMINOSITE_PIN=A0;
const unsigned long activation = 111269;
const unsigned long idLum=2269;
const unsigned long desactivation = 962111;
const unsigned int delai = 11;
RCSwitch mySwitch = RCSwitch();
// watchdog interrupt
ISR (WDT_vect)
{
wdt_disable(); // disable watchdog
} // end of WDT_vect
void myWatchdogEnable()
{
// clear various "reset" flags
MCUSR = 0;
// allow changes, disable reset
WDTCSR = bit (WDCE) | bit (WDE);
// set interrupt mode and an interval
WDTCSR = bit (WDIE) | bit (WDP3) | bit (WDP0); // set WDIE, and 8 seconds delay
wdt_reset(); // pat the dog
byte old_ADCSRA = ADCSRA;
// disable ADC to save power
ADCSRA = 0;
// slow clock to divide by 256
// clock_prescale_set (clock_div_256);
// ready to sleep
set_sleep_mode (SLEEP_MODE_PWR_DOWN);
sleep_enable();
// turn off brown-out enable in software
MCUCR = bit (BODS) | bit (BODSE);
MCUCR = bit (BODS);
sleep_cpu ();
// cancel sleep as a precaution
sleep_disable();
power_all_enable (); // enable modules again
// reenable ADC
ADCSRA = old_ADCSRA;
}
void setup () {
Serial.begin(9600);
}
void loop ()
{
mySwitch.enableTransmit(2);
long vcc = readVcc();
pinMode (LED, OUTPUT);
digitalWrite (LED, HIGH);
pinMode (LED, INPUT);
int lum = analogRead(A0);
mySwitch.send(activation, 24);
(delai); //delayMicroseconds
// LUX
// R=K*L^-gamma
// R étant la résistance pour un niveau d'éclairement L.
myMessageSend(idLum,(1000.0 * lum / 1024.0));
mySwitch.send(desactivation, 24);
delay(delai);
Serial.print(vcc);
Serial.print(" ");
Serial.println(lum);
delay (100);
digitalWrite (LED, LOW);
delay(10);
// sleep for a total of 64 seconds (8 x 8)
//for (int i = 0; i < 8; i++) {
myWatchdogEnable ();
// }
}
void myMessageSend(long id, long value) {
Serial.print("Send id="); Serial.print(id);
Serial.print(" value="); Serial.println(value);
mySwitch.send(id, 24); //"000000000001010100010001");
delay(delai);
mySwitch.send(value, 24); //"000000000001010100010001");
delay(delai);
//delay(5000);
//delayMicroseconds(TWOTIME*8);
}
//--------------------------------------------------------------------------------------------------
// Read current supply voltage
//--------------------------------------------------------------------------------------------------
long readVcc() {
bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
long result;
// Read 1.1V reference against Vcc
#if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
#endif
// ADCSRB = 0;
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate Vcc in mV
// ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
// analogReference(DEFAULT);
return result; // Vcc in millivolts
}

View File

@@ -0,0 +1,385 @@
#include <avr/sleep.h>
#include <avr/power.h> // Power management
#include <avr/wdt.h>
#include <Wire.h>
#include <RCSwitch.h>
#include <Adafruit_BMP085.h>
const byte LED = 13;
const byte LUMINOSITE_PIN=A0;
const unsigned long activation = 111269;
const unsigned long idLum=2269;
const unsigned long desactivation = 962111;
const unsigned int delai = 11;
RCSwitch mySwitch = RCSwitch();
// ECRAN LCD
#include <SPI.h> // We'll use SPI to transfer data. Faster!
#define PIN_RESET 3
#define PIN_SCE 4
#define PIN_DC 5
#define PIN_SDIN 6
#define PIN_SCLK 7
#define PIN_LCD 9 // backlight
#define PIN_FADER 1 // analog
#define PIN_TMP 0 // analog
#define LCD_C LOW
#define LCD_D HIGH
#define LCD_COMMAND 0
#define LCD_X 84
#define LCD_Y 48
long contrast = 200;
char strBuffer[255];
static const byte ASCII[][5] =
{
{0x00, 0x00, 0x00, 0x00, 0x00} // 20
,{0x00, 0x00, 0x5f, 0x00, 0x00} // 21 !
,{0x00, 0x07, 0x00, 0x07, 0x00} // 22 "
,{0x14, 0x7f, 0x14, 0x7f, 0x14} // 23 #
,{0x24, 0x2a, 0x7f, 0x2a, 0x12} // 24 $
,{0x23, 0x13, 0x08, 0x64, 0x62} // 25 %
,{0x36, 0x49, 0x55, 0x22, 0x50} // 26 &
,{0x00, 0x05, 0x03, 0x00, 0x00} // 27 '
,{0x00, 0x1c, 0x22, 0x41, 0x00} // 28 (
,{0x00, 0x41, 0x22, 0x1c, 0x00} // 29 )
,{0x14, 0x08, 0x3e, 0x08, 0x14} // 2a *
,{0x08, 0x08, 0x3e, 0x08, 0x08} // 2b +
,{0x00, 0x50, 0x30, 0x00, 0x00} // 2c ,
,{0x08, 0x08, 0x08, 0x08, 0x08} // 2d -
,{0x00, 0x60, 0x60, 0x00, 0x00} // 2e .
,{0x20, 0x10, 0x08, 0x04, 0x02} // 2f backslash
,{0x3e, 0x51, 0x49, 0x45, 0x3e} // 30 0
,{0x00, 0x42, 0x7f, 0x40, 0x00} // 31 1
,{0x42, 0x61, 0x51, 0x49, 0x46} // 32 2
,{0x21, 0x41, 0x45, 0x4b, 0x31} // 33 3
,{0x18, 0x14, 0x12, 0x7f, 0x10} // 34 4
,{0x27, 0x45, 0x45, 0x45, 0x39} // 35 5
,{0x3c, 0x4a, 0x49, 0x49, 0x30} // 36 6
,{0x01, 0x71, 0x09, 0x05, 0x03} // 37 7
,{0x36, 0x49, 0x49, 0x49, 0x36} // 38 8
,{0x06, 0x49, 0x49, 0x29, 0x1e} // 39 9
,{0x00, 0x36, 0x36, 0x00, 0x00} // 3a :
,{0x00, 0x56, 0x36, 0x00, 0x00} // 3b ;
,{0x08, 0x14, 0x22, 0x41, 0x00} // 3c <
,{0x14, 0x14, 0x14, 0x14, 0x14} // 3d =
,{0x00, 0x41, 0x22, 0x14, 0x08} // 3e >
,{0x02, 0x01, 0x51, 0x09, 0x06} // 3f ?
,{0x32, 0x49, 0x79, 0x41, 0x3e} // 40 @
,{0x7e, 0x11, 0x11, 0x11, 0x7e} // 41 A
,{0x7f, 0x49, 0x49, 0x49, 0x36} // 42 B
,{0x3e, 0x41, 0x41, 0x41, 0x22} // 43 C
,{0x7f, 0x41, 0x41, 0x22, 0x1c} // 44 D
,{0x7f, 0x49, 0x49, 0x49, 0x41} // 45 E
,{0x7f, 0x09, 0x09, 0x09, 0x01} // 46 F
,{0x3e, 0x41, 0x49, 0x49, 0x7a} // 47 G
,{0x7f, 0x08, 0x08, 0x08, 0x7f} // 48 H
,{0x00, 0x41, 0x7f, 0x41, 0x00} // 49 I
,{0x20, 0x40, 0x41, 0x3f, 0x01} // 4a J
,{0x7f, 0x08, 0x14, 0x22, 0x41} // 4b K
,{0x7f, 0x40, 0x40, 0x40, 0x40} // 4c L
,{0x7f, 0x02, 0x0c, 0x02, 0x7f} // 4d M
,{0x7f, 0x04, 0x08, 0x10, 0x7f} // 4e N
,{0x3e, 0x41, 0x41, 0x41, 0x3e} // 4f O
,{0x7f, 0x09, 0x09, 0x09, 0x06} // 50 P
,{0x3e, 0x41, 0x51, 0x21, 0x5e} // 51 Q
,{0x7f, 0x09, 0x19, 0x29, 0x46} // 52 R
,{0x46, 0x49, 0x49, 0x49, 0x31} // 53 S
,{0x01, 0x01, 0x7f, 0x01, 0x01} // 54 T
,{0x3f, 0x40, 0x40, 0x40, 0x3f} // 55 U
,{0x1f, 0x20, 0x40, 0x20, 0x1f} // 56 V
,{0x3f, 0x40, 0x38, 0x40, 0x3f} // 57 W
,{0x63, 0x14, 0x08, 0x14, 0x63} // 58 X
,{0x07, 0x08, 0x70, 0x08, 0x07} // 59 Y
,{0x61, 0x51, 0x49, 0x45, 0x43} // 5a Z
,{0x00, 0x7f, 0x41, 0x41, 0x00} // 5b [
,{0x02, 0x04, 0x08, 0x10, 0x20} // 5c ¥
,{0x00, 0x41, 0x41, 0x7f, 0x00} // 5d ]
,{0x04, 0x02, 0x01, 0x02, 0x04} // 5e ^
,{0x40, 0x40, 0x40, 0x40, 0x40} // 5f _
,{0x00, 0x01, 0x02, 0x04, 0x00} // 60 `
,{0x20, 0x54, 0x54, 0x54, 0x78} // 61 a
,{0x7f, 0x48, 0x44, 0x44, 0x38} // 62 b
,{0x38, 0x44, 0x44, 0x44, 0x20} // 63 c
,{0x38, 0x44, 0x44, 0x48, 0x7f} // 64 d
,{0x38, 0x54, 0x54, 0x54, 0x18} // 65 e
,{0x08, 0x7e, 0x09, 0x01, 0x02} // 66 f
,{0x0c, 0x52, 0x52, 0x52, 0x3e} // 67 g
,{0x7f, 0x08, 0x04, 0x04, 0x78} // 68 h
,{0x00, 0x44, 0x7d, 0x40, 0x00} // 69 i
,{0x20, 0x40, 0x44, 0x3d, 0x00} // 6a j
,{0x7f, 0x10, 0x28, 0x44, 0x00} // 6b k
,{0x00, 0x41, 0x7f, 0x40, 0x00} // 6c l
,{0x7c, 0x04, 0x18, 0x04, 0x78} // 6d m
,{0x7c, 0x08, 0x04, 0x04, 0x78} // 6e n
,{0x38, 0x44, 0x44, 0x44, 0x38} // 6f o
,{0x7c, 0x14, 0x14, 0x14, 0x08} // 70 p
,{0x08, 0x14, 0x14, 0x18, 0x7c} // 71 q
,{0x7c, 0x08, 0x04, 0x04, 0x08} // 72 r
,{0x48, 0x54, 0x54, 0x54, 0x20} // 73 s
,{0x04, 0x3f, 0x44, 0x40, 0x20} // 74 t
,{0x3c, 0x40, 0x40, 0x20, 0x7c} // 75 u
,{0x1c, 0x20, 0x40, 0x20, 0x1c} // 76 v
,{0x3c, 0x40, 0x30, 0x40, 0x3c} // 77 w
,{0x44, 0x28, 0x10, 0x28, 0x44} // 78 x
,{0x0c, 0x50, 0x50, 0x50, 0x3c} // 79 y
,{0x44, 0x64, 0x54, 0x4c, 0x44} // 7a z
,{0x00, 0x08, 0x36, 0x41, 0x00} // 7b {
,{0x00, 0x00, 0x7f, 0x00, 0x00} // 7c |
,{0x00, 0x41, 0x36, 0x08, 0x00} // 7d }
,{0x10, 0x08, 0x08, 0x10, 0x08} // 7e ←
,{0x78, 0x46, 0x41, 0x46, 0x78} // 7f →
};
// FIN ECRAN
// watchdog interrupt
ISR (WDT_vect)
{
wdt_disable(); // disable watchdog
} // end of WDT_vect
void myWatchdogEnable()
{
// clear various "reset" flags
MCUSR = 0;
// allow changes, disable reset
WDTCSR = bit (WDCE) | bit (WDE);
// set interrupt mode and an interval
WDTCSR = bit (WDIE) | bit (WDP3) | bit (WDP0); // set WDIE, and 8 seconds delay
wdt_reset(); // pat the dog
byte old_ADCSRA = ADCSRA;
// disable ADC to save power
ADCSRA = 0;
// slow clock to divide by 256
// clock_prescale_set (clock_div_256);
// ready to sleep
set_sleep_mode (SLEEP_MODE_PWR_DOWN);
sleep_enable();
// turn off brown-out enable in software
MCUCR = bit (BODS) | bit (BODSE);
MCUCR = bit (BODS);
sleep_cpu ();
// cancel sleep as a precaution
sleep_disable();
power_all_enable (); // enable modules again
// reenable ADC
ADCSRA = old_ADCSRA;
}
void setup () {
Serial.begin(9600);
// ECRAN
LcdInitialise();
LcdClear();
LcdString("Starting");
setContrast(contrast);
//drawLine();
// FIN ECRAN
}
void loop ()
{
mySwitch.enableTransmit(2);
long vcc = readVcc();
pinMode (LED, OUTPUT);
digitalWrite (LED, HIGH);
pinMode (LED, INPUT);
int lum = analogRead(A0);
mySwitch.send(activation, 24);
delay(delai); //delayMicroseconds
// LUX
// R=K*L^-gamma
// R étant la résistance pour un niveau d'éclairement L.
myMessageSend(idLum,(1000.0 * lum / 1024.0));
mySwitch.send(desactivation, 24);
delay(delai);
Serial.print(vcc);
Serial.print(" ");
Serial.println(lum);
delay (100);
digitalWrite (LED, LOW);
delay(10);
// LcdClear();
gotoXY(0,0);
LcdString("Lum ");
itoa(lum,strBuffer,10);
LcdString(strBuffer);
// itoa(fractionC,strBuffer,10);
// LcdString(".");
// LcdString(strBuffer);
LcdString("Lux ");
gotoXY(0,1);
LcdString("Pile ");
itoa(vcc,strBuffer,10);
LcdString(strBuffer);
// itoa(fractionC,strBuffer,10);
// LcdString(".");
// LcdString(strBuffer);
LcdString("V ");
// sleep for a total of 64 seconds (8 x 8)
//for (int i = 0; i < 8; i++) {
//myWatchdogEnable ();
// }
delay(5000);
}
void myMessageSend(long id, long value) {
#ifdef DEBUG
Serial.print("Send id="); Serial.print(id);
Serial.print(" value="); Serial.println(value);
#endif
mySwitch.send(id, 24); //"000000000001010100010001");
delay(delai);
mySwitch.send(value, 24); //"000000000001010100010001");
delay(delai);
//delay(5000);
//delayMicroseconds(TWOTIME*8);
}
//--------------------------------------------------------------------------------------------------
// Read current supply voltage
//--------------------------------------------------------------------------------------------------
long readVcc() {
bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
long result;
// Read 1.1V reference against Vcc
#if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
#endif
// ADCSRB = 0;
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate Vcc in mV
// ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
// analogReference(DEFAULT);
return result; // Vcc in millivolts
}
// ECRAN Methodes
void LcdCharacter(char character)
{
LcdWrite(LCD_D, 0x00);
for (int index = 0; index < 5; index++)
{
LcdWrite(LCD_D, ASCII[character - 0x20][index]);
}
LcdWrite(LCD_D, 0x00);
}
void LcdClear(void)
{
for (int index = 0; index < LCD_X * LCD_Y / 8; index++)
{
LcdWrite(LCD_D, 0x00);
}
}
void LcdInitialise(void)
{
pinMode(PIN_SCE, OUTPUT);
pinMode(PIN_RESET, OUTPUT);
pinMode(PIN_DC, OUTPUT);
pinMode(PIN_SDIN, OUTPUT);
pinMode(PIN_SCLK, OUTPUT);
pinMode(PIN_LCD, OUTPUT);
digitalWrite(PIN_LCD, HIGH);
digitalWrite(PIN_RESET, LOW);
digitalWrite(PIN_RESET, HIGH);
LcdWrite(LCD_C, 0x21 ); // LCD Extended Commands.
LcdWrite(LCD_C, 0xB1 ); // Set LCD Vop (Contrast).
LcdWrite(LCD_C, 0x04 ); // Set Temp coefficent. //0x04
LcdWrite(LCD_C, 0x14 ); // LCD bias mode 1:48. //0x13
LcdWrite(LCD_C, 0x0C ); // LCD in normal mode.
LcdWrite(LCD_C, 0x20 );
LcdWrite(LCD_C, 0x0C );
}
void LcdString(char *characters)
{
while (*characters)
{
LcdCharacter(*characters++);
}
}
void LcdWrite(byte dc, byte data)
{
digitalWrite(PIN_DC, dc);
digitalWrite(PIN_SCE, LOW);
shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
digitalWrite(PIN_SCE, HIGH);
}
void setContrast(byte contrast)
{
analogWrite(PIN_LCD, contrast);
}
void gotoXY(int x, int y)
{
LcdWrite( 0, 0x80 | x); // Column.
LcdWrite( 0, 0x40 | y); // Row.
}
void drawLine(void)
{
unsigned char j;
for(j=0; j<84; j++) // top
{
gotoXY (j,0);
LcdWrite (1,0x01);
}
for(j=0; j<84; j++) //Bottom
{
gotoXY (j,5);
LcdWrite (1,0x80);
}
for(j=0; j<6; j++) // Right
{
gotoXY (83,j);
LcdWrite (1,0xff);
}
for(j=0; j<6; j++) // Left
{
gotoXY (0,j);
LcdWrite (1,0xff);
}
}

View File

@@ -0,0 +1,253 @@
// ------------------------------
// LED
// ------------------------------
const byte LED_PIN = 13;
#define DEBUG TRUE
// ------------------------------
// Energie
// ------------------------------
#include "EmonLib.h" // Include Emon Library
EnergyMonitor emon1; // Create an instance
int boucle = 0;
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(9, 8); // RX | TX
// ----------------
// PZEM for arduino
// -----------------
#include <PZEM004Tv30.h>
PZEM004Tv30 pzem(11, 12);
// ----------------------------
// Dimmer
// ----------------------------
#include <RBDdimmer.h>
#define outputPin 6
#define zerocross D2 // for boards with CHANGEBLE input pins
#define pas 5
dimmerLamp dimmer(outputPin); //initialase port for dimmer for ESP8266, ESP32, Arduino due boards
// To set dimmer off ==> dimmer.setPower(128);
// value 0 = On
// ----------------------------
// Interruption
// ----------------------------
const byte interruptPin = 3;
//volatile byte backlight_status = LOW;
// ----------------------------
// Screen LCD
// ----------------------------
#include <LiquidCrystal_I2C.h>
#include "LowPower.h"
#define I2C_SLAVE_ADDRESS 0x0B // 12 pour l'esclave 2 et ainsi de suite
#define PAYLOAD_SIZE 2
LiquidCrystal_I2C lcd(0x27, 16, 2); // set the LCD address to 0x27 for a 16 chars and 2 line display
/******************************************************************/
/******************************************************************/
/******************************************************************/
#define SolaireProduction "1087"
#define Consommation_Apparente "1123"
#define CONSOMMATION_GENERALE "1115"
void setup()
{
lcd.init(); // initialize the lcd
delay(200);
lcd.noBacklight();
lcd.setCursor(0, 0);
lcd.print("Screen Ok");
Serial.begin(9600);
ESPserial.begin(9600);
// Screen
Serial.println("Screen init...");
delay(1000);
pinMode(LED_PIN, OUTPUT);
pinMode(interruptPin, INPUT);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Serial communication & wifi");
emon1.voltage(A1, 320 , 2.6); // Voltage: input pin, calibration, phase_shift
emon1.current(A2, 30); // Current: input pin, calibration.
delay(1000);
// Dimmer
Serial.println("Dimmer Program is starting...");
delay(1000);
dimmer.begin(NORMAL_MODE, ON); //dimmer initialisation: name.begin(MODE, STATE)
Serial.println("Set value");
dimmer.setPower(50); // setPower(0-100%);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Dimmer set to 0");
delay(1000);
lcd.print("-------PZEM-----------"); // Start Print Test to Line 2
pzem.resetEnergy();
delay(1000);
digitalWrite(interruptPin, LOW);
}
void loop()
{
// if (digitalRead(interruptPin) == HIGH) {
// lcd.backlight();
// }
// else {
// lcd.noBacklight();
// }
double Irms[2];
boucle ++;
emon1.calcVI(20, 200); // 1 Demande a Emonlib de tout calculer, (puissance relle, volts moyen, ampère moyen et facteur de puissance)
// Irms[0] = emon1.calcIrms(5440) * 230; //emon1.apparentPower);
Irms[0] = emon1.apparentPower;
float verif_voltage = emon1.Vrms; // 1 creation de la variable "volts moyen" (mesurable avec un voltmètre pour l'etalonnage)
float verif_ampere = emon1.Irms; // 1 creation de la variable "Ampères Moyen" (mesurable avec une pince ampèremétrique pour l'etalonnage))
float Cos_phi = emon1.powerFactor;
Serial.print(verif_voltage);
Serial.print(" V ");
Serial.print(verif_ampere);
Serial.print(" A ");
Serial.print(emon1.realPower);
Serial.print(" Wr ");
Serial.print(emon1.apparentPower); // Calculate Irms only
Serial.print(" Wcap ");
Serial.print(Irms[0]); // Calculate Irms only
Serial.print(" Wc ");
if (boucle < 10) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Calibration :" + String(boucle));
delay (500);
}
else {
double value = pzemRead();
ESPserial.print(getJson(String(SolaireProduction), value));
delay(500);
Serial.print(value); // Calculate Irms only
Serial.print(" Wr ");
ESPserial.print(getJson(String(Consommation_Apparente), emon1.realPower));
delay(500);
ESPserial.print(getJson(String(CONSOMMATION_GENERALE), emon1.apparentPower));
if (boucle % 2 == 0) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Cso:" + String(emon1.apparentPower, 0) + " R " + String(emon1.realPower, 0));
lcd.setCursor(0, 1);
lcd.print("Sol:" + String(value, 0) + " V " + String(emon1.Vrms, 1));
}
delay (2000);
if (boucle > 1000) {
boucle = 11;
}
}
while ( ESPserial.available()) {
Serial.write( ESPserial.read() );
}
Serial.println();
}
double pzemRead() {
lcd.setCursor(0, 0);
double voltage = pzem.voltage();
double current = pzem.current();
double pf = pzem.pf();
double power = pzem.power();
double energy = pzem.energy();
double frequency = pzem.frequency();
// if ( !isnan(voltage) ) {
// Serial.print("Voltage: "); Serial.print(voltage); Serial.println("V");
// //lcd.print(String(voltage,1) + " V ");
//
// } else {
// Serial.println("Error reading voltage");
// }
// if ( !isnan(current) ) {
// Serial.print("Current: "); Serial.print(current); Serial.println("A");
// // lcd.print(String(current,1) + "A ");
//
// } else {
// Serial.println("Error reading current");
// }
if (boucle % 2 == 1) {
lcd.clear();
if ( !isnan(pf) ) {
//Serial.print("PF: "); Serial.println(pf);
lcd.print(String(pf, 3) + "pf ");
if (pf != 0) {
lcd.print(String(power / pf, 0) + "Wa");
}
} else {
//Serial.println("Error reading power factor");
}
lcd.setCursor(0, 1);
if ( !isnan(power) ) {
//Serial.print("Power: "); Serial.print(power); Serial.println("W");
if (pf > 0) {
lcd.print("+" + String(power, 1) + "W ");
}
else {
lcd.print("-" + String(power, 1) + "Wa");
}
} else {
//Serial.println("Error reading power");
}
if ( !isnan(energy) ) {
if (energy < 1000) {
lcd.print(String(energy * 1000, 0) + "Wh ");
}
else {
lcd.print(String(energy, 1) + "kWh ");
}
// Serial.print("Energy: ");
// Serial.print(energy, 3);
// Serial.println("kWh");
} else {
//Serial.println("Error reading energy");
}
// if ( !isnan(frequency) ) {
// Serial.print("Frequency: "); Serial.print(frequency, 1); Serial.println("Hz");
// } else {
// Serial.println("Error reading frequency");
// }
}
return power;
}
String getJson(String idx, double value)
{
String json = "/json.htm?type=command&param=udevice&idx=" + idx + "&svalue=" + String(value) + ";0&nvalue=0&nvalue=0&nvalue=0";
Serial.println(json);
return json;
}

View File

@@ -0,0 +1,109 @@
// ------------------------------
// LED
// ------------------------------
const byte LED_PIN = 13;
#define DEBUG TRUE
#define A1 20
#define A2 21
// ------------------------------
// Energie
// ------------------------------
#include "EmonLib.h" // Include Emon Library
EnergyMonitor emon1; // Create an instance
int boucle = 0;
// ----------------------------
// Interruption
// ----------------------------
const byte interruptPin = 3;
//volatile byte backlight_status = LOW;
/******************************************************************/
/******************************************************************/
/******************************************************************/
#define SolaireProduction "1087"
#define Consommation_Apparente "1123"
#define CONSOMMATION_GENERALE "1115"
void setup()
{
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
pinMode(interruptPin, INPUT);
emon1.voltage(A1, 320 , 2.6); // Voltage: input pin, calibration, phase_shift
emon1.current(A2, 30); // Current: input pin, calibration.
delay(1000);
digitalWrite(interruptPin, LOW);
}
void loop()
{
// if (digitalRead(interruptPin) == HIGH) {
// lcd.backlight();
// }
// else {
// lcd.noBacklight();
// }
double Irms[2];
boucle ++;
emon1.calcVI(20, 200); // 1 Demande a Emonlib de tout calculer, (puissance relle, volts moyen, ampère moyen et facteur de puissance)
// Irms[0] = emon1.calcIrms(5440) * 230; //emon1.apparentPower);
Irms[0] = emon1.apparentPower;
float verif_voltage = emon1.Vrms; // 1 creation de la variable "volts moyen" (mesurable avec un voltmètre pour l'etalonnage)
float verif_ampere = emon1.Irms; // 1 creation de la variable "Ampères Moyen" (mesurable avec une pince ampèremétrique pour l'etalonnage))
float Cos_phi = emon1.powerFactor;
Serial.print(verif_voltage);
Serial.print(" V ");
Serial.print(verif_ampere);
Serial.print(" A ");
Serial.print(emon1.realPower);
Serial.print(" Wr ");
Serial.print(emon1.apparentPower); // Calculate Irms only
Serial.print(" Wcap ");
Serial.print(Irms[0]); // Calculate Irms only
Serial.print(" Wc ");
if (boucle < 10) {
Serial.println("Calibration :" + String(boucle));
delay (500);
}
else {
//Serial.println(getJson(String(Consommation_Apparente), emon1.realPower));
//delay(500);
// Serial.println(getJson(String(CONSOMMATION_GENERALE), emon1.apparentPower));
if (boucle % 2 == 0) {
Serial.println("Cso:" + String(emon1.apparentPower, 0) + " R " + String(emon1.realPower, 0));
}
delay (2000);
if (boucle > 1000) {
boucle = 11;
}
}
Serial.println();
}
String getJson(String idx, double value)
{
String json = "/json.htm?type=command&param=udevice&idx=" + idx + "&svalue=" + String(value) + ";0&nvalue=0&nvalue=0&nvalue=0";
//Serial.println(json);
return json;
}

View File

@@ -0,0 +1,460 @@
#include <RCSwitch.h>
#include <Narcoleptic.h>
#include <Adafruit_BMP085.h>
#include <Wire.h>
#include "DHT.h"
// ECRAN LCD
#include <SPI.h> // We'll use SPI to transfer data. Faster!
#define PIN_RESET 3
#define PIN_SCE 4
#define PIN_DC 5
#define PIN_SDIN 6
#define PIN_SCLK 7
#define PIN_LCD 9 // backlight
#define PIN_FADER 1 // analog
#define PIN_TMP 0 // analog
#define LCD_C LOW
#define LCD_D HIGH
#define LCD_COMMAND 0
#define LCD_X 84
#define LCD_Y 48
long contrast = 200;
char strBuffer[30];
static const byte ASCII[][5] =
{
{0x00, 0x00, 0x00, 0x00, 0x00} // 20
,{0x00, 0x00, 0x5f, 0x00, 0x00} // 21 !
,{0x00, 0x07, 0x00, 0x07, 0x00} // 22 "
,{0x14, 0x7f, 0x14, 0x7f, 0x14} // 23 #
,{0x24, 0x2a, 0x7f, 0x2a, 0x12} // 24 $
,{0x23, 0x13, 0x08, 0x64, 0x62} // 25 %
,{0x36, 0x49, 0x55, 0x22, 0x50} // 26 &
,{0x00, 0x05, 0x03, 0x00, 0x00} // 27 '
,{0x00, 0x1c, 0x22, 0x41, 0x00} // 28 (
,{0x00, 0x41, 0x22, 0x1c, 0x00} // 29 )
,{0x14, 0x08, 0x3e, 0x08, 0x14} // 2a *
,{0x08, 0x08, 0x3e, 0x08, 0x08} // 2b +
,{0x00, 0x50, 0x30, 0x00, 0x00} // 2c ,
,{0x08, 0x08, 0x08, 0x08, 0x08} // 2d -
,{0x00, 0x60, 0x60, 0x00, 0x00} // 2e .
,{0x20, 0x10, 0x08, 0x04, 0x02} // 2f backslash
,{0x3e, 0x51, 0x49, 0x45, 0x3e} // 30 0
,{0x00, 0x42, 0x7f, 0x40, 0x00} // 31 1
,{0x42, 0x61, 0x51, 0x49, 0x46} // 32 2
,{0x21, 0x41, 0x45, 0x4b, 0x31} // 33 3
,{0x18, 0x14, 0x12, 0x7f, 0x10} // 34 4
,{0x27, 0x45, 0x45, 0x45, 0x39} // 35 5
,{0x3c, 0x4a, 0x49, 0x49, 0x30} // 36 6
,{0x01, 0x71, 0x09, 0x05, 0x03} // 37 7
,{0x36, 0x49, 0x49, 0x49, 0x36} // 38 8
,{0x06, 0x49, 0x49, 0x29, 0x1e} // 39 9
,{0x00, 0x36, 0x36, 0x00, 0x00} // 3a :
,{0x00, 0x56, 0x36, 0x00, 0x00} // 3b ;
,{0x08, 0x14, 0x22, 0x41, 0x00} // 3c <
,{0x14, 0x14, 0x14, 0x14, 0x14} // 3d =
,{0x00, 0x41, 0x22, 0x14, 0x08} // 3e >
,{0x02, 0x01, 0x51, 0x09, 0x06} // 3f ?
,{0x32, 0x49, 0x79, 0x41, 0x3e} // 40 @
,{0x7e, 0x11, 0x11, 0x11, 0x7e} // 41 A
,{0x7f, 0x49, 0x49, 0x49, 0x36} // 42 B
,{0x3e, 0x41, 0x41, 0x41, 0x22} // 43 C
,{0x7f, 0x41, 0x41, 0x22, 0x1c} // 44 D
,{0x7f, 0x49, 0x49, 0x49, 0x41} // 45 E
,{0x7f, 0x09, 0x09, 0x09, 0x01} // 46 F
,{0x3e, 0x41, 0x49, 0x49, 0x7a} // 47 G
,{0x7f, 0x08, 0x08, 0x08, 0x7f} // 48 H
,{0x00, 0x41, 0x7f, 0x41, 0x00} // 49 I
,{0x20, 0x40, 0x41, 0x3f, 0x01} // 4a J
,{0x7f, 0x08, 0x14, 0x22, 0x41} // 4b K
,{0x7f, 0x40, 0x40, 0x40, 0x40} // 4c L
,{0x7f, 0x02, 0x0c, 0x02, 0x7f} // 4d M
,{0x7f, 0x04, 0x08, 0x10, 0x7f} // 4e N
,{0x3e, 0x41, 0x41, 0x41, 0x3e} // 4f O
,{0x7f, 0x09, 0x09, 0x09, 0x06} // 50 P
,{0x3e, 0x41, 0x51, 0x21, 0x5e} // 51 Q
,{0x7f, 0x09, 0x19, 0x29, 0x46} // 52 R
,{0x46, 0x49, 0x49, 0x49, 0x31} // 53 S
,{0x01, 0x01, 0x7f, 0x01, 0x01} // 54 T
,{0x3f, 0x40, 0x40, 0x40, 0x3f} // 55 U
,{0x1f, 0x20, 0x40, 0x20, 0x1f} // 56 V
,{0x3f, 0x40, 0x38, 0x40, 0x3f} // 57 W
,{0x63, 0x14, 0x08, 0x14, 0x63} // 58 X
,{0x07, 0x08, 0x70, 0x08, 0x07} // 59 Y
,{0x61, 0x51, 0x49, 0x45, 0x43} // 5a Z
,{0x00, 0x7f, 0x41, 0x41, 0x00} // 5b [
,{0x02, 0x04, 0x08, 0x10, 0x20} // 5c ¥
,{0x00, 0x41, 0x41, 0x7f, 0x00} // 5d ]
,{0x04, 0x02, 0x01, 0x02, 0x04} // 5e ^
,{0x40, 0x40, 0x40, 0x40, 0x40} // 5f _
,{0x00, 0x01, 0x02, 0x04, 0x00} // 60 `
,{0x20, 0x54, 0x54, 0x54, 0x78} // 61 a
,{0x7f, 0x48, 0x44, 0x44, 0x38} // 62 b
,{0x38, 0x44, 0x44, 0x44, 0x20} // 63 c
,{0x38, 0x44, 0x44, 0x48, 0x7f} // 64 d
,{0x38, 0x54, 0x54, 0x54, 0x18} // 65 e
,{0x08, 0x7e, 0x09, 0x01, 0x02} // 66 f
,{0x0c, 0x52, 0x52, 0x52, 0x3e} // 67 g
,{0x7f, 0x08, 0x04, 0x04, 0x78} // 68 h
,{0x00, 0x44, 0x7d, 0x40, 0x00} // 69 i
,{0x20, 0x40, 0x44, 0x3d, 0x00} // 6a j
,{0x7f, 0x10, 0x28, 0x44, 0x00} // 6b k
,{0x00, 0x41, 0x7f, 0x40, 0x00} // 6c l
,{0x7c, 0x04, 0x18, 0x04, 0x78} // 6d m
,{0x7c, 0x08, 0x04, 0x04, 0x78} // 6e n
,{0x38, 0x44, 0x44, 0x44, 0x38} // 6f o
,{0x7c, 0x14, 0x14, 0x14, 0x08} // 70 p
,{0x08, 0x14, 0x14, 0x18, 0x7c} // 71 q
,{0x7c, 0x08, 0x04, 0x04, 0x08} // 72 r
,{0x48, 0x54, 0x54, 0x54, 0x20} // 73 s
,{0x04, 0x3f, 0x44, 0x40, 0x20} // 74 t
,{0x3c, 0x40, 0x40, 0x20, 0x7c} // 75 u
,{0x1c, 0x20, 0x40, 0x20, 0x1c} // 76 v
,{0x3c, 0x40, 0x30, 0x40, 0x3c} // 77 w
,{0x44, 0x28, 0x10, 0x28, 0x44} // 78 x
,{0x0c, 0x50, 0x50, 0x50, 0x3c} // 79 y
,{0x44, 0x64, 0x54, 0x4c, 0x44} // 7a z
,{0x00, 0x08, 0x36, 0x41, 0x00} // 7b {
,{0x00, 0x00, 0x7f, 0x00, 0x00} // 7c |
,{0x00, 0x41, 0x36, 0x08, 0x00} // 7d }
,{0x10, 0x08, 0x08, 0x10, 0x08} // 7e ←
,{0x78, 0x46, 0x41, 0x46, 0x78} // 7f →
};
// FIN ECRAN
#define DHTPIN A2 // what pin we're connected to
#define DHTTYPE DHT11 // DHT 11
// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);
#define SEND_MESSAGE_DELAY 30000 // Ne pas dépasser 32000 !! Delay in ms between each value's extraction
#define SEND_433_PAUSE 160 // 16 multiple
//#define DEBUG true
const unsigned long activation = 111269;
const unsigned long idTemp=1969;
const unsigned long idPressure=2069;
const unsigned long idPression=2169;
const unsigned long idLum=2269;
const unsigned long idHum=2369;
const unsigned long desactivation = 962111;
const unsigned int delai = 11;
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
// ################# Barometre ####
Adafruit_BMP085 bmp;
// #####################
float temperature = 0.0;
float pressure = 0.0;
float pression = 0.0;
float presiune = 0.0;
float humidite = 0.0;
RCSwitch mySwitch = RCSwitch();
void setup() {
#ifdef DEBUG
Serial.begin(9600);
Serial.println("\n[Oregon V2.1 encoder]");
#endif
// ECRAN
LcdInitialise();
LcdClear();
LcdString("Starting");
setContrast(contrast);
// FIN ECRAN
pinMode(13, OUTPUT);
mySwitch.enableTransmit(9);
//mySwitch.setRepeatTransmit(2);
// DHT
dht.begin();
}
// Commande pour barometre humidité température
// Virtual Device
// http://192.168.0.10:8080/json.htm?type=command&param=udevice&idx=160&nvalue=0&svalue=23.3;50;2;1024.20;1024&battery=89
void doDHT() {
// 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();
humidite = h;
// Read temperature as Celsius
float t = dht.readTemperature();
// Read temperature as Fahrenheit
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;
} else {
// Compute heat index
// Must send in temp in Fahrenheit!
float hi = dht.computeHeatIndex(f, h);
#ifdef DEBUG
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(hi);
Serial.println(" *F");
#endif
}
}
// Prise Eléctrique
//ON 1 1381719 1398103
//ON 2 1394007
//ON 3 1397079 1398103
//
//OFF 1 1381716
//OFF 2 1398103
//OFF 3 1397076
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(10); // wait for a second
digitalWrite(13, LOW);
long vcc = readVcc();
barometre();
doDHT();
#ifdef DEBUG
Serial.print("Send");
Serial.println(vcc);
#endif
mySwitch.send(activation, 24);
(delai); //delayMicroseconds
myMessageSend(idTemp,temperature * 100);
myMessageSend(idPressure,pressure * 10);
myMessageSend(idHum,humidite);
myMessageSend(idPression,pression * 10);
// LUX
// R=K*L^-gamma
// R étant la résistance pour un niveau d'éclairement L.
int lum = analogRead(1);
int lux = (1000.0 * lum / 1024.0);
myMessageSend(idLum,lux);
mySwitch.send(desactivation, 24);
delay(delai);
// ECRAN
LcdClear();
float fractionC;
fractionC = temperature - ((int)temperature);
gotoXY(0,0);
LcdString("TEMP ");
itoa(temperature,strBuffer,10);
LcdString(strBuffer);
itoa(fractionC,strBuffer,10);
LcdString(".");
LcdString(strBuffer);
LcdString("C ");
fractionC = pression - ((int) pression);
gotoXY(0,10);
LcdString("Pres ");
itoa(pression,strBuffer,10);
LcdString(strBuffer);
itoa(fractionC,strBuffer,10);
LcdString(".");
LcdString(strBuffer);
LcdString("hp");
fractionC = lux - ((int) lux);
gotoXY(0,20);
LcdString("Lum ");
itoa(lux,strBuffer,10);
LcdString(strBuffer);
itoa(fractionC,strBuffer,10);
LcdString(".");
LcdString(strBuffer);
LcdString("Lux ");
// FIN ECRAN
#ifdef DEBUG
Serial.print("Luminosite=");
Serial.println(lum);
delay(delai);
#endif
delayMicroseconds(TWOTIME*8);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
Narcoleptic.delay(SEND_MESSAGE_DELAY);
}
void barometre() {
/* See Example: TypeA_WithDIPSwitches */
// mySwitch.switchOn("00001", "10000");
// delay(1000);
// BMP
if (bmp.begin()) {
temperature = bmp.readTemperature();
pressure= bmp.readPressure() / 100.0;
pression = pressure / 101.325;
pression = pression * 0.760 * 100;
// http://en.wikipedia.org/wiki/Atmospheric_pressure#Mean_sea_level_pressure
// Serial.print("Presiure la nivelul marii (calculata) = ");
presiune = bmp.readSealevelPressure(19) / 101.325;
presiune = presiune * 0.760;
#ifdef DEBUG
Serial.print("Temperature="); Serial.println(temperature);
Serial.print("pressure="); Serial.println(pressure);
Serial.print("pression="); Serial.println(pression);
#endif
}
}
void myMessageSend(long id, long value) {
#ifdef DEBUG
Serial.print("Send id="); Serial.print(id);
Serial.print(" value="); Serial.println(value);
#endif
mySwitch.send(id, 24); //"000000000001010100010001");
delay(delai);
mySwitch.send(value, 24); //"000000000001010100010001");
delay(delai);
//delay(5000);
//delayMicroseconds(TWOTIME*8);
}
//--------------------------------------------------------------------------------------------------
// Read current supply voltage
//--------------------------------------------------------------------------------------------------
long readVcc() {
bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
long result;
// Read 1.1V reference against Vcc
#if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
#endif
// ADCSRB = 0;
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate Vcc in mV
// ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
// analogReference(DEFAULT);
return result; // Vcc in millivolts
}
// ECRAN Methodes
void LcdCharacter(char character)
{
LcdWrite(LCD_D, 0x00);
for (int index = 0; index < 5; index++)
{
LcdWrite(LCD_D, ASCII[character - 0x20][index]);
}
LcdWrite(LCD_D, 0x00);
}
void LcdClear(void)
{
for (int index = 0; index < LCD_X * LCD_Y / 8; index++)
{
LcdWrite(LCD_D, 0x00);
}
}
void LcdInitialise(void)
{
pinMode(PIN_SCE, OUTPUT);
pinMode(PIN_RESET, OUTPUT);
pinMode(PIN_DC, OUTPUT);
pinMode(PIN_SDIN, OUTPUT);
pinMode(PIN_SCLK, OUTPUT);
pinMode(PIN_LCD, OUTPUT);
digitalWrite(PIN_LCD, HIGH);
digitalWrite(PIN_RESET, LOW);
digitalWrite(PIN_RESET, HIGH);
LcdWrite(LCD_C, 0x21 ); // LCD Extended Commands.
LcdWrite(LCD_C, 0x91 ); // Set LCD Vop (Contrast).
LcdWrite(LCD_C, 0x04 ); // Set Temp coefficent. //0x04
LcdWrite(LCD_C, 0x14 ); // LCD bias mode 1:48. //0x13
LcdWrite(LCD_C, 0x0C ); // LCD in normal mode.
LcdWrite(LCD_C, 0x20 );
LcdWrite(LCD_C, 0x0C );
}
void LcdString(char *characters)
{
while (*characters)
{
LcdCharacter(*characters++);
}
}
void LcdWrite(byte dc, byte data)
{
digitalWrite(PIN_DC, dc);
digitalWrite(PIN_SCE, LOW);
shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
digitalWrite(PIN_SCE, HIGH);
}
void setContrast(byte contrast)
{
analogWrite(PIN_LCD, contrast);
}
void gotoXY(int x, int y)
{
LcdWrite( 0, 0x80 | x); // Column.
LcdWrite( 0, 0x40 | y); // Row.
}

View File

@@ -0,0 +1,411 @@
//#include <Narcoleptic.h>
#include <ESP8266WiFi.h>
#include "DHT.h"
//Wire.setClock(100000);
#define DEBUG true
#define SEND_MESSAGE_DELAY 30000 // Ne pas dépasser 32000 !! Delay in ms between each value's extraction
//#define SEND_433_PAUSE 160 // 16 multiple
#define DEBUG true
#define DHTPIN A2 // what pin we're connected to
#define DHTTYPE DHT11 // DHT 11
float temperature = 0.0;
float pressure = 0.0;
float pression = 0.0;
float presiune = 0.0;
float humidite = 0.0;
// ESP8266
String NomduReseauWifi = "Livebox-37cc"; // Garder les guillements
String MotDePasse = "8A6060920A8A86896F770F2C47"; // Garder les guillements
boolean done = false;
/****************************************************************/
/* INIT */
/****************************************************************/
void setupESP()
{
#ifdef DEBUG
Serial.begin(9600);
#endif
ESP8266.begin(115200);
envoieAuESP8266("AT+RST");
recoitDuESP8266(2000);
envoieAuESP8266("AT+CIOBAUD=9600");
recoitDuESP8266(2000);
ESP8266.begin(9600);
initESP8266();
}
/****************************************************************/
/* Fonction qui initialise l'ESP8266 */
/****************************************************************/
void initESP8266()
{
pinMode(13, OUTPUT);
pinMode(3, OUTPUT);
digitalWrite(3, HIGH);
debugPrintln("**************** DEBUT DE L'INITIALISATION ***************");
envoieAuESP8266("AT");
recoitDuESP8266(1000);
envoieAuESP8266("AT+CWMODE=3");
recoitDuESP8266(1000);
envoieAuESP8266("AT+CWJAP=\"" + NomduReseauWifi + "\",\"" + MotDePasse + "\"");
recoitDuESP8266(10000);
envoieAuESP8266("AT+CIFSR");
recoitDuESP8266(1000);
envoieAuESP8266("AT+CIPMUX=1");
recoitDuESP8266(1000);
envoieAuESP8266("AT+CIPSERVER=1,80");
recoitDuESP8266(1000);
debugPrintln("***************** INITIALISATION TERMINEE ****************");
debugPrintln("");
}
/****************************************************************/
/* Fonction qui envoie une commande à l'ESP8266 */
/****************************************************************/
void envoieAuESP8266(String commande)
{
// debugPrintln(commande);
ESP8266.println(commande);
}
/****************************************************************/
/*Fonction qui lit et affiche les messages envoyés par l'ESP8266*/
/****************************************************************/
void recoitDuESP8266(const int timeout)
{
String reponse = "";
long int time = millis();
while ( (time + timeout) > millis())
{
while (ESP8266.available())
{
char c = ESP8266.read();
reponse += c;
}
}
debugPrintln(reponse);
}
// FIN ESP8266
void recup() {
// Initialize DHT sensor for normal 16mhz Arduino
// DHT dht(DHTPIN, DHTTYPE);
// // DHT
// dht.begin();
// // Commande pour barometre humidité température
// // Virtual Device
// // http://192.168.0.10:8080/json.htm?type=command&param=udevice&idx=160&nvalue=0&svalue=23.3;50;2;1024.20;1024&battery=89
//
//
// // 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();
// humidite = h;
//
// // Read temperature as Celsius
// float t = dht.readTemperature();
// // Read temperature as Fahrenheit
// float f = dht.readTemperature(true);
// // Check if any reads failed and exit early (to try again).
// if (isnan(h) || isnan(t) || isnan(f)) {
// debugPrintln("Failed to read from DHT sensor!");
// return;
// } else {
// // Compute heat index
// // Must send in temp in Fahrenheit!
// float hi = dht.computeHeatIndex(f, h);
//
// debugPrint("Humidity: ");
// debugPrint(String(h));
// debugPrint(" %\t");
// debugPrint("Temperature: ");
// debugPrint(String(t));
// debugPrint(" *C ");
// debugPrint(String(f));
// debugPrint(" *F\t");
// debugPrint("Heat index: ");
// debugPrint(String(hi));
// debugPrintln(" *F");
//
// }
//
// long vcc = readVcc();
//
// // ################# Barometre ####
// Adafruit_BMP085 bmp;
// // #####################
// // BMP
// if (bmp.begin()) {
// temperature = bmp.readTemperature();
// pressure = bmp.readPressure() / 100.0;
// pression = pressure / 101.325;
// pression = pression * 0.760 * 100;
// // http://en.wikipedia.org/wiki/Atmospheric_pressure#Mean_sea_level_pressure
// // debugPrint("Presiure la nivelul marii (calculata) = ");
// presiune = bmp.readSealevelPressure(19) / 101.325;
// presiune = presiune * 0.760;
//
// debugPrint("Temperature="); debugPrintln(String(temperature));
// debugPrint("pressure="); debugPrintln(String(pressure));
// debugPrint("pression="); debugPrintln(String(pression));
// }
//
// // LUX
// // R=K*L^-gamma
// // R étant la résistance pour un niveau d'éclairement L.
// int lum = analogRead(1);
// int lux = (1000.0 * lum / 1024.0);
// debugPrint("Luminosite=");
// debugPrintln(String(lum));
}
void setup() {
pinMode(13, OUTPUT);
}
int boucle = 0;
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(10); // wait
digitalWrite(13, LOW);
// recup();
// ESP8266
// ESP8266
setupESP();
//
// sendToDomoticz(122,temperature);
// sendToDomoticz(121,pressure);
// sendToDomoticz(123,pression);
// sendToDomoticz(158,150); //lux);
envoie("/json.htm?type=command&param=udevice&idx=158&svalue=255");
//envoie("/json.htm?type=devices&rid=" + String(290));
//sendToDomoticz(288,234 + boucle * 5);
boucle++;
// FIN ESP8266
delay(30000);
// Narcoleptic.delay(SEND_MESSAGE_DELAY);
// Narcoleptic.delay(SEND_MESSAGE_DELAY);
// Narcoleptic.delay(SEND_MESSAGE_DELAY);
// Narcoleptic.delay(SEND_MESSAGE_DELAY);
}
void debugPrint(String m) {
#ifdef DEBUG
Serial.print(m);
#endif
}
void debugPrintln(String m) {
#ifdef DEBUG
Serial.println(m);
#endif
}
//void sendToDomoticz(int id, int val) {
// envoie("/json.htm?type=command&param=udevice&idx=" + String(id) + "&svalue=" + String(val));
//}
//
//
////--------------------------------------------------------------------------------------------------
//// Read current supply voltage
////--------------------------------------------------------------------------------------------------
//long readVcc() {
// bitClear(PRR, PRADC); ADCSRA |= bit(ADEN); // Enable the ADC
// long result;
// // Read 1.1V reference against Vcc
//#if defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
// ADMUX = _BV(MUX5) | _BV(MUX0); // For ATtiny84
//#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
// ADMUX = _BV(MUX3) | _BV(MUX2);
//#else
// ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // For ATmega328
//#endif
// // ADCSRB = 0;
//
// delay(2); // Wait for Vref to settle
// ADCSRA |= _BV(ADSC); // Convert
// while (bit_is_set(ADCSRA, ADSC));
// result = ADCL;
// result |= ADCH << 8;
// result = 1126400L / result; // Back-calculate Vcc in mV
// // ADCSRA &= ~ bit(ADEN); bitSet(PRR, PRADC); // Disable the ADC to save power
//
// // analogReference(DEFAULT);
//
// return result; // Vcc in millivolts
//}
void connection() {
debugPrintln("***************** Connexion ****************");
/**
* Faire un HTTP GET
*/
debugPrintln("***************** GET ******************************");
String cmd = "AT+CIPSTART=4,\"TCP\",\"192.168.0.10\",8080";
envoieAuESP8266(cmd);
recoitDuESP8266(2000);
}
void envoie(String url) {
connection();
int maxLoops = 10;
int currentLoop = 0;
//String url = "/json.htm?type=devices&rid=" + String(idRadiateurInDomoticz);
String cmdGET = "GET " + url + " HTTP/1.1\r\n"
+ "Host: 192.168.0.10\r\nUser-Agent: ESP8266_HTTP_Client\r\nConnection: close\r\n\r\n";
debugPrintln("***************Commande GET **********************");
// demande d'envoi
ESP8266.print("AT+CIPSEND=4,");
ESP8266.println(cmdGET.length());
delay(500);
done = ESP8266.find(">");
currentLoop = 0;
while (!done) {
delay(500);
done = ESP8266.find(">");
if (currentLoop >= maxLoops) {
//debugPrintln(" Attente dépassée");
break;
}
currentLoop++;
//debugPrint(".");
}
// requete
envoieAuESP8266(cmdGET + "\r\n\r\n");
// recoitDuESP8266(8000);
String ret = recoitDuESP8266WithJson(10000, "status");
debugPrintln("** ret=" + ret);
if (ret.equalsIgnoreCase("On")) {
digitalWrite(3, HIGH);
digitalWrite(13, HIGH);
} else if (ret.equalsIgnoreCase("Off")) {
digitalWrite(3, LOW);
digitalWrite(13, LOW);
}
deconnexion();
}
void deconnexion() {
////////////////////////////////
// sendToDomoticz("288", "15", "225");
///////////////////////////////
envoieAuESP8266("AT+CIPSTATUS");
recoitDuESP8266(2000);
// Close all connections
envoieAuESP8266("AT+CIPCLOSE=5");
recoitDuESP8266(2000);
// restart from zero
envoieAuESP8266("AT");
recoitDuESP8266(2000);
// 4 secondes déjà passées
delay(200);
}
/****************************************************************/
/*Fonction qui lit et affiche les messages envoyés par l'ESP8266*/
/****************************************************************/
String recoitDuESP8266WithJson(const int timeout, String jsonId)
{
String ret = "";
String reponse = "";
boolean found = false;
long int time = millis();
while ( (time + timeout) > millis())
{
while (ESP8266.available())
{
//reponse = "";
char c = ESP8266.read();
reponse += c;
//reponse.trim();
if (reponse.equalsIgnoreCase(jsonId)) {
debugPrint("Trouve" + reponse + " " + jsonId);
}
if (c == 10 || c == 13 || reponse.length() > 80) {
reponse.trim();
// debugPrint(reponse);
int p = reponse.indexOf(':');
String id = reponse.substring(0, p);
String value = reponse.substring(p + 1, reponse.length() - 1);
id.trim();
value.trim();
id.replace("\"", "");
value.replace("\"", "");
if (id.equalsIgnoreCase(jsonId) && !found) {
debugPrintln("========> Trouve " + jsonId + " == " + value);
ret = value;
found = true;
} else {
debugPrintln(id + " " + value);
}
reponse = "";
}
}
}
//debugPrintln(reponse);
return ret;
}

View File

@@ -0,0 +1,86 @@
#include <avr/io.h>
#include <avr/interrupt.h>
//*********************************************//
//********* Prototypes de fonctions ***********//
//*********************************************//
//Initialise l'ADC et démarre une première conversion
void initAdc();
//*********************************************//
//********* Variables globales ***********//
//*********************************************//
//ADC variables
volatile uint16_t adc = 0;
//*********************************************//
//********* Programme principal ***********//
//*********************************************//
int main(void){
initAdc();
DDRB |= 1<<DDB0;
sei(); //Activer les interruptions
while(1){
if(adc > 0){
PORTB |= 1<<PORTB0;
}
else{
PORTB &= ~(1<<PORTB0);
}
}
return 0;
}
//*********************************************//
//********* Interruptions ***********//
//*********************************************//
//Interruption lorsqu'une conversion de l'ADC se termine
//Conversion en boucle
ISR(ADC_vect){
//Lire le resultat
adc = ADC;
//Démarrer une nouvelle conversion
ADCSRA |= 1<<ADSC;
}
//*********************************************//
//********* Fonctions ***********//
//*********************************************//
//Initialise l'ADC et démarre une première conversion
void initAdc(){
//Activer l'ADC via ADEN dans ADCSRA
ADCSRA |= 1<ADEN;
//Selectionner la référence de voltage via REFSn dans ADMUX
//Rien à faire car utilisation de AREF, donc REFS0 et RES1 = 0
//Sélectionner le premier convertisseur via MUX dans ADMUX
//Rien à faire car l'on souhaite commencer par ADC0, donc MUX3...0 = 0
//Activer l'interruption sur conversion terminée via ADIE dans ADCSRA
ADCSRA |= 1<<ADIE;
//Paramétrer le prescaler de l'ADC à 64 :horloge 8Mhz -> horloge ADC de 125kHz
ADCSRA |= 1<<ADPS1 | 1<<ADPS2;
//Démarrer une première conversion
ADCSRA |= 1<<ADSC;
}

View File

@@ -0,0 +1,72 @@
#include <avr/sleep.h>
const byte LED = 13;
int sensorPin = A0; // select the input pin for the potentiometer
int sensorValue = 0; // variable to store the value coming from the sensor
// keep the state of register ADCSRA
byte keep_ADCSRA;
void wake ()
{
// cancel sleep as a precaution
sleep_disable();
// must do this as the pin will probably stay low for a while
detachInterrupt (0);
ADCSRA = keep_ADCSRA;
} // end of wake
void setup ()
{
digitalWrite (2, HIGH); // enable pull-up
} // end of setup
void loop ()
{
pinMode (LED, OUTPUT);
// three second LED to confirm start of process:
digitalWrite (LED, HIGH);
delay (3000);
digitalWrite (LED, LOW);
delay (50);
// read the value from the sensor:
sensorValue = analogRead(sensorPin);
// turn the ledPin on
digitalWrite(LED, HIGH);
// stop the program for <sensorValue> milliseconds:
delay(sensorValue);
// turn the ledPin off:
digitalWrite(LED, LOW);
// stop the program for for <sensorValue> milliseconds:
delay(sensorValue);
pinMode (LED, INPUT);
keep_ADCSRA = ADCSRA;
// disable ADC
ADCSRA = 0;
set_sleep_mode (SLEEP_MODE_PWR_DOWN);
sleep_enable();
// Do not interrupt before we go to sleep, or the
// ISR will detach interrupts and we won't wake.
noInterrupts ();
// will be called when pin D2 goes low
attachInterrupt (0, wake, LOW);
// turn off brown-out enable in software
// BODS must be set to one and BODSE must be set to zero within four clock cycles
MCUCR = bit (BODS) | bit (BODSE);
// The BODS bit is automatically cleared after three clock cycles
MCUCR = bit (BODS);
// We are guaranteed that the sleep_cpu call will be done
// as the processor executes the next instruction after
// interrupts are turned on.
interrupts (); // one cycle
sleep_cpu (); // one cycle
} // end of loop

459
ATMEGA_TH1/ATMEGA_TH1.ino Executable file
View File

@@ -0,0 +1,459 @@
/*
* connectingStuff, Oregon Scientific v2.1 Emitter
* http://connectingstuff.net/blog/encodage-protocoles-oregon-scientific-sur-arduino/
*
* Copyright (C) 2013 olivier.lebrun@gmail.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <avr/sleep.h>
#include <avr/wdt.h>
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif
volatile boolean f_wdt = 1;
#include <dht11.h>
#define DHT11PIN PB1
dht11 DHT11;
//#include <SoftwareSerial.h>
//#define SERIAL_RX PB3 //pin 2 //INPUT
//#define SERIAL_TX PB4 //pin 3 //OUTPUT
//SoftwareSerial Serial(SERIAL_RX, SERIAL_TX); // RX, TX
//#define THN132N
const byte TX_PIN = 0;
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
#define SEND_HIGH() digitalWrite(TX_PIN, HIGH)
#define SEND_LOW() digitalWrite(TX_PIN, LOW)
// Buffer for Oregon message
#ifdef THN132N
byte OregonMessageBuffer[8];
#else
byte OregonMessageBuffer[9];
#endif
/**
* \brief Send logical "0" over RF
* \details azero bit be represented by an off-to-on transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendZero(void)
{
SEND_HIGH();
delayMicroseconds(TIME);
SEND_LOW();
delayMicroseconds(TWOTIME);
SEND_HIGH();
delayMicroseconds(TIME);
}
/**
* \brief Send logical "1" over RF
* \details a one bit be represented by an on-to-off transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendOne(void)
{
SEND_LOW();
delayMicroseconds(TIME);
SEND_HIGH();
delayMicroseconds(TWOTIME);
SEND_LOW();
delayMicroseconds(TIME);
}
/**
* Send a bits quarter (4 bits = MSB from 8 bits value) over RF
*
* @param data Source data to process and sent
*/
/**
* \brief Send a bits quarter (4 bits = MSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterMSB(const byte data)
{
(bitRead(data, 4)) ? sendOne() : sendZero();
(bitRead(data, 5)) ? sendOne() : sendZero();
(bitRead(data, 6)) ? sendOne() : sendZero();
(bitRead(data, 7)) ? sendOne() : sendZero();
}
/**
* \brief Send a bits quarter (4 bits = LSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterLSB(const byte data)
{
(bitRead(data, 0)) ? sendOne() : sendZero();
(bitRead(data, 1)) ? sendOne() : sendZero();
(bitRead(data, 2)) ? sendOne() : sendZero();
(bitRead(data, 3)) ? sendOne() : sendZero();
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Send a buffer over RF
* \param data Data to send
* \param size size of data to send
*/
void sendData(byte *data, byte size)
{
for(byte i = 0; i < size; ++i)
{
sendQuarterLSB(data[i]);
sendQuarterMSB(data[i]);
}
}
/**
* \brief Send an Oregon message
* \param data The Oregon message
*/
void sendOregon(byte *data, byte size)
{
sendPreamble();
//sendSync();
sendData(data, size);
sendPostamble();
}
/**
* \brief Send preamble
* \details The preamble consists of 16 "1" bits
*/
inline void sendPreamble(void)
{
byte PREAMBLE[]={0xFF,0xFF};
sendData(PREAMBLE, 2);
}
/**
* \brief Send postamble
* \details The postamble consists of 8 "0" bits
*/
inline void sendPostamble(void)
{
#ifdef THN132N
sendQuarterLSB(0x00);
#else
byte POSTAMBLE[]={0x00};
sendData(POSTAMBLE, 1);
#endif
}
/**
* \brief Send sync nibble
* \details The sync is 0xA. It is not use in this version since the sync nibble
* \ is include in the Oregon message to send.
*/
inline void sendSync(void)
{
sendQuarterLSB(0xA);
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Set the sensor type
* \param data Oregon message
* \param type Sensor type
*/
inline void setType(byte *data, byte* type)
{
data[0] = type[0];
data[1] = type[1];
}
/**
* \brief Set the sensor channel
* \param data Oregon message
* \param channel Sensor channel (0x10, 0x20, 0x30)
*/
inline void setChannel(byte *data, byte channel)
{
data[2] = channel;
}
/**
* \brief Set the sensor ID
* \param data Oregon message
* \param ID Sensor unique ID
*/
inline void setId(byte *data, byte ID)
{
data[3] = ID;
}
/**
* \brief Set the sensor battery level
* \param data Oregon message
* \param level Battery level (0 = low, 1 = high)
*/
void setBatteryLevel(byte *data, byte level)
{
if(!level) data[4] = 0x0C;
else data[4] = 0x00;
}
/**
* \brief Set the sensor temperature
* \param data Oregon message
* \param temp the temperature
*/
void setTemperature(byte *data, float temp)
{
// Set temperature sign
if(temp < 0)
{
data[6] = 0x08;
temp *= -1;
}
else
{
data[6] = 0x00;
}
// Determine decimal and float part
int tempInt = (int)temp;
int td = (int)(tempInt / 10);
int tf = (int)round((float)((float)tempInt/10 - (float)td) * 10);
int tempFloat = (int)round((float)(temp - (float)tempInt) * 10);
// Set temperature decimal part
data[5] = (td << 4);
data[5] |= tf;
// Set temperature float part
data[4] |= (tempFloat << 4);
}
/**
* \brief Set the sensor humidity
* \param data Oregon message
* \param hum the humidity
*/
void setHumidity(byte* data, byte hum)
{
data[7] = (hum/10);
data[6] |= (hum - data[7]*10) << 4;
}
/**
* \brief Sum data for checksum
* \param count number of bit to sum
* \param data Oregon message
*/
int Sum(byte count, const byte* data)
{
int s = 0;
for(byte i = 0; i<count;i++)
{
s += (data[i]&0xF0) >> 4;
s += (data[i]&0xF);
}
if(int(count) != count)
s += (data[count]&0xF0) >> 4;
return s;
}
/**
* \brief Calculate checksum
* \param data Oregon message
*/
void calculateAndSetChecksum(byte* data)
{
#ifdef THN132N
int s = ((Sum(6, data) + (data[6]&0xF) - 0xa) & 0xff);
data[6] |= (s&0x0F) << 4; data[7] = (s&0xF0) >> 4;
#else
data[8] = ((Sum(8, data) - 0xa) & 0xFF);
#endif
}
/******************************************************************/
void setup()
{
setup_watchdog(9);
//pinMode(PB3, OUTPUT);
//digitalWrite(PB3,HIGH);delay(500);
//digitalWrite(PB3,LOW);delay(500);
//digitalWrite(PB3,HIGH);
pinMode(TX_PIN, OUTPUT);
pinMode(PB4, OUTPUT); //tx
Serial.begin(9600);
Serial.println("\n[Oregon V2.1 encoder]");
SEND_LOW();
#ifdef THN132N
// Create the Oregon message for a temperature only sensor (TNHN132N)
byte ID[] = {0xEA,0x4C};
#else
// Create the Oregon message for a temperature/humidity sensor (THGR2228N)
byte ID[] = {0x1A,0x2D};
#endif
setType(OregonMessageBuffer, ID);
setChannel(OregonMessageBuffer, 0x20);
setId(OregonMessageBuffer, 0xEE);
}
// set system into the sleep state
// system wakes up when wtchdog is timed out
void system_sleep() {
cbi(ADCSRA,ADEN); // switch Analog to Digitalconverter OFF
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
sleep_enable();
sleep_mode(); // System sleeps here
sleep_disable(); // System continues execution here when watchdog timed out
sbi(ADCSRA,ADEN); // switch Analog to Digitalconverter ON
}
// 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms
// 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
void setup_watchdog(int ii) {
byte bb;
int ww;
if (ii > 9 ) ii=9;
bb=ii & 7;
if (ii > 7) bb|= (1<<5);
bb|= (1<<WDCE);
ww=bb;
MCUSR &= ~(1<<WDRF);
// start timed sequence
WDTCR |= (1<<WDCE) | (1<<WDE);
// set new watchdog timeout value
WDTCR = bb;
WDTCR |= _BV(WDIE);
}
// Watchdog Interrupt Service / is executed when watchdog timed out
ISR(WDT_vect) {
f_wdt=1; // set global flag
}
void loop()
{
int chk = DHT11.read(DHT11PIN);
switch (chk)
{
case DHTLIB_OK:
Serial.println("OK");
break;
case DHTLIB_ERROR_CHECKSUM:
Serial.println("Checksum error");
break;
case DHTLIB_ERROR_TIMEOUT:
Serial.println("Time out error");
break;
default:
Serial.println("Unknown error");
break;
}
Serial.print("Temperature : ");Serial.print(DHT11.temperature);Serial.write(176); // caractère °
Serial.write('C'); Serial.println();
Serial.print("Humidity : ");Serial.print(DHT11.humidity);
Serial.write('%'); Serial.println();
// (ie: 1wire DS18B20 for température, ...)
setBatteryLevel(OregonMessageBuffer, 0); // 0 : low, 1 : high
setTemperature(OregonMessageBuffer, DHT11.temperature);
#ifndef THN132N
// Set Humidity
setHumidity(OregonMessageBuffer, DHT11.humidity);
#endif
// Calculate the checksum
calculateAndSetChecksum(OregonMessageBuffer);
// Show the Oregon Message
for (byte i = 0; i < sizeof(OregonMessageBuffer); ++i) {
//Serial.print(OregonMessageBuffer[i] >> 4, HEX);
//Serial.print(OregonMessageBuffer[i] & 0x0F, HEX);
}
// Send the Message over RF
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
// Send a "pause"
SEND_LOW();
delayMicroseconds(TWOTIME*8);
// Send a copie of the first message. The v2.1 protocol send the
// message two time
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
// Wait for 30 seconds before send a new message
SEND_LOW();
//
//9 secs * 6 = 54 secs
system_sleep();
system_sleep();
system_sleep();
system_sleep();
system_sleep();
system_sleep();
//
//delay(30000);
}

View File

@@ -0,0 +1,94 @@
/************************************************************
Horloge Arduino
Horloge simple avec un Arduino, un module breakout
RTC DS1307 et un afficheur LCD.
Branchements du breakout RTC DS1307:
Gnd --> GND
Vcc --> 5 V
Sda --> analog pin A4
Scl --> analog pin A5
***************************************************/
#include <Wire.h>
#include <RTClib.h>
RTC_DS1307 RTC;
void setup() {
Wire.begin();
Serial.begin(9600);
RTC.begin();
delay(1000);
RTC.adjust(DateTime("Dec 5 2012","12:00:00"));
// RTC.adjust(DateTime(2017, 2, 12, 14, 50, 0));
}
void loop() {
DateTime now = RTC.now();
Serial.println(now.month());
switch (now.month()) {
case 1:
Serial.println("janvier");
break;
case 2:
Serial.println("fevrier");
break;
case 3:
Serial.println("mars");
break;
case 4:
Serial.println("avril");
break;
case 5:
Serial.println("mai");
break;
case 6:
Serial.println("juin");
break;
case 7:
Serial.println("juillet");
break;
case 8:
Serial.println("aout");
break;
case 9:
Serial.println("septembre");
break;
case 10:
Serial.println("octobre");
break;
case 11:
Serial.println("novembre");
break;
case 12:
Serial.println("decembre");
break;
}
Serial.println(" ");
Serial.println(now.year());
Serial.print(now.day(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.year(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
delay(3000);
}

108
ATMEGA_TIMER_1/ATMEGA_TIMER_1.ino Executable file
View File

@@ -0,0 +1,108 @@
/*
DS1302 RTC module test by Tuxun
-CE/RST RTC pin D3(3)
-IO/DAT RTC pin D4(4)
-CLK RTC pin D5(5)
Under PUBLIC DOMAIN!
*/
//RTC part
//time from http://www.pjrc.com/teensy/arduino_libraries/Time.zip
#include <Time.h>
//DS1302 from http://playground.arduino.cc/uploads/Main/DS1302RTC.zip
#include <DS1302RTC.h>
// Set RTC pins: CE, IO,CLK
DS1302RTC RTC(3, 4, 5);
// Optional connection for RTC module: -1 to disable
#define DS1302_GND_PIN -1
#define DS1302_VCC_PIN -1
void setup()
{
//initial welcome :)
Serial.begin(9600);
Serial.println("DS1302 TEST PROGRAM");
Serial.println();
// Activate RTC module
digitalWrite(DS1302_GND_PIN, LOW);
pinMode(DS1302_GND_PIN, OUTPUT);
digitalWrite(DS1302_VCC_PIN, HIGH);
pinMode(DS1302_VCC_PIN, OUTPUT);
Serial.println("RTC module activated");
Serial.println();
delay(500);
//check that it is activated
if (RTC.haltRTC()) {
Serial.println("The DS1302 is stopped. Please run the SetTime");
Serial.println("example to initialize the time and begin running.");
Serial.println();
}
if (!RTC.writeEN()) {
Serial.println("The DS1302 is write protected. This normal.");
Serial.println();
}
delay(5000);
}
void loop()
{
Serial.println("\n");
//DS1302 timestamp structure
tmElements_t tm;
//Serial.print("UNIX Time: ");
//Serial.print(RTC.get());
if (! RTC.read(tm)) {
Serial.print(" Time = ");
print2digits(tm.Hour);
Serial.write(':');
print2digits(tm.Minute);
Serial.write(':');
print2digits(tm.Second);
Serial.print(", Date (D/M/Y) = ");
Serial.print(tm.Day);
Serial.write('/');
Serial.print(tm.Month);
Serial.write('/');
Serial.print(tmYearToCalendar(tm.Year));
Serial.print(", DoW = ");
Serial.print(tm.Wday);
Serial.println();
} else {
Serial.println("DS1302 read error! Please check the circuitry.");
Serial.println();
delay(9000);
}
// Wait one second before repeating :)
delay (1000);
}
void print2digits(int number) {
if (number >= 0 && number < 10)
Serial.write('0');
Serial.print(number);
}

View File

@@ -0,0 +1,93 @@
// Program: Date and time with RTC DS1302 module
// Amendment and adaptation: Arduino and Cia
//
// Based on the original program Krodal and virtuabotixRTC library
// Load the virtuabotixRTC library
#include "virtuabotixRTC.h"
// Determine the pins connected to the module
// myRTC (clock, data, RST)
virtuabotixRTC myRTC (6, 7, 8);
void setup ()
{
Serial.begin
(9600); // date and time of initial Information
// After to set the entire information, comment the following line
// (seconds, minutes, hours, day of week, day of month, month, year)
myRTC.setDS1302Time (0, 18, 23, 6, 31, 7, 2021);
}
void loop ()
{
// Reads the information from the CI
myRTC.updateTime ();
// Print the details in serial monitor
Serial.print
("Data "); // Call the routine that prints the day of the week
imprime_dia_da_semana (myRTC.dayofweek);
Serial.print (", ");
Serial.print (myRTC.dayofmonth);
Serial.print ("/");
Serial.print (myRTC.month);
Serial.print ("/");
Serial.print (myRTC.year);
Serial.print ("");
Serial.print
(" Time "); // Adds a 0 if the time value is <10
if (myRTC.hours <10)
{
Serial.print ("0");
}
Serial.print (myRTC.hours);
Serial.print
(":"); // Adds a 0 if the value of the minutes is <10
if (myRTC.minutes <10)
{
Serial.print ("0");
}
Serial.print (myRTC.minutes);
Serial.print
(":"); // Adds a 0 if the value of the latter is <10
if (myRTC.seconds <10)
{
Serial.print ("0");
}
Serial.println (myRTC.seconds);
delay (1000);
}
void imprime_dia_da_semana (int day)
{
switch (day)
{
case 1:
Serial.print
("Sunday");
break; case 2:
Serial.print
("Second");
break; case 3:
Serial.print
("Terca");
break; case 4:
Serial.print
("Wednesday");
break; case 5:
Serial.print
("Quinta");
break; case 6:
Serial.print
("Friday");
break; case 7:
Serial.print
("Saturday"); break;
}
}

View File

@@ -0,0 +1,359 @@
// Program: Date and time with RTC DS1302 module
// Amendment and adaptation: Arduino and Cia
//
// Based on the original program Krodal and virtuabotixRTC library
#include <EtherCard.h>
#include <Client.h>
#include <Servo.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
//DallasTemperature sensors(&oneWire);
Servo monServo;
#define STATIC 0 // set to 1 to disable DHCP (adjust myip/gwip values below)
#if STATIC
// ethernet interface ip address
static byte myip[] = { 192,168,0,22 };
// gateway ip address
static byte gwip[] = { 192,168,0,1 };
#endif
// ethernet mac address - must be unique on your network
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
byte Ethernet::buffer[500]; //??????
BufferFiller bfill; //???????
const int onOffPin = 7;
const int servo = 9;
// Load the virtuabotixRTC library
#include <virtuabotixRTC.h>
// Determine the pins connected to the module
// myRTC (clock, data, RST)
virtuabotixRTC myRTC (4, 5, 6);
void setup ()
{
Serial.begin(9600); // date and time of initial Information
// After to set the entire information, comment the following line
// (seconds, minutes, hours, day of week, day of month, month, year)
//myRTC.setDS1302Time (30, 56, 12, 7, 25, 6, 2016);
Serial.println("\n[backSoon]");
pinMode(onOffPin, OUTPUT);
if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
Serial.println( "Failed to access Ethernet controller");
#if STATIC
ether.staticSetup(myip, gwip);
#else
if (!ether.dhcpSetup())
Serial.println("DHCP failed");
#endif
ether.printIp("IP: ", ether.myip);
ether.printIp("GW: ", ether.gwip);
ether.printIp("DNS: ", ether.dnsip);
// Servo moteur
// Attacher la pin 9 à l'objet servo.
// ATTN: le code initialise l'angle à 90 degrés par défaut.
monServo.attach(servo); // 9
// remettre l'angle à 0 degrés
monServo.write( 0 );
// Start up the library Dallas one wire
// sensors.begin();
}
void imprime_dia_da_semana (int day)
{
switch (day)
{
case 1:
Serial.print("Dimanche");
break;
case 2:
Serial.print("Lundi");
break;
case 3:
Serial.print("Mardi");
break;
case 4:
Serial.print("Mercredi");
break;
case 5:
Serial.print("Jeudi");
break;
case 6:
Serial.print("Vendredi");
break;
case 7:
Serial.print("Samedi");
break;
}
}
void homePage() {
// long t = millis() / 1000;
// word h = t / 3600;
// byte m = (t / 60) % 60;
// byte s = t % 60;
// String html = "<img src=\"http://www.ac-grenoble.fr/ien.vienne1-2/spip/IMG/bmp_Image004.bmp\">";
//
// int len = html.length() + 1;
// char tmp[len];
// //Serial.println(tmp);
// html.toCharArray(tmp, len);bfill = ether.tcpOffset();
bfill.emit_p(PSTR( //???????
"HTTP/1.0 200 OK\r\n"
"Content-Type: text/html\r\n"
"Pragma: no-cache\r\n"
"\r\n"
"<meta></meta>" // http-equiv='refresh' content='1'/>"
"<html><head><title>RBBB server</title>"
//"<link rel=""stylesheet"" type=""text/css"" href=""css.css"">"
"</head>"
//"<body background=""http://www.resimsi.com/wp-content/uploads/2015/09/html-background.jpg"">")); //???????
"<body>"));
delay(1);
bfill.emit_p(PSTR(
"<form method=""get"" action=""/on""><button type=""submit"">$F</button></FORM><form method=""get"" action=""/off""><button type=""submit"">$F</button></FORM>"),
PSTR("ON"), PSTR("OFF"));
// bfill.emit_p(PSTR("<a href=""http://google.com"" class=""button"">Go to Google</a>"));
//bfill.emit_p(PSTR("<P>$F</P>"),23); //sensors.getTempCByIndex(0));
// bfill.emit_p(PSTR("<TABLE>"));
// delay(1);
//
// delay(1);
// //bfill = ether.tcpOffset();
// for (int i = 0; i < 3; i++) {
//// // word pin = 0;
// bfill.emit_p(PSTR("<TR><TD>$F</TD><TD>$F</TD><TD>$F</TD></TR>"),
// PSTR("TOTO"), PSTR("X"), PSTR("O"));
// delay(2);
////
// }
// bfill.emit_p(PSTR("</TABLE></body></html>"));
bfill.emit_p(PSTR("</body></html>"));
delay(1);
}
const char okHeader[] PROGMEM =
"HTTP/1.0 200 OK\r\n"
"Content-Type: text/html\r\n"
"Pragma: no-cache\r\n";
const char okCSS[] PROGMEM =
"HTTP/1.0 200 OK\r\n"
"Content-Type: text/css\r\n"
"Pragma: no-cache\r\n";
static void configPage(const char* data) {
bfill.emit_p(PSTR("$F\r\n"
"<h3>Send a wireless data packet</h3>"
"<form>"
"<p>"
"Data bytes <input type=text name=b size=50> (decimal)<br>"
"Destination node <input type=text name=d size=3> "
"(1..31, or 0 to broadcast)<br>"
"</p>"
"<input type=submit value=Send>"
"</form>"), okHeader);
}
static void cssPage() {
const char css[] = "a.button {"
"-webkit-appearance: button;"
"-moz-appearance: button;"
"appearance: button;"
" text-decoration: none;"
"color: initial;}";
bfill.emit_p(PSTR("$F\r\n$F"), okCSS, css);
}
static void sendPage(const char* data) {
// // pick up submitted data, if present
// const char* p = strstr(data, "b=");
// byte d = getIntArg(data, "d");
// if (data[6] == '?' && p != 0 && 0 <= d && d <= 31) {
// // prepare to send data as soon as possible in loop()
// outDest = d & RF12_HDR_MASK ? RF12_HDR_DST | d : 0;
// outCount = 0;
// // convert the input string to a number of decimal data bytes in outBuf
// ++p;
// while (*p != 0 && *p != '&') {
// outBuf[outCount] = 0;
// while ('0' <= *++p && *p <= '9')
// outBuf[outCount] = 10 * outBuf[outCount] + (*p - '0');
// ++outCount;
// }
//#if SERIAL
// Serial.print("Send to ");
// Serial.print(outDest, DEC);
// Serial.print(':');
// for (byte i = 0; i < outCount; ++i) {
// Serial.print(' ');
// Serial.print(outBuf[i], DEC);
// }
// Serial.println();
//#endif
// // redirect to home page
// bfill.emit_p(PSTR(
// "HTTP/1.0 302 found\r\n"
// "Location: /\r\n"
// "\r\n"));
// return;
// }
// else show a send form
bfill.emit_p(PSTR("$F\r\n"
"<h3>Send a wireless data packet</h3>"
"<form>"
"<p>"
"Data bytes <input type=text name=b size=50> (decimal)<br>"
"Destination node <input type=text name=d size=3> "
"(1..31, or 0 to broadcast)<br>"
"</p>"
"<input type=submit value=Send>"
"</form>"), okHeader);
}
void getTime() {
// Reads the information from the CI
myRTC.updateTime ();
// Print the details in serial monitor
Serial.print ("Data "); // Call the routine that prints the day of the week
imprime_dia_da_semana (myRTC.dayofweek);
Serial.print (", ");
Serial.print (myRTC.dayofmonth);
Serial.print ("/");
Serial.print (myRTC.month);
Serial.print ("/");
Serial.print (myRTC.year);
Serial.print ("");
Serial.print
(" Time "); // Adds a 0 if the time value is <10
if (myRTC.hours <10)
{
Serial.print ("0");
}
Serial.print (myRTC.hours);
Serial.print
(":"); // Adds a 0 if the value of the minutes is <10
if (myRTC.minutes <10)
{
Serial.print ("0");
}
Serial.print (myRTC.minutes);
Serial.print
(":"); // Adds a 0 if the value of the latter is <10
if (myRTC.seconds <10)
{
Serial.print ("0");
}
Serial.println (myRTC.seconds);
}
void loop ()
{
word len = ether.packetReceive();
word pos = ether.packetLoop(len);
// check if valid tcp data is received
if (pos) {
delay(1); // necessary for my system
bfill = ether.tcpOffset();
char* data = (char *) Ethernet::buffer + pos;
Serial.println(data);
// receive buf hasn't been clobbered by reply yet
if (strncmp("GET / ", data, 6) == 0) {
Serial.println("HomePage");
homePage();
} else if (strncmp("GET /css.css", data, 12) == 0) {
Serial.println("CSS");
cssPage();
} else if (strncmp("GET /on", data, 7) == 0) {
getTime();
Serial.println("ON");
digitalWrite(onOffPin, LOW);
homePage();
// // Servo
// // Passer de 0 a 180° par angle de 10 degré
// for( int iAngle=0; iAngle<= 360; iAngle+=10 )
// {
// monServo.write(iAngle);
// delay( 250 );
// }
} else if (strncmp("GET /off", data, 8) == 0) {
getTime();
Serial.println("OFF");
digitalWrite(onOffPin, HIGH);
homePage();
// // Angle décroissant progressif
// for( int iAngle = 360; iAngle>=0; iAngle-- )
// {
// monServo.write( iAngle );
// delay( 10 );
// }
} else if (strncmp("GET /c", data, 6) == 0) {
Serial.println("Config");
configPage(data);
} else if (strncmp("GET /d", data, 6) == 0) {
Serial.println("Data");
sendPage(data);
} else {
bfill.emit_p(PSTR(
"HTTP/1.0 401 Unauthorized\r\n"
"Content-Type: text/html\r\n"
"\r\n"
"<h1>401 Unauthorized</h1>"));
}
ether.httpServerReply(bfill.position()); // send web page data
}
// delay (1000);
}

View File

@@ -0,0 +1,76 @@
/*
*
* Udemy.com
* Building an Arduino DC Voltmeter
*
*/
float vPow = 4.7;
float r1 = 68000;
float r2 = 680000;
int speed = 120;
void setup() {
pinMode(3, OUTPUT);
analogWrite(3, speed);
Serial.begin(9600);
// Send ANSI terminal codes
Serial.print("\x1B");
Serial.print("[2J");
Serial.print("\x1B");
Serial.println("[H");
// End ANSI terminal codes
Serial.println("--------------------");
Serial.println("DC VOLTMETER");
Serial.print("Maximum Voltage: ");
Serial.print((int)(vPow / (r2 / (r1 + r2))));
Serial.println("V");
Serial.println("--------------------");
Serial.println("");
delay(2000);
}
void loop() {
float v = (analogRead(A0)* vPow) / 1024.0;
float v2 = v / (r2 / (r1 + r2));
// Send ANSI terminal codes
//Serial.print("\x1B");
//Serial.print("[1A ");
// End ANSI terminal codes
Serial.print(analogRead(A0));
Serial.print(" ");
Serial.println(v2);
// First we check to see if incoming data is available:
while (Serial.available() > 0)
{
// If it is, we'll use parseInt() to pull out any numbers:
speed = Serial.parseInt();
// Because analogWrite() only works with numbers from
// 0 to 255, we'll be sure the input is in that range:
speed = constrain(speed, 0, 255);
// We'll print out a message to let you know that the
// number was received:
Serial.print("Setting speed to ");
Serial.println(speed);
// And finally, we'll set the speed of the motor!
analogWrite(3, speed);
}
}

View File

@@ -0,0 +1,181 @@
#include <SoftwareSerial.h>
SoftwareSerial esp8266(10,11);
String ssid = "Livebox-37cc"; // Garder les guillements
String key = "8A6060920A8A86896F770F2C47"; // Garder les guillements
boolean done = false;
/****************************************************************/
/* INIT */
/****************************************************************/
void setup() {
// put your setup code here, to run once:
//esp8266.begin(115200);
delay(500);
esp8266.println("AT+RST");
/**
* Initialisation
*/
delay(1000);
esp8266.println("AT");
done = esp8266.find("OK");
if(!done){
delay(1000);
done = esp8266.find("OK");
}
// /**
// * Se mettre en mode DHCP
// */
// esp8266.println("AT+CWDHCP=1,1");
// done = esp8266.find("OK");
// if(!done){
// delay(1000);
// done = esp8266.find("OK");
// }
/**
* Se mettre en mode CLIENT
*/
esp8266.println("AT+CWMODE=1");
done = esp8266.find("OK");
if(!done){
delay(1000);
done = esp8266.find("OK");
}
/**
* Affecter son adresse IP manuellement
*/
// delay(1000);
// esp8266.println("AT+CIPSTA_DEF=\"192.168.0.200\",\"192.168.0.1\",\"255.255.255.0\"");
// done = esp8266.find("OK");
// while(!done){
// delay(1000);
// done = esp8266.find("OK");
// }
/**
* Rechercher les points d'accès WIFI
*/
/*
delay(1000);
esp8266.println("AT+CWLAP");
done = esp8266.find("OK");
while(!done){
delay(1000);
done = esp8266.find("OK");
delay(3000);
break;
}*/
/**
* Se connecter au point d'accès Wifi défini dans la variable "ssid"
*/
esp8266.println("AT+CWJAP=\""+ssid+"\",\""+key+"\"");
done = esp8266.find("OK");
while(!done){
delay(1000);
done = esp8266.find("OK");
}
/**
* Se mettre en mode connexions multiples
*/
esp8266.println("AT+CIPMUX=1");
done = esp8266.find("OK");
if(!done){
delay(1000);
done = esp8266.find("OK");
}
/**
* afficher son adresse IP
*/
esp8266.println("AT+CIFSR");
done = esp8266.find("STAIP");
if(!done){
delay(1000);
done = esp8266.find("OK");
}
/**
* faire un ping sur un server
*/
/*
delay(1000);
esp8266.println("AT+PING=\"192.168.1.100\"");
done = false;
if(!done){
delay(1000);
done = esp8266.find("OK");
}*/
}
void loop() {
int maxLoops = 5;
/**
* Faire un HTTP GET
*/
String cmd = "AT+CIPSTART=4,\"TCP\",\"192.168.1.10\",8080";
esp8266.println(cmd);
delay(500);
done = esp8266.find("OK");
int currentLoop = 0;
while(!done){
delay(500);
done = esp8266.find("OK");
if(currentLoop >= maxLoops){
break;
}
currentLoop++;
}
String url = "/json.htm?type=command&param=switchlight&idx=99&switchcmd=On";
String cmdGET = "GET " + url + " HTTP/1.1\r\n"+
"Host: 192.168.1.10\r\nUser-Agent: ESP8266_HTTP_Client\r\nConnection: close\r\n\r\n";
esp8266.print("AT+CIPSEND=4,");
esp8266.println(cmdGET.length());
delay(1000);
done = esp8266.find(">");
currentLoop = 0;
while(!done){
delay(500);
done = esp8266.find(">");
if(currentLoop >= maxLoops){
break;
}
currentLoop++;
}
esp8266.println(cmdGET+"\r\n\r\n");
delay(1000);
esp8266.println("AT+CIPSTATUS");
delay(1000);
// Close all connections
esp8266.println("AT+CIPCLOSE=5");
delay(1000);
// restart from zero
esp8266.println("AT");
// 4 secondes déjà passées
delay(20000);
}

View File

@@ -0,0 +1,313 @@
#include <SoftwareSerial.h>
//#include <Narcoleptic.h>
SoftwareSerial ESP8266(10, 11);
//#include <Adafruit_BMP085.h>
//#include <Wire.h>
String NomduReseauWifi = "Livebox-37cc"; // Garder les guillements
String MotDePasse = "8A6060920A8A86896F770F2C47"; // Garder les guillements
// Time to sleep (in seconds):
const int sleepTimeS = 60;
#define SEND_MESSAGE_DELAY 30000 // Ne pas dépasser 32000 !! Delay in ms between each value's extraction
#define SEND_433_PAUSE 160 // 16 multiple
//#define DEBUG true
// 163 = Radiateur bureau
#define idRadiateurInDomoticz 290
// Radiateur Manon 217
// Radiateur Théo 219
// Radaiteur chambre 218
// Radiateur salon 207 208 209
// EthernetServer server(80);
boolean done = false;
/****************************************************************/
/* INIT */
/****************************************************************/
int baud = 9600;
void setup()
{
#ifdef DEBUG
Serial.begin(baud);
#endif
setupEsp8266();
}
void setupEsp8266() {
ESP8266.begin(115200);
ESP8266.println("AT+RST");
recoitDuESP8266(1000);
ESP8266.println("AT+CIOBAUD=" + baud);
recoitDuESP8266(1000);
ESP8266.begin(baud);
initESP8266();
}
void debugPrint(String m) {
#ifdef DEBUG
Serial.print(m);
#endif
}
void debugPrintln(String m) {
#ifdef DEBUG
Serial.println(m);
#endif
}
/****************************************************************/
/* BOUCLE INFINIE */
/****************************************************************/
void loop() {
// connection();
// envoie("/json.htm?type=devices&rid=" + String(idRadiateurInDomoticz));
//
String s = "/json.htm?type=devices&rid=";
envoie(s + String(2));
envoie(s + String(257));
envoie(s + String(258));
// envoie("/json.htm?type=command&param=udevice&idx=158&svalue=255");
// deconnexion();
debugPrintln("Sleep");
delay(1000);
// 0 minute
//Narcoleptic.delay(SEND_MESSAGE_DELAY);
// Narcoleptic.delay(SEND_MESSAGE_DELAY);
// // 1
// Narcoleptic.delay(SEND_MESSAGE_DELAY);
// Narcoleptic.delay(SEND_MESSAGE_DELAY);
// // 2
// Narcoleptic.delay(SEND_MESSAGE_DELAY);
// Narcoleptic.delay(SEND_MESSAGE_DELAY);
// // 3
// Narcoleptic.delay(SEND_MESSAGE_DELAY);
// Narcoleptic.delay(SEND_MESSAGE_DELAY);
// // 4
// Narcoleptic.delay(SEND_MESSAGE_DELAY);
// Narcoleptic.delay(SEND_MESSAGE_DELAY);
// 5
delay(10000);
setupEsp8266();
}
void connection() {
ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.0.10\",8080");
recoitDuESP8266(2000);
}
void envoie(String url) {
connection();
int maxLoops = 10;
int currentLoop = 0;
//String url = "/json.htm?type=devices&rid=" + String(idRadiateurInDomoticz);
String cmdGET = "GET " + url + " HTTP/1.1\r\n"
+ "Host: 192.168.0.10\r\nUser-Agent: ESP8266_HTTP_Client\r\nConnection: close\r\n\r\n";
//debugPrintln("***GET url = " + url);
// demande d'envoi
ESP8266.print("AT+CIPSEND=4,");
ESP8266.println(cmdGET.length());
delay(500);
done = ESP8266.find(">");
currentLoop = 0;
while(!done){
delay(500);
done = ESP8266.find(">");
if(currentLoop >= maxLoops){
//debugPrintln(" Attente dépassée");
break;
}
currentLoop++;
//debugPrint(".");
}
// requete
ESP8266.println(cmdGET+"\r\n\r\n");
String ret = recoitDuESP8266WithJson(10000, "status");
debugPrintln("** ret=" + ret);
if (ret.equalsIgnoreCase("On")) {
digitalWrite(3, HIGH);
digitalWrite(13, HIGH);
} else if (ret.equalsIgnoreCase("Off")) {
digitalWrite(3, LOW);
digitalWrite(13, LOW);
}
deconnexion();
}
void deconnexion() {
////////////////////////////////
// sendToDomoticz("288", "15", "225");
///////////////////////////////
ESP8266.println("AT+CIPSTATUS");
recoitDuESP8266(2000);
// Close all connections
ESP8266.println("AT+CIPCLOSE=5");
recoitDuESP8266(2000);
// restart from zero
ESP8266.println("AT");
recoitDuESP8266(2000);
// 4 secondes déjà passées
delay(200);
}
//void sendToDomoticz(String id, String nvalue, String svalue) {
//
// debugPrintln("**Send To Domoticz " + id + " " + nvalue + " " + svalue);
//
// int maxLoops = 5;
// int currentLoop = 0;
// String url = "/json.htm?type=command&param=udevice&idx=" + id + "&nvalue=" + nvalue + "&svalue=" + svalue; // + String(val);
// //String url = "/json.htm?type=command&param=udevice&idx=288&nvalue=10&svalue=220.5"; // + String(val);
// //String url = "/json.htm?type=command&param=getSunRiseSet";
// String cmdGET = "GET " + url + " HTTP/1.1\r\n"+
// "Host: 192.168.0.10\r\nUser-Agent: ESP8266_HTTP_Client\r\nConnection: close\r\n\r\n";
//
//
// ESP8266.print("AT+CIPSEND=4,");
// ESP8266.println(cmdGET.length());
//
// done = ESP8266.find(">");
// currentLoop = 0;
// while(!done){
// delay(500);
// done = ESP8266.find(">");
// if(currentLoop >= maxLoops){
// break;
// }
// currentLoop++;
// }
// ESP8266.println(cmdGET+"\r\n\r\n");
// recoitDuESP8266(5000);
//
//}
/****************************************************************/
/* Fonction qui initialise l'ESP8266 */
/****************************************************************/
void initESP8266()
{
pinMode(13, OUTPUT);
pinMode(3, OUTPUT);
digitalWrite(3, LOW);
digitalWrite(13, LOW);
//debugPrintln("**************** DEBUT DE L'INITIALISATION ***************");
ESP8266.println("AT");
recoitDuESP8266(1000);
ESP8266.println("AT+CWMODE=3");
recoitDuESP8266(1000);
ESP8266.println("AT+CWJAP=\""+ NomduReseauWifi + "\",\"" + MotDePasse +"\"");
recoitDuESP8266(10000);
ESP8266.println("AT+CIFSR");
recoitDuESP8266(1000);
ESP8266.println("AT+CIPMUX=1");
recoitDuESP8266(1000);
ESP8266.println("AT+CIPSERVER=1,80");
recoitDuESP8266(1000);
//debugPrintln("***************** INITIALISATION TERMINEE ****************");
}
/****************************************************************/
/*Fonction qui lit et affiche les messages envoyés par l'ESP8266*/
/****************************************************************/
String recoitDuESP8266(const int timeout)
{
String reponse = "";
long int time = millis();
while( (time+timeout) > millis())
{
while(ESP8266.available())
{
//reponse = "";
char c = ESP8266.read();
reponse+=c;
if (c == 13 || reponse.length() > 100) {
//debugPrint(reponse);
reponse = "";
}
}
}
//debugPrint(reponse);
return reponse;
}
/****************************************************************/
/*Fonction qui lit et affiche les messages envoyés par l'ESP8266*/
/****************************************************************/
String recoitDuESP8266WithJson(const int timeout, String jsonId)
{
String ret = "";
String reponse = "";
boolean found = false;
long int time = millis();
while( (time+timeout) > millis())
{
while(ESP8266.available())
{
//reponse = "";
char c = ESP8266.read();
reponse+=c;
//reponse.trim();
// if (reponse.equalsIgnoreCase(jsonId)) {
// debugPrintln("Trouve" + reponse + " " + jsonId);
// }
if (c == 10) {
reponse.trim();
// debugPrint(reponse);
int p = reponse.indexOf(':');
String id = reponse.substring(0,p);
String value = reponse.substring(p + 1, reponse.length() -1);
id.trim();
value.trim();
id.replace("\"", "");
value.replace("\"", "");
if (id.equalsIgnoreCase(jsonId) && !found) {
//debugPrintln("========> Trouve " + jsonId + " == " + value);
ret = value;
found = true;
} else {
//debugPrintln(id + " " + value);
}
reponse = "";
}
}
}
//debugPrintln(reponse);
return ret;
}

View File

@@ -0,0 +1,53 @@
/*
Software serial multple serial test
Receives from the hardware serial, sends to software serial.
Receives from software serial, sends to hardware serial.
The circuit:
* RX is digital pin 10 (connect to TX of other device)
* TX is digital pin 11 (connect to RX of other device)
Note:
Not all pins on the Mega and Mega 2560 support change interrupts,
so only the following can be used for RX:
10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69
Not all pins on the Leonardo and Micro support change interrupts,
so only the following can be used for RX:
8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).
created back in the mists of time
modified 25 May 2012
by Tom Igoe
based on Mikal Hart's example
This example code is in the public domain.
*/
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("Goodnight moon!");
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
mySerial.println("Hello, world?");
}
void loop() { // run over and over
if (mySerial.available()) {
Serial.write(mySerial.read());
}
if (Serial.available()) {
mySerial.write(Serial.read());
}
}

View File

@@ -0,0 +1,450 @@
/*
* connectingStuff, Oregon Scientific v2.1 Emitter
* http://connectingstuff.net/blog/encodage-protocoles-oregon-scientific-sur-arduino
* and
* http://blog.idleman.fr/raspberry-pi-18-construire-une-sonde-de-temperature-radio-pour-7e/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <OneWire.h>
#include <DallasTemperature.h>
#include <avr/sleep.h>
#include <avr/power.h> // Power management
#include <avr/wdt.h>
#define THN132N
const byte TEMPERATURE_1_PIN = 3; //A5;
const byte LUMINOSITE_PIN=A1;
const byte TRANSMITTER_PIN = 9;
const byte LED_PIN = 13;
//#define DEBUG TRUE
// On crée une instance de la classe oneWire pour communiquer avec le materiel on wire (dont le capteur ds18b20)
OneWire oneWire(TEMPERATURE_1_PIN);
//On passe la reference onewire à la classe DallasTemperature qui vas nous permettre de relever la temperature simplement
DallasTemperature sensors(&oneWire);
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
#define SEND_HIGH() digitalWrite(TRANSMITTER_PIN, HIGH)
#define SEND_LOW() digitalWrite(TRANSMITTER_PIN, LOW)
// Buffer for Oregon message
#ifdef THN132N
byte OregonMessageBuffer[8];
#else
byte OregonMessageBuffer[9];
#endif
/**
* \brief Send logical "0" over RF
* \details azero bit be represented by an off-to-on transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendZero(void)
{
SEND_HIGH();
delayMicroseconds(TIME);
SEND_LOW();
delayMicroseconds(TWOTIME);
SEND_HIGH();
delayMicroseconds(TIME);
}
/**
* \brief Send logical "1" over RF
* \details a one bit be represented by an on-to-off transition
* \ of the RF signal at the middle of a clock period.
* \ Remenber, the Oregon v2.1 protocol add an inverted bit first
*/
inline void sendOne(void)
{
SEND_LOW();
delayMicroseconds(TIME);
SEND_HIGH();
delayMicroseconds(TWOTIME);
SEND_LOW();
delayMicroseconds(TIME);
}
/**
* Send a bits quarter (4 bits = MSB from 8 bits value) over RF
*
* @param data Source data to process and sent
*/
/**
* \brief Send a bits quarter (4 bits = MSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterMSB(const byte data)
{
(bitRead(data, 4)) ? sendOne() : sendZero();
(bitRead(data, 5)) ? sendOne() : sendZero();
(bitRead(data, 6)) ? sendOne() : sendZero();
(bitRead(data, 7)) ? sendOne() : sendZero();
}
/**
* \brief Send a bits quarter (4 bits = LSB from 8 bits value) over RF
* \param data Data to send
*/
inline void sendQuarterLSB(const byte data)
{
(bitRead(data, 0)) ? sendOne() : sendZero();
(bitRead(data, 1)) ? sendOne() : sendZero();
(bitRead(data, 2)) ? sendOne() : sendZero();
(bitRead(data, 3)) ? sendOne() : sendZero();
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Send a buffer over RF
* \param data Data to send
* \param size size of data to send
*/
void sendData(byte *data, byte size)
{
for(byte i = 0; i < size; ++i)
{
sendQuarterLSB(data[i]);
sendQuarterMSB(data[i]);
}
}
/**
* \brief Send an Oregon message
* \param data The Oregon message
*/
void sendOregon(byte *data, byte size)
{
sendPreamble();
//sendSync();
sendData(data, size);
sendPostamble();
}
/**
* \brief Send preamble
* \details The preamble consists of 16 "1" bits
*/
inline void sendPreamble(void)
{
byte PREAMBLE[]={0xFF,0xFF};
sendData(PREAMBLE, 2);
}
/**
* \brief Send postamble
* \details The postamble consists of 8 "0" bits
*/
inline void sendPostamble(void)
{
#ifdef THN132N
sendQuarterLSB(0x00);
#else
byte POSTAMBLE[]={0x00};
sendData(POSTAMBLE, 1);
#endif
}
/**
* \brief Send sync nibble
* \details The sync is 0xA. It is not use in this version since the sync nibble
* \ is include in the Oregon message to send.
*/
inline void sendSync(void)
{
sendQuarterLSB(0xA);
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
/**
* \brief Set the sensor type
* \param data Oregon message
* \param type Sensor type
*/
inline void setType(byte *data, byte* type)
{
data[0] = type[0];
data[1] = type[1];
}
/**
* \brief Set the sensor channel
* \param data Oregon message
* \param channel Sensor channel (0x10, 0x20, 0x30)
*/
inline void setChannel(byte *data, byte channel)
{
data[2] = channel;
}
/**
* \brief Set the sensor ID
* \param data Oregon message
* \param ID Sensor unique ID
*/
inline void setId(byte *data, byte ID)
{
data[3] = ID;
}
/**
* \brief Set the sensor battery level
* \param data Oregon message
* \param level Battery level (0 = low, 1 = high)
*/
void setBatteryLevel(byte *data, byte level)
{
if(!level) data[4] = 0x0C;
else data[4] = 0x00;
}
/**
* \brief Set the sensor temperature
* \param data Oregon message
* \param temp the temperature
*/
void setTemperature(byte *data, float temp)
{
// Set temperature sign
if(temp < 0)
{
data[6] = 0x08;
temp *= -1;
}
else
{
data[6] = 0x00;
}
// Determine decimal and float part
int tempInt = (int)temp;
int td = (int)(tempInt / 10);
int tf = (int)round((float)((float)tempInt/10 - (float)td) * 10);
int tempFloat = (int)round((float)(temp - (float)tempInt) * 10);
// Set temperature decimal part
data[5] = (td << 4);
data[5] |= tf;
// Set temperature float part
data[4] |= (tempFloat << 4);
}
/**
* \brief Set the sensor humidity
* \param data Oregon message
* \param hum the humidity
*/
void setHumidity(byte* data, byte hum)
{
data[7] = (hum/10);
data[6] |= (hum - data[7]*10) << 4;
#ifdef DEBUG
Serial.print("Hum=" + hum);
#endif
}
/**
* \brief Sum data for checksum
* \param count number of bit to sum
* \param data Oregon message
*/
int Sum(byte count, const byte* data)
{
int s = 0;
for(byte i = 0; i<count;i++)
{
s += (data[i]&0xF0) >> 4;
s += (data[i]&0xF);
}
if(int(count) != count)
s += (data[count]&0xF0) >> 4;
return s;
}
/**
* \brief Calculate checksum
* \param data Oregon message
*/
void calculateAndSetChecksum(byte* data)
{
#ifdef THN132N
int s = ((Sum(6, data) + (data[6]&0xF) - 0xa) & 0xff);
data[6] |= (s&0x0F) << 4; data[7] = (s&0xF0) >> 4;
#else
data[8] = ((Sum(8, data) - 0xa) & 0xFF);
#endif
}
/******************************************************************/
/******************************************************************/
/******************************************************************/
void setup()
{
DDRB = 0b000001; // all but PB0 INPUT, want to use PB0 ...
PORTB = 0b000000; // all LOW
pinMode(TRANSMITTER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
#ifdef DEBUG
Serial.begin(115200);
Serial.println("\n[Oregon V2.1 encoder]");
#endif
SEND_LOW();
//On initialise le capteur de temperature
sensors.begin();
#ifdef THN132N
// Create the Oregon message for a temperature only sensor (TNHN132N)
byte ID[] = {0xEA,0x4C};
#ifdef DEBUG
Serial.println("Def THN132");
#endif
#else
// Create the Oregon message for a temperature/humidity sensor (THGR2228N)
byte ID[] = {0x1A,0x2D};
#ifdef DEBUG
Serial.println("UnDef THN132");
#endif
#endif
setType(OregonMessageBuffer, ID);
setChannel(OregonMessageBuffer, 0x20);
// ATMEGA 1 = BC
// TEST OREGON BB
// TEST Luminosite BD
setId(OregonMessageBuffer, 0xBC); // ID BB BC BD
delay(1000);
}
void loop()
{
digitalWrite(LED_PIN, HIGH);
digitalWrite(LED_PIN, LOW);
// if (currentVcc > 5000) {
// currentVcc = 5000;
// }
#ifdef DEBUG
Serial.println(currentVcc);
#endif
// Get Temperature, humidity and battery level from sensors
// (ie: 1wire DS18B20 for température, ...)
// if (currentVcc < 3000) {
// setBatteryLevel(OregonMessageBuffer, 0); // 0 : low, 1 : high
// } else {
// setBatteryLevel(OregonMessageBuffer, 1); // 0 : low, 1 : high
// }
setBatteryLevel(OregonMessageBuffer, 1);
// need addaptation here
// Ajout perso
//Lancement de la commande de récuperation de la temperature
sensors.requestTemperatures();
//Serial.println(sensors.getTempCByIndex(0));
//if (LUMINOSITE_PIN != 0) {
//setTemperature(OregonMessageBuffer,analogRead(LUMINOSITE_PIN));
//} else {
setTemperature(OregonMessageBuffer,sensors.getTempCByIndex(0));
//}
// setTemperature(OregonMessageBuffer, 11.2);
#ifndef THN132N
// Set Humidity
setHumidity(OregonMessageBuffer, 52);
#endif
// Calculate the checksum
calculateAndSetChecksum(OregonMessageBuffer);
// Show the Oregon Message
#ifdef DEBUG
for (byte i = 0; i < sizeof(OregonMessageBuffer); ++i) {
Serial.print(OregonMessageBuffer[i] >> 4, HEX);
Serial.print(OregonMessageBuffer[i] & 0x0F, HEX);
}
Serial.println("");
#endif
// Send the Message over RF
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
// Send a "pause"
SEND_LOW();
delayMicroseconds(TWOTIME*8);
// Send a copie of the first message. The v2.1 protocol send the
// message two time
sendOregon(OregonMessageBuffer, sizeof(OregonMessageBuffer));
delay(1000);
// Wait for 30 seconds before send a new message
SEND_LOW();
//delay(3000);
// disable ADC
//ADCSRA = 0;
// sleep for a total of 64 seconds (8 x 8)
for (int i = 0; i < 8; i++) {
sleepNow();
}
}
void sleepNow() {
{
// BODCR |= (1<<BODS)|(1<<BODSE); //Disable Brown Out Detector Control Register
ACSR |= (1<<ACD); //Analog comparator off
ACSR = ADMUX = ADCSRA = 0;
}
WDTCR |= (1<<WDP3) ; //Watchdog set for about 4 seconds
// Enable watchdog timer interrupts
WDTCR |= (1<<WDTIE);
sei(); // Enable global interrupts
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_mode();
sleep_disable();
}

View File

@@ -0,0 +1,227 @@
#include <avr/sleep.h>
#include <avr/power.h>
//#include <avr/interrupt.h>
//#include <avr/io.h>
#include <util/delay.h>
#define F_CPU 1200000UL
#define PIN_TX (1<<PB3) // PB3 pin, goes to transmitter data pin
#define nTransmitterPin 0
#define nProtocol 1
#define nPulseLength 1 // 270 //pulse lenght calibrate untill the "real"
//lenght are around 350
#define nRepeatTransmit 5 //retransmitts
// const int buttonPin = 0;
const int ledPin = 4; //1;
void setup() {
DDRB = 0b000001; // all but PB0 INPUT, want to use PB0 ...
PORTB = 0b000000; // all LOW
// pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
DDRB |= PIN_TX; // Set output direction on PIN_TX
}
void loop() {
//sleep(); // sleep function called here
digitalWrite(ledPin, HIGH);
delay(10);
digitalWrite(ledPin, LOW);
// delay(1000);
for (int i = 0; i < nRepeatTransmit; i++) {
send("1011101000110101");
delay(100);
}
// 4s * n
for (int i = 0; i < 3; i++) {
sleepNow();
}
}
void sleepNow() {
{
// BODCR |= (1<<BODS)|(1<<BODSE); //Disable Brown Out Detector Control Register
ACSR |= (1<<ACD); //Analog comparator off
ACSR = ADMUX = ADCSRA = 0;
}
WDTCR |= (1<<WDP3) ; //Watchdog set for about 4 seconds
// Enable watchdog timer interrupts
WDTCR |= (1<<WDTIE);
sei(); // Enable global interrupts
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_mode();
sleep_disable();
}
/* */
/**
* Sends a "0" Bit
* _
* Waveform Protocol 1: | |___
* _
* Waveform Protocol 2: | |__
*/
void send0() {
if (nProtocol == 1){
transmit(1,3);
}
else if (nProtocol == 2) {
transmit(1,2);
}
else if (nProtocol == 3) {
transmit(4,11);
}
}
/**
* Sends a "1" Bit
* ___
* Waveform Protocol 1: | |_
* __
* Waveform Protocol 2: | |_
*/
void send1() {
if (nProtocol == 1){
transmit(3,1);
}
else if (nProtocol == 2) {
transmit(2,1);
}
else if (nProtocol == 3) {
transmit(9,6);
}
}
/**
* Sends a Tri-State "0" Bit
* _ _
* Waveform: | |___| |___
*/
void sendT0() {
transmit(1,3);
transmit(1,3);
}
/**
* Sends a Tri-State "1" Bit
* ___ ___
* Waveform: | |_| |_
*/
void sendT1() {
transmit(3,1);
transmit(3,1);
}
/**
* Sends a Tri-State "F" Bit
* _ ___
* Waveform: | |___| |_
*/
void sendTF() {
transmit(1,3);
transmit(3,1);
}
/**
* Sends a "Sync" Bit
* _
* Waveform Protocol 1: | |_______________________________
* _
* Waveform Protocol 2: | |__________
*/
void sendSync() {
if (nProtocol == 1){
transmit(1,31);
}
else if (nProtocol == 2) {
transmit(1,10);
}
else if (nProtocol == 3) {
transmit(1,71);
}
}
void sendTriState(char* sCodeWord) {
for (int nRepeat=0; nRepeat<nRepeatTransmit; nRepeat++) {
int i = 0;
while (sCodeWord[i] != '\0') {
switch(sCodeWord[i]) {
case '0':
sendT0();
break;
case 'F':
sendTF();
break;
case '1':
sendT1();
break;
}
i++;
}
sendSync();
}
}
void transmit(int nHighPulses, int nLowPulses) {
digitalWrite(nTransmitterPin, HIGH);
_delay_ms(nPulseLength * nHighPulses);
digitalWrite(nTransmitterPin, LOW);
_delay_ms(nPulseLength * nLowPulses);
}
char* dec2binWzerofill(unsigned long Dec, unsigned int bitLength){
return dec2binWcharfill(Dec, bitLength, '0');
}
char* dec2binWcharfill(unsigned long Dec, unsigned int bitLength, char fill){
static char bin[64];
unsigned int i=0;
while (Dec > 0) {
bin[32+i++] = ((Dec & 1) > 0) ? '1' : fill;
Dec = Dec >> 1;
}
for (unsigned int j = 0; j< bitLength; j++) {
if (j >= bitLength - i) {
bin[j] = bin[ 31 + i - (j - (bitLength - i)) ];
}else {
bin[j] = fill;
}
}
bin[bitLength] = '\0';
return bin;
}
void send(char* sCodeWord) {
for (int nRepeat=0; nRepeat<nRepeatTransmit; nRepeat++) {
int i = 0;
while (sCodeWord[i] != '\0') {
switch(sCodeWord[i]) {
case '0':
send0();
break;
case '1':
send1();
break;
}
i++;
}
sendSync();
}
}

View File

@@ -0,0 +1,46 @@
#include <avr/io.h>
#include <util/delay.h>
#include <avr/sleep.h>
#include <avr/power.h>
const int ledPin = 4; //1;
//#define F_CPU 16000000UL
void sleepNow() {
{
// BODCR |= (1<<BODS)|(1<<BODSE); //Disable Brown Out Detector Control Register
ACSR |= (1<<ACD); //Analog comparator off
ACSR = ADMUX = ADCSRA = 0;
}
WDTCR |= (1<<WDP3) ; //Watchdog set for about 4 seconds
// Enable watchdog timer interrupts
WDTCR |= (1<<WDTIE);
sei(); // Enable global interrupts
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_mode();
sleep_disable();
}
void setup() {
DDRB = 0b000001; // all but PB0 INPUT, want to use PB0 ...
PORTB = 0b000000; // all LOW
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
}
void loop() {
digitalWrite(ledPin, HIGH);
_delay_ms(10);
digitalWrite(ledPin, LOW);
// _delay_ms(300);
sleepNow();
}

View File

@@ -0,0 +1,43 @@
#include <avr/sleep.h>
#ifdef __AVR_ATtiny13__
#define SLEEP_FOREVER 128
#define SLEEP_016MS (period_t)0
#define SLEEP_125MS (1<<WDP1) | (1<<WDP0)
#define SLEEP_250MS (1<<WDP2)
#define SLEEP_500MS (1<<WDP2) | (1<<WDP0)
#define SLEEP_1SEC (1<<WDP2) | (1<<WDP1)
#define SLEEP_2SEC (1<<WDP2) | (1<<WDP1) | (1<<WDP0)
#define SLEEP_4SEC (1<<WDP3)
#define SLEEP_8SEC (1<<WDP3) | (1<<WDP0)
#endif /* ifdef __AVR_ATtiny13__ */
// without that empty declaration, I got some problems with my other code. Maybe you don't need that.
ISR(WDT_vect) {
}
void sleepNow(byte b) {
{
ACSR |= (1 << ACD); //Analog comparator off
ACSR = ADMUX = ADCSRA = 0;
}
if (b != SLEEP_FOREVER) {
WDTCR |= b; //Watchdog
// Enable watchdog timer interrupts
WDTCR |= (1 << WDTIE);
}
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
cli(); // No interrupts; timed sequence
sei(); // Enable global interrupts or we never wake
sleep_mode();
sleep_disable();
}
// calling in loop() for example: sleepNow(SLEEP_1SEC);

307
ATTINY_TEMP/ATTINY_TEMP.ino Executable file
View File

@@ -0,0 +1,307 @@
/* Humidity/Temperature sensor si7021@atmega328p-pu chip running at 1 MGz powered by the two AA batteries
* Emulates Oregon V2.1 protocol to send the data
* The voltage regulator ams1117-adj, supplies constant 1.24 volts to battPIN pin when is powered up through the powerPIN
* The higher the value read on battPIN the lower the battery.
* arduine reads 380 at 3.3 volts on battery, and 569 at 2.22 volts on the battery
*/
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
#include <TinyWireM.h>
#include <USI_TWI_Master.h>
#include <SI7021.h>
const byte transPIN = 1; // Pin for the radio transmitter
const byte battPIN = 3; // A3, Pin to read battery level
const byte ledPIN = 4; // The test led pid
const uint16_t low_battery = 2100; // The limit for low battery (2.1 mV)
//------------ digitalWrite using direct port manipulation, attuny85 has portB only -----------------------
class directPort {
public:
directPort() { }
void sendOne(void);
void sendZero(void);
void selectPin(byte pin) {
set_mask = 0;
if (pin <= 7) {
set_mask = 1 << pin;
clr_mask = ~set_mask;
}
}
protected:
byte set_mask;
byte clr_mask;
public:
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
};
void directPort::sendOne(void) {
PORTB &= clr_mask; // digitalWrite(tx_pin, LOW);
delayMicroseconds(TIME);
PORTB |= set_mask; // digitalWrite(tx_pin, HIGH);
delayMicroseconds(TWOTIME);
PORTB &= clr_mask; // digitalWrite(tx_pin, LOW);
delayMicroseconds(TIME);
}
void directPort::sendZero(void) {
PORTB |= set_mask; // digitalWrite(tx_pin, HIGH);
delayMicroseconds(TIME);
PORTB &= clr_mask; // digitalWrite(tx_pin, LOW);
delayMicroseconds(TWOTIME);
PORTB |= set_mask; // digitalWrite(tx_pin, HIGH);
delayMicroseconds(TIME);
}
//----------------------------------- Send the temp & humidity using oregon v2.1 protocol -------------
class OregonSensor {
public:
OregonSensor(byte txPin, byte channel, byte sensorID, bool Humidity = false) {
tx_pin = txPin;
if (tx_pin <= 7) { // PORTD
dpB.selectPin(tx_pin);
}
existsHumidity = Humidity;
int type = 0xEA4C; // by default emulate TNHN132N
if (existsHumidity) type = 0x1A2D; // emulate THGR2228N
buffer[0] = type >> 8;
buffer[1] = type & 0xFF;
buffer[2] = channel;
buffer[3] = sensorID;
}
void init(void);
void sendTempHumidity(int temp, byte humm, bool battery);
private:
inline void sendOne(void) { dpB.sendOne(); }
inline void sendZero(void) { dpB.sendZero(); }
void sendData(const byte *data, byte size); // Send data buffer
void sendPreamble(void); // Send preamble
void sendPostamble(void); // Send postamble
void sendOregon(void); // Send preamble, data, postamble
void sendSync(void);
int sum(byte count); // Count the buffer summ
void calculateAndSetChecksum(void);
bool existsHumidity; // Weither THGR2228N (send Humidity)
byte buffer[9];
byte tx_pin;
directPort dpB;
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
};
void OregonSensor::init(void) {
pinMode(tx_pin, OUTPUT);
digitalWrite(tx_pin, LOW);
}
void OregonSensor::sendData(const byte *data, byte size) {
for(byte i = 0; i < size; ++i) {
byte m = 1;
byte d = data[i];
(d & m)? sendOne(): sendZero(); m <<= 1;
(d & m)? sendOne(): sendZero(); m <<= 1;
(d & m)? sendOne(): sendZero(); m <<= 1;
(d & m)? sendOne(): sendZero(); m <<= 1;
(d & m)? sendOne(): sendZero(); m <<= 1;
(d & m)? sendOne(): sendZero(); m <<= 1;
(d & m)? sendOne(): sendZero(); m <<= 1;
(d & m)? sendOne(): sendZero();
}
}
void OregonSensor::sendOregon(void) {
sendPreamble();
byte size = 8;
if (existsHumidity) size = 9;
sendData(buffer, size);
sendPostamble();
digitalWrite(tx_pin, LOW);
}
void OregonSensor::sendPreamble(void) {
byte PREAMBLE[] = {0xFF,0xFF};
sendData(PREAMBLE, 2);
}
void OregonSensor::sendPostamble(void) {
sendZero();
sendZero();
sendZero();
sendZero();
if (!existsHumidity) return; // TNHN132N
sendZero();
sendZero();
sendZero();
sendZero();
}
void OregonSensor::sendSync(void) {
byte data = 0xA;
(data & 1)? sendOne(): sendZero(); data >>= 1;
(data & 1)? sendOne(): sendZero(); data >>= 1;
(data & 1)? sendOne(): sendZero(); data >>= 1;
(data & 1)? sendOne(): sendZero();
}
int OregonSensor::sum(byte count) {
int s = 0;
for(byte i = 0; i < count; i++) {
s += (buffer[i]&0xF0) >> 4;
s += (buffer[i]&0xF);
}
if(int(count) != count)
s += (buffer[count]&0xF0) >> 4;
return s;
}
void OregonSensor::calculateAndSetChecksum(void) {
if (!existsHumidity) {
int s = ((sum(6) + (buffer[6]&0xF) - 0xa) & 0xff);
buffer[6] |= (s&0x0F) << 4; buffer[7] = (s&0xF0) >> 4;
} else {
buffer[8] = ((sum(8) - 0xa) & 0xFF);
}
}
void OregonSensor::sendTempHumidity(int temp, byte humm, bool battery) { // temperature centegrees * 10
if(!battery) buffer[4] = 0x0C; else buffer[4] = 0x00;
if(temp < 0) {
buffer[6] = 0x08;
temp *= -1;
} else {
buffer[6] = 0x00;
}
byte d3 = temp % 10; // Set temperature decimal part
buffer[4] |= d3 << 4;
temp /= 10;
byte d1 = temp / 10; // 1st decimal digit of the temperature
byte d2 = temp % 10; // 2nd deciaml digit of the temperature
buffer[5] = d1 << 4;
buffer[5] |= d2;
if (existsHumidity) { // THGR2228N
buffer[7] = humm / 10;
buffer[6] |= (humm % 10) << 4;
}
calculateAndSetChecksum();
sendOregon(); // The v2.1 protocol send the message two times
delayMicroseconds(TWOTIME*8);
sendOregon();
}
//================================ End of the class definitions ==================================================
SI7021 sensor;
OregonSensor os(transPIN, 0x20, 0xAA, true);
void enterSleep(void) {
ADCSRA &= ~(1<<ADEN); // disable ADC
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // the lowest power consumption
sleep_enable();
sleep_cpu(); // Now enter sleep mode.
// The program will continue from here after the WDT timeout.
sleep_disable(); // First thing to do is disable sleep.
power_all_enable(); // Re-enable the peripherals.
ADCSRA |= 1<<ADEN; // enable ADC
}
/*
* https://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/
* Read 1.1V reference against AVcc
* set the reference to Vcc and the measurement to the internal 1.1V reference
*/
uint32_t readVcc() { // Vcc in millivolts
#if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0);
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#endif
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Start conversion
while (bit_is_set(ADCSRA,ADSC)); // measuring
uint8_t low = ADCL; // must read ADCL first - it then locks ADCH
uint8_t high = ADCH; // unlocks both
long result = (high<<8) | low;
result = 1125300L / result; // Calculate Vcc (in mV); 112530 = 1.1*1023*1000
return result;
}
volatile byte f_wdt = 1;
void setup() {
pinMode(battPIN, INPUT);
pinMode(ledPIN, OUTPUT);
digitalWrite(ledPIN, LOW); // Switch off the led
os.init();
delay(15000); // This timeout allows to flash new program
// Setup the WDT
MCUSR &= ~(1<<WDRF); // Clear the reset flag
// In order to change WDE or the prescaler, we need to
// set WDCE (This will allow updates for 4 clock cycles).
WDTCR |= (1<<WDCE) | (1<<WDE);
WDTCR = 1<<WDP0 | 1<<WDP3; // set new watchdog timeout prescaler value 8.0 seconds
WDTCR |= _BV(WDIE); // Enable the WD interrupt (note no reset).
sensor.begin();
}
void loop() {
static int awake_counter = 1;
static int check_battery = 0;
static bool batteryOK = true;
if (f_wdt == 1) {
f_wdt = 0;
--awake_counter;
if (awake_counter <= 0) { // Send Weather data
awake_counter = 5;
// Check the battery level every 100 wake ups 100*5*8s = 4000 seconds
if (batteryOK && (check_battery == 0)) { // The battery cannot repare by itself!
uint32_t mV = readVcc();
batteryOK = (mV >= low_battery);
}
++check_battery; if (check_battery > 100) check_battery = 0;
int temperature = sensor.getCelsiusHundredths();
if (temperature > 0)
temperature += 5;
else
temperature -= 5;
temperature /= 10;
byte humidity = sensor.getHumidityPercent();
digitalWrite(ledPIN, HIGH); // turn-on the led during the data transmition
os.sendTempHumidity(temperature, humidity, batteryOK);
digitalWrite(ledPIN, LOW);
}
enterSleep(); // power-save mode for 8 seconds
}
}
ISR(WDT_vect) {
if (f_wdt == 0) f_wdt = 1;
}

View File

@@ -0,0 +1,333 @@
/* Humidity/Temperature sensor si7021@atmega328p-pu chip running at 1 MGz powered by the two AA batteries
* Emulates Oregon V2.1 protocol to send the data
* The voltage regulator ams1117-adj, supplies constant 1.24 volts to battPIN pin when is powered up through the powerPIN
* The higher the value read on battPIN the lower the battery.
* arduine reads 380 at 3.3 volts on battery, and 569 at 2.22 volts on the battery
*/
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
#include <Wire.h>
//#include <USI_TWI_Master.h>
//#include <SI7021.h>
#include <Adafruit_BMP085.h>
const byte transPIN = 9; // Pin for the radio transmitter
const byte battPIN = 3; // A3, Pin to read battery level
const byte ledPIN = 13; // The test led pid
const uint16_t low_battery = 2100; // The limit for low battery (2.1 mV)
static int awake_counter = 1;
static int check_battery = 0;
static bool batteryOK = true;
//------------ digitalWrite using direct port manipulation, attuny85 has portB only -----------------------
class directPort {
public:
directPort() { }
void sendOne(void);
void sendZero(void);
void selectPin(byte pin) {
set_mask = 0;
if (pin <= 7) {
set_mask = 1 << pin;
clr_mask = ~set_mask;
}
}
protected:
byte set_mask;
byte clr_mask;
public:
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
};
void directPort::sendOne(void) {
PORTB &= clr_mask; // digitalWrite(tx_pin, LOW);
delayMicroseconds(TIME);
PORTB |= set_mask; // digitalWrite(tx_pin, HIGH);
delayMicroseconds(TWOTIME);
PORTB &= clr_mask; // digitalWrite(tx_pin, LOW);
delayMicroseconds(TIME);
}
void directPort::sendZero(void) {
PORTB |= set_mask; // digitalWrite(tx_pin, HIGH);
delayMicroseconds(TIME);
PORTB &= clr_mask; // digitalWrite(tx_pin, LOW);
delayMicroseconds(TWOTIME);
PORTB |= set_mask; // digitalWrite(tx_pin, HIGH);
delayMicroseconds(TIME);
}
//----------------------------------- Send the temp & humidity using oregon v2.1 protocol -------------
class OregonSensor {
public:
OregonSensor(byte txPin, byte channel, byte sensorID, bool Humidity = false) {
tx_pin = txPin;
if (tx_pin <= 7) { // PORTD
dpB.selectPin(tx_pin);
}
existsHumidity = Humidity;
int type = 0xEA4C; // by default emulate TNHN132N
if (existsHumidity) type = 0x1A2D; // emulate THGR2228N
buffer[0] = type >> 8;
buffer[1] = type & 0xFF;
buffer[2] = channel;
buffer[3] = sensorID;
}
void init(void);
void sendTempHumidity(int temp, byte humm, bool battery);
private:
inline void sendOne(void) { dpB.sendOne(); }
inline void sendZero(void) { dpB.sendZero(); }
void sendData(const byte *data, byte size); // Send data buffer
void sendPreamble(void); // Send preamble
void sendPostamble(void); // Send postamble
void sendOregon(void); // Send preamble, data, postamble
void sendSync(void);
int sum(byte count); // Count the buffer summ
void calculateAndSetChecksum(void);
bool existsHumidity; // Weither THGR2228N (send Humidity)
byte buffer[9];
byte tx_pin;
directPort dpB;
const unsigned long TIME = 512;
const unsigned long TWOTIME = TIME*2;
};
void OregonSensor::init(void) {
pinMode(tx_pin, OUTPUT);
digitalWrite(tx_pin, LOW);
}
void OregonSensor::sendData(const byte *data, byte size) {
for(byte i = 0; i < size; ++i) {
byte m = 1;
byte d = data[i];
(d & m)? sendOne(): sendZero(); m <<= 1;
(d & m)? sendOne(): sendZero(); m <<= 1;
(d & m)? sendOne(): sendZero(); m <<= 1;
(d & m)? sendOne(): sendZero(); m <<= 1;
(d & m)? sendOne(): sendZero(); m <<= 1;
(d & m)? sendOne(): sendZero(); m <<= 1;
(d & m)? sendOne(): sendZero(); m <<= 1;
(d & m)? sendOne(): sendZero();
}
}
void OregonSensor::sendOregon(void) {
sendPreamble();
byte size = 8;
if (existsHumidity) size = 9;
sendData(buffer, size);
sendPostamble();
digitalWrite(tx_pin, LOW);
}
void OregonSensor::sendPreamble(void) {
byte PREAMBLE[] = {0xFF,0xFF};
sendData(PREAMBLE, 2);
}
void OregonSensor::sendPostamble(void) {
sendZero();
sendZero();
sendZero();
sendZero();
if (!existsHumidity) return; // TNHN132N
sendZero();
sendZero();
sendZero();
sendZero();
}
void OregonSensor::sendSync(void) {
byte data = 0xA;
(data & 1)? sendOne(): sendZero(); data >>= 1;
(data & 1)? sendOne(): sendZero(); data >>= 1;
(data & 1)? sendOne(): sendZero(); data >>= 1;
(data & 1)? sendOne(): sendZero();
}
int OregonSensor::sum(byte count) {
int s = 0;
for(byte i = 0; i < count; i++) {
s += (buffer[i]&0xF0) >> 4;
s += (buffer[i]&0xF);
}
if(int(count) != count)
s += (buffer[count]&0xF0) >> 4;
return s;
}
void OregonSensor::calculateAndSetChecksum(void) {
if (!existsHumidity) {
int s = ((sum(6) + (buffer[6]&0xF) - 0xa) & 0xff);
buffer[6] |= (s&0x0F) << 4; buffer[7] = (s&0xF0) >> 4;
} else {
buffer[8] = ((sum(8) - 0xa) & 0xFF);
}
}
void OregonSensor::sendTempHumidity(int temp, byte humm, bool battery) { // temperature centegrees * 10
if(!battery) buffer[4] = 0x0C; else buffer[4] = 0x00;
if(temp < 0) {
buffer[6] = 0x08;
temp *= -1;
} else {
buffer[6] = 0x00;
}
byte d3 = temp % 10; // Set temperature decimal part
buffer[4] |= d3 << 4;
temp /= 10;
byte d1 = temp / 10; // 1st decimal digit of the temperature
byte d2 = temp % 10; // 2nd deciaml digit of the temperature
buffer[5] = d1 << 4;
buffer[5] |= d2;
if (existsHumidity) { // THGR2228N
buffer[7] = humm / 10;
buffer[6] |= (humm % 10) << 4;
}
calculateAndSetChecksum();
sendOregon(); // The v2.1 protocol send the message two times
delayMicroseconds(TWOTIME*8);
sendOregon();
}
//================================ End of the class definitions ==================================================
//SI7021 sensor;
// ################# Barometre ####
Adafruit_BMP085 sensor;
// #####################
OregonSensor os(transPIN, 0x20, 0xAA, true);
void enterSleep(void) {
ADCSRA &= ~(1<<ADEN); // disable ADC
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // the lowest power consumption
sleep_enable();
sleep_cpu(); // Now enter sleep mode.
// The program will continue from here after the WDT timeout.
sleep_disable(); // First thing to do is disable sleep.
power_all_enable(); // Re-enable the peripherals.
ADCSRA |= 1<<ADEN; // enable ADC
}
/*
* https://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/
* Read 1.1V reference against AVcc
* set the reference to Vcc and the measurement to the internal 1.1V reference
*/
uint32_t readVcc() { // Vcc in millivolts
#if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0);
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#endif
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Start conversion
while (bit_is_set(ADCSRA,ADSC)); // measuring
uint8_t low = ADCL; // must read ADCL first - it then locks ADCH
uint8_t high = ADCH; // unlocks both
long result = (high<<8) | low;
result = 1125300L / result; // Calculate Vcc (in mV); 112530 = 1.1*1023*1000
return result;
}
volatile byte f_wdt = 1;
void setup() {
pinMode(battPIN, INPUT);
pinMode(ledPIN, OUTPUT);
digitalWrite(ledPIN, LOW); // Switch off the led
os.init();
//delay(30000); // This timeout allows to flash new program
// Setup the WDT
MCUSR &= ~(1<<WDRF); // Clear the reset flag
// In order to change WDE or the prescaler, we need to
// set WDCE (This will allow updates for 4 clock cycles).
// WDTCR |= (1<<WDCE) | (1<<WDE);
// WDTCR = 1<<WDP0 | 1<<WDP3; // set new watchdog timeout prescaler value 8.0 seconds
// WDTCR |= _BV(WDIE); // Enable the WD interrupt (note no reset).
Serial.begin(9600);
Serial.println("Setup ");
wdt_enable(WDTO_8S);
sensor.begin();
}
void loop() {
// static int awake_counter = 1;
// static int check_battery = 0;
// static bool batteryOK = true;
Serial.print("Boucle ");
Serial.print(awake_counter);
Serial.print(" ");
Serial.println(f_wdt);
if (f_wdt == 1) {
f_wdt = 0;
--awake_counter;
if (awake_counter <= 0) { // Send Weather data
awake_counter = 5;
// Check the battery level every 100 wake ups 100*5*8s = 4000 seconds
if (batteryOK && (check_battery == 0)) { // The battery cannot repare by itself!
uint32_t mV = readVcc();
batteryOK = (mV >= low_battery);
}
++check_battery; if (check_battery > 100) check_battery = 0;
int temperature = 15; //sensor.readTemperature(); //sensor.getCelsiusHundredths();
if (temperature > 0)
temperature += 5;
else
temperature -= 5;
temperature /= 10;
byte humidity = 0; //sensor.getHumidityPercent();
digitalWrite(ledPIN, HIGH); // turn-on the led during the data transmition
os.sendTempHumidity(temperature, humidity, batteryOK);
digitalWrite(ledPIN, LOW);
}
Serial.print(awake_counter);
Serial.print(" ");
Serial.println(f_wdt);
delay(100);
enterSleep(); // power-save mode for 8 seconds
}
}
ISR(WDT_vect) {
if (f_wdt == 0) f_wdt = 1;
}

View File

@@ -0,0 +1,37 @@
#include <ESP8266WiFi.h>
#include <Adafruit_BMP085.h>
Adafruit_BMP085 bmp;
const int sleepTimeS = 60;
WiFiClient espClient;
char valTemperature[5];
char valPressure[5];
void setup() {
pinMode(BUILTIN_LED, OUTPUT);
Serial.begin(9600);
if (!bmp.begin()) {
Serial.println("BMP085 not found");
while (1) {}
}
delay(10000);
}
void loop() {
// read temperature
dtostrf(bmp.readTemperature(), 3, 1, valTemperature);
String payload;
payload = "sensor2 temperature=";
payload += valTemperature;
// read pressure
dtostrf(bmp.readPressure(), 3, 1, valPressure);
payload = "sensor2 pressure=";
payload += valPressure;
}

119
AnalogInput/AnalogInput.ino Normal file
View File

@@ -0,0 +1,119 @@
/*
Analog Input
Demonstrates analog input by reading an analog sensor on analog pin 0 and
turning on and off a light emitting diode(LED) connected to digital pin 13.
The amount of time the LED will be on and off depends on the value obtained
by analogRead().
The circuit:
- potentiometer
center pin of the potentiometer to the analog input 0
one side pin (either one) to ground
the other side pin to +5V
- LED
anode (long leg) attached to digital output 13
cathode (short leg) attached to ground
- Note: because most Arduinos have a built-in LED attached to pin 13 on the
board, the LED is optional.
created by David Cuartielles
modified 30 Aug 2011
By Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/AnalogInput
*/
int sensorPin = A3; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
float sensorValue = 0; // variable to store the value coming from the sensor
void setup() {
// declare the ledPin as an OUTPUT:
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
// read the value from the sensor:
// sensorValue = 0;
// int bcl = 75;
// for (int i=1; i <bcl; i++) {
// sensorValue += analogRead(sensorPin);
// delay(1);
// }
int number_of_samples = 50;
long sum_squared_voltage = 0;
for (int n=0; n<number_of_samples; n++)
{
// inst_voltage calculation from raw ADC input goes here.
int inst_voltage = analogRead(A3) - 512;
long squared_voltage = inst_voltage * inst_voltage;
sum_squared_voltage += squared_voltage;
// delay(20);
}
double mean_square_voltage = sum_squared_voltage / number_of_samples;
double root_mean_square_voltage = sqrt(mean_square_voltage);
//
// sensorValue = analogRead(sensorPin);
// Serial.print(sensorValue - 512);
// Serial.print(mean_square_voltage);
// Serial.print(" V2 ");
Serial.print(root_mean_square_voltage);
Serial.println(" V ");
// long sum_squared_current = 0;
//
// for (int n=0; n<number_of_samples; n++)
// {
// // inst_current calculation from raw ADC input goes here.
// int inst_current = analogRead(A5) - 512;
//
// long squared_current = inst_current * inst_current;
//
// sum_squared_current += squared_current;
// }
//
// double mean_square_current = sum_squared_current / number_of_samples;
// double root_mean_square_current = sqrt(mean_square_current);
//
// Serial.print(root_mean_square_current);
// Serial.println(" A ");
// sum_squared_current = 0;
//
// for (int n=0; n<number_of_samples; n++)
// {
// // inst_current calculation from raw ADC input goes here.
// int inst_current = analogRead(A5) - 512;
//
// long squared_current = inst_current * inst_current;
//
// sum_squared_current += squared_current;
// }
//
// mean_square_current = sum_squared_current / number_of_samples;
// root_mean_square_current = sqrt(mean_square_current);
//
// Serial.print(root_mean_square_current);
// Serial.println(" A ");
// Serial.print("moyenne ");
// Serial.println(somme / mesure);
// turn the ledPin on
// digitalWrite(ledPin, HIGH);
// // stop the program for <sensorValue> milliseconds:
// delay(sensorValue);
// // turn the ledPin off:
// digitalWrite(ledPin, LOW);
// stop the program for for <sensorValue> milliseconds:
// delay(1);
}

View File

@@ -0,0 +1,377 @@
// ArduCAM Mini demo (C)2017 Lee
// Web: http://www.ArduCAM.com
// This program is a demo of how to use most of the functions
// of the library with ArduCAM ESP8266 2MP/5MP camera.
// This demo was made for ArduCAM ESP8266 2MP/5MP Camera.
// It can take photo and send to the Web.
// It can take photo continuously as video streaming and send to the Web.
// The demo sketch will do the following tasks:
// 1. Set the camera to JPEG output mode.
// 2. if server.on("/capture", HTTP_GET, serverCapture),it can take photo and send to the Web.
// 3.if server.on("/stream", HTTP_GET, serverStream),it can take photo continuously as video
//streaming and send to the Web.
// This program requires the ArduCAM V4.0.0 (or later) library and ArduCAM ESP8266 2MP/5MP camera
// and use Arduino IDE 1.6.8 compiler or above
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <Wire.h>
#include <ArduCAM.h>
#include <SPI.h>
#include "memorysaver.h"
#if !(defined ESP8266 )
#error Please select the ArduCAM ESP8266 UNO board in the Tools/Board
#endif
//This demo can only work on OV2640_MINI_2MP or ARDUCAM_SHIELD_V2 platform.
#if !(defined (OV2640_MINI_2MP)||defined (OV5640_MINI_5MP_PLUS) || defined (OV5642_MINI_5MP_PLUS) \
|| defined (OV5642_MINI_5MP) || defined (OV5642_MINI_5MP_BIT_ROTATION_FIXED) \
||(defined (ARDUCAM_SHIELD_V2) && (defined (OV2640_CAM) || defined (OV5640_CAM) || defined (OV5642_CAM))))
#error Please select the hardware platform and camera module in the ../libraries/ArduCAM/memorysaver.h file
#endif
// set GPIO16 as the slave select :
const int CS = 16;
//you can change the value of wifiType to select Station or AP mode.
//Default is AP mode.
int wifiType = 0; // 0:Station 1:AP
//AP mode configuration
//Default is arducam_esp8266.If you want,you can change the AP_aaid to your favorite name
const char *AP_ssid = "arducam_esp8266";
//Default is no password.If you want to set password,put your password here
const char *AP_password = "";
//Station mode you should put your ssid and password
const char *ssid = "Livebox-37cc"; // Put your SSID here
const char *password = "8A6060920A8A86896F770F2C47"; // Put your PASSWORD here
static const size_t bufferSize = 2048;
static uint8_t buffer[bufferSize] = {0xFF};
uint8_t temp = 0, temp_last = 0;
int i = 0;
bool is_header = false;
ESP8266WebServer server(80);
#if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
ArduCAM myCAM(OV2640, CS);
#elif defined (OV5640_MINI_5MP_PLUS) || defined (OV5640_CAM)
ArduCAM myCAM(OV5640, CS);
#elif defined (OV5642_MINI_5MP_PLUS) || defined (OV5642_MINI_5MP) || defined (OV5642_MINI_5MP_BIT_ROTATION_FIXED) ||(defined (OV5642_CAM))
ArduCAM myCAM(OV5642, CS);
#endif
void start_capture() {
myCAM.clear_fifo_flag();
myCAM.start_capture();
}
void camCapture(ArduCAM myCAM) {
WiFiClient client = server.client();
uint32_t len = myCAM.read_fifo_length();
if (len >= MAX_FIFO_SIZE) //8M
{
Serial.println(F("Over size."));
}
if (len == 0 ) //0 kb
{
Serial.println(F("Size is 0."));
}
myCAM.CS_LOW();
myCAM.set_fifo_burst();
if (!client.connected()) return;
String response = "HTTP/1.1 200 OK\r\n";
response += "Content-Type: image/jpeg\r\n";
response += "Content-len: " + String(len) + "\r\n\r\n";
server.sendContent(response);
i = 0;
while ( len-- )
{
temp_last = temp;
temp = SPI.transfer(0x00);
//Read JPEG data from FIFO
if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
{
buffer[i++] = temp; //save the last 0XD9
//Write the remain bytes in the buffer
if (!client.connected()) break;
client.write(&buffer[0], i);
is_header = false;
i = 0;
myCAM.CS_HIGH();
break;
}
if (is_header == true)
{
//Write image data to buffer if not full
if (i < bufferSize)
buffer[i++] = temp;
else
{
//Write bufferSize bytes image data to file
if (!client.connected()) break;
client.write(&buffer[0], bufferSize);
i = 0;
buffer[i++] = temp;
}
}
else if ((temp == 0xD8) & (temp_last == 0xFF))
{
is_header = true;
buffer[i++] = temp_last;
buffer[i++] = temp;
}
}
}
void serverCapture() {
start_capture();
Serial.println(F("CAM Capturing"));
int total_time = 0;
total_time = millis();
while (!myCAM.get_bit(ARDUCHIP_TRIG, CAP_DONE_MASK));
total_time = millis() - total_time;
Serial.print(F("capture total_time used (in miliseconds):"));
Serial.println(total_time, DEC);
total_time = 0;
Serial.println(F("CAM Capture Done."));
total_time = millis();
camCapture(myCAM);
total_time = millis() - total_time;
Serial.print(F("send total_time used (in miliseconds):"));
Serial.println(total_time, DEC);
Serial.println(F("CAM send Done."));
}
void serverStream() {
WiFiClient client = server.client();
String response = "HTTP/1.1 200 OK\r\n";
response += "Content-Type: multipart/x-mixed-replace; boundary=frame\r\n\r\n";
server.sendContent(response);
while (1) {
start_capture();
while (!myCAM.get_bit(ARDUCHIP_TRIG, CAP_DONE_MASK));
size_t len = myCAM.read_fifo_length();
if (len >= MAX_FIFO_SIZE) //8M
{
Serial.println(F("Over size."));
continue;
}
if (len == 0 ) //0 kb
{
Serial.println(F("Size is 0."));
continue;
}
myCAM.CS_LOW();
myCAM.set_fifo_burst();
if (!client.connected()) {
client.stop(); is_header = false; break;
}
response = "--frame\r\n";
response += "Content-Type: image/jpeg\r\n\r\n";
server.sendContent(response);
while ( len-- )
{
temp_last = temp;
temp = SPI.transfer(0x00);
//Read JPEG data from FIFO
if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
{
buffer[i++] = temp; //save the last 0XD9
//Write the remain bytes in the buffer
myCAM.CS_HIGH();;
if (!client.connected()) {
client.stop(); is_header = false; break;
}
client.write(&buffer[0], i);
is_header = false;
i = 0;
}
if (is_header == true)
{
//Write image data to buffer if not full
if (i < bufferSize)
buffer[i++] = temp;
else
{
//Write bufferSize bytes image data to file
myCAM.CS_HIGH();
if (!client.connected()) {
client.stop(); is_header = false; break;
}
client.write(&buffer[0], bufferSize);
i = 0;
buffer[i++] = temp;
myCAM.CS_LOW();
myCAM.set_fifo_burst();
}
}
else if ((temp == 0xD8) & (temp_last == 0xFF))
{
is_header = true;
buffer[i++] = temp_last;
buffer[i++] = temp;
}
}
if (!client.connected()) {
client.stop(); is_header = false; break;
}
}
}
void handleNotFound() {
String message = "Server is running!\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
server.send(200, "text/plain", message);
if (server.hasArg("ql")) {
int ql = server.arg("ql").toInt();
#if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
myCAM.OV2640_set_JPEG_size(ql);
#elif defined (OV5640_MINI_5MP_PLUS) || defined (OV5640_CAM)
myCAM.OV5640_set_JPEG_size(ql);
#elif defined (OV5642_MINI_5MP_PLUS) || defined (OV5642_MINI_5MP_BIT_ROTATION_FIXED) ||(defined (OV5642_CAM))
myCAM.OV5642_set_JPEG_size(ql);
#endif
delay(1000);
Serial.println("QL change to: " + server.arg("ql"));
}
}
void setup() {
uint8_t vid, pid;
uint8_t temp;
#if defined(__SAM3X8E__)
Wire1.begin();
#else
Wire.begin();
#endif
Serial.begin(115200);
Serial.println(F("ArduCAM Start!"));
// set the CS as an output:
pinMode(CS, OUTPUT);
// initialize SPI:
SPI.begin();
SPI.setFrequency(4000000); //4MHz
//Check if the ArduCAM SPI bus is OK
myCAM.write_reg(ARDUCHIP_TEST1, 0x55);
temp = myCAM.read_reg(ARDUCHIP_TEST1);
if (temp != 0x55) {
Serial.println(F("SPI1 interface Error!"));
while (1);
}
#if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
//Check if the camera module type is OV2640
myCAM.wrSensorReg8_8(0xff, 0x01);
myCAM.rdSensorReg8_8(OV2640_CHIPID_HIGH, &vid);
myCAM.rdSensorReg8_8(OV2640_CHIPID_LOW, &pid);
if ((vid != 0x26 ) && (( pid != 0x41 ) || ( pid != 0x42 )))
Serial.println(F("Can't find OV2640 module!"));
else
Serial.println(F("OV2640 detected."));
#elif defined (OV5640_MINI_5MP_PLUS) || defined (OV5640_CAM)
//Check if the camera module type is OV5640
myCAM.wrSensorReg16_8(0xff, 0x01);
myCAM.rdSensorReg16_8(OV5640_CHIPID_HIGH, &vid);
myCAM.rdSensorReg16_8(OV5640_CHIPID_LOW, &pid);
if ((vid != 0x56) || (pid != 0x40))
Serial.println(F("Can't find OV5640 module!"));
else
Serial.println(F("OV5640 detected."));
#elif defined (OV5642_MINI_5MP_PLUS) || defined (OV5642_MINI_5MP) || defined (OV5642_MINI_5MP_BIT_ROTATION_FIXED) ||(defined (OV5642_CAM))
//Check if the camera module type is OV5642
myCAM.wrSensorReg16_8(0xff, 0x01);
myCAM.rdSensorReg16_8(OV5642_CHIPID_HIGH, &vid);
myCAM.rdSensorReg16_8(OV5642_CHIPID_LOW, &pid);
if ((vid != 0x56) || (pid != 0x42)) {
Serial.println(F("Can't find OV5642 module!"));
}
else
Serial.println(F("OV5642 detected."));
#endif
//Change to JPEG capture mode and initialize the OV2640 module
myCAM.set_format(JPEG);
myCAM.InitCAM();
#if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
myCAM.OV2640_set_JPEG_size(OV2640_800x600);
#elif defined (OV5640_MINI_5MP_PLUS) || defined (OV5640_CAM)
myCAM.write_reg(ARDUCHIP_TIM, VSYNC_LEVEL_MASK); //VSYNC is active HIGH
myCAM.OV5640_set_JPEG_size(OV5640_320x240);
#elif defined (OV5642_MINI_5MP_PLUS) || defined (OV5642_MINI_5MP) || defined (OV5642_MINI_5MP_BIT_ROTATION_FIXED) ||(defined (OV5642_CAM))
myCAM.write_reg(ARDUCHIP_TIM, VSYNC_LEVEL_MASK); //VSYNC is active HIGH
myCAM.OV5640_set_JPEG_size(OV5642_320x240);
#endif
myCAM.clear_fifo_flag();
if (wifiType == 0) {
if (!strcmp(ssid, "SSID")) {
Serial.println(F("Please set your SSID"));
while (1);
}
if (!strcmp(password, "PASSWORD")) {
Serial.println(F("Please set your PASSWORD"));
while (1);
}
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print(F("Connecting to "));
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(F("."));
}
Serial.println(F("WiFi connected"));
Serial.println("");
Serial.println(WiFi.localIP());
} else if (wifiType == 1) {
Serial.println();
Serial.println();
Serial.print(F("Share AP: "));
Serial.println(AP_ssid);
Serial.print(F("The password is: "));
Serial.println(AP_password);
WiFi.mode(WIFI_AP);
WiFi.softAP(AP_ssid, AP_password);
Serial.println("");
Serial.println(WiFi.softAPIP());
}
// Start the server
server.on("/capture", HTTP_GET, serverCapture);
server.on("/stream", HTTP_GET, serverStream);
server.onNotFound(handleNotFound);
server.begin();
Serial.println(F("Server started"));
}
void loop() {
server.handleClient();
}

View File

@@ -0,0 +1,383 @@
// ArduCAM Mini demo (C)2017 Lee
// Web: http://www.ArduCAM.com
// This program is a demo of how to use most of the functions
// of the library with ArduCAM ESP8266 2MP/5MP camera.
// This demo was made for ArduCAM ESP8266 2MP/5MP Camera.
// It can take photo and send to the Web.
// It can take photo continuously as video streaming and send to the Web.
// The demo sketch will do the following tasks:
// 1. Set the camera to JPEG output mode.
// 2. if server.on("/capture", HTTP_GET, serverCapture),it can take photo and send to the Web.
// 3.if server.on("/stream", HTTP_GET, serverStream),it can take photo continuously as video
//streaming and send to the Web.
// This program requires the ArduCAM V4.0.0 (or later) library and ArduCAM ESP8266 2MP/5MP camera
// and use Arduino IDE 1.6.8 compiler or above
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <Wire.h>
#include <ArduCAM.h>
#include <SPI.h>
#include "memorysaver.h"
#if !(defined ESP8266 )
#error Please select the ArduCAM ESP8266 UNO board in the Tools/Board
#endif
//This demo can only work on OV2640_MINI_2MP or ARDUCAM_SHIELD_V2 platform.
#if !(defined (OV2640_MINI_2MP)||defined (OV5640_MINI_5MP_PLUS) || defined (OV5642_MINI_5MP_PLUS) \
|| defined (OV5642_MINI_5MP) || defined (OV5642_MINI_5MP_BIT_ROTATION_FIXED) \
||(defined (ARDUCAM_SHIELD_V2) && (defined (OV2640_CAM) || defined (OV5640_CAM) || defined (OV5642_CAM))))
#error Please select the hardware platform and camera module in the ../libraries/ArduCAM/memorysaver.h file
#endif
// set GPIO2 as the slave select :
const int CS = 2;
//Version 2,set GPIO0 as the slave select :
const int SD_CS = 0;
const int CAM_POWER_ON = 15;
//you can change the value of wifiType to select Station or AP mode.
//Default is AP mode.
int wifiType = 1; // 0:Station 1:AP
//AP mode configuration
//Default is arducam_esp8266.If you want,you can change the AP_aaid to your favorite name
const char *AP_ssid = "arducam_esp8266";
//Default is no password.If you want to set password,put your password here
const char *AP_password = "";
//Station mode you should put your ssid and password
const char *ssid = "Livebox-37cc"; // Put your SSID here
const char *password = "8A6060920A8A86896F770F2C47"; // Put your PASSWORD here
static const size_t bufferSize = 4096;
static uint8_t buffer[bufferSize] = {0xFF};
uint8_t temp = 0, temp_last = 0;
int i = 0;
bool is_header = false;
ESP8266WebServer server(80);
#if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
ArduCAM myCAM(OV2640, CS);
#elif defined (OV5640_MINI_5MP_PLUS) || defined (OV5640_CAM)
ArduCAM myCAM(OV5640, CS);
#elif defined (OV5642_MINI_5MP_PLUS) || defined (OV5642_MINI_5MP) || defined (OV5642_MINI_5MP_BIT_ROTATION_FIXED) ||(defined (OV5642_CAM))
ArduCAM myCAM(OV5642, CS);
#endif
void start_capture() {
myCAM.clear_fifo_flag();
myCAM.start_capture();
}
void camCapture(ArduCAM myCAM) {
WiFiClient client = server.client();
uint32_t len = myCAM.read_fifo_length();
if (len >= MAX_FIFO_SIZE) //8M
{
Serial.println(F("Over size."));
}
if (len == 0 ) //0 kb
{
Serial.println(F("Size is 0."));
}
myCAM.CS_LOW();
myCAM.set_fifo_burst();
if (!client.connected()) return;
String response = "HTTP/1.1 200 OK\r\n";
response += "Content-Type: image/jpeg\r\n";
response += "Content-len: " + String(len) + "\r\n\r\n";
server.sendContent(response);
i = 0;
while ( len-- )
{
temp_last = temp;
temp = SPI.transfer(0x00);
//Read JPEG data from FIFO
if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
{
buffer[i++] = temp; //save the last 0XD9
//Write the remain bytes in the buffer
if (!client.connected()) break;
client.write(&buffer[0], i);
is_header = false;
i = 0;
myCAM.CS_HIGH();
break;
}
if (is_header == true)
{
//Write image data to buffer if not full
if (i < bufferSize)
buffer[i++] = temp;
else
{
//Write bufferSize bytes image data to file
if (!client.connected()) break;
client.write(&buffer[0], bufferSize);
i = 0;
buffer[i++] = temp;
}
}
else if ((temp == 0xD8) & (temp_last == 0xFF))
{
is_header = true;
buffer[i++] = temp_last;
buffer[i++] = temp;
}
}
}
void serverCapture() {
start_capture();
Serial.println(F("CAM Capturing"));
int total_time = 0;
total_time = millis();
while (!myCAM.get_bit(ARDUCHIP_TRIG, CAP_DONE_MASK));
total_time = millis() - total_time;
Serial.print(F("capture total_time used (in miliseconds):"));
Serial.println(total_time, DEC);
total_time = 0;
Serial.println(F("CAM Capture Done."));
total_time = millis();
camCapture(myCAM);
total_time = millis() - total_time;
Serial.print(F("send total_time used (in miliseconds):"));
Serial.println(total_time, DEC);
Serial.println(F("CAM send Done."));
}
void serverStream() {
WiFiClient client = server.client();
String response = "HTTP/1.1 200 OK\r\n";
response += "Content-Type: multipart/x-mixed-replace; boundary=frame\r\n\r\n";
server.sendContent(response);
while (1) {
start_capture();
while (!myCAM.get_bit(ARDUCHIP_TRIG, CAP_DONE_MASK));
size_t len = myCAM.read_fifo_length();
if (len >= MAX_FIFO_SIZE) //8M
{
Serial.println(F("Over size."));
continue;
}
if (len == 0 ) //0 kb
{
Serial.println(F("Size is 0."));
continue;
}
myCAM.CS_LOW();
myCAM.set_fifo_burst();
if (!client.connected()) {
client.stop(); is_header = false; break;
}
response = "--frame\r\n";
response += "Content-Type: image/jpeg\r\n\r\n";
server.sendContent(response);
while ( len-- )
{
temp_last = temp;
temp = SPI.transfer(0x00);
//Read JPEG data from FIFO
if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
{
buffer[i++] = temp; //save the last 0XD9
//Write the remain bytes in the buffer
myCAM.CS_HIGH();;
if (!client.connected()) {
client.stop(); is_header = false; break;
}
client.write(&buffer[0], i);
is_header = false;
i = 0;
}
if (is_header == true)
{
//Write image data to buffer if not full
if (i < bufferSize)
buffer[i++] = temp;
else
{
//Write bufferSize bytes image data to file
myCAM.CS_HIGH();
if (!client.connected()) {
client.stop(); is_header = false; break;
}
client.write(&buffer[0], bufferSize);
i = 0;
buffer[i++] = temp;
myCAM.CS_LOW();
myCAM.set_fifo_burst();
}
}
else if ((temp == 0xD8) & (temp_last == 0xFF))
{
is_header = true;
buffer[i++] = temp_last;
buffer[i++] = temp;
}
}
if (!client.connected()) {
client.stop(); is_header = false; break;
}
}
}
void handleNotFound() {
String message = "Server is running!\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
server.send(200, "text/plain", message);
if (server.hasArg("ql")) {
int ql = server.arg("ql").toInt();
#if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
myCAM.OV2640_set_JPEG_size(ql);
#elif defined (OV5640_MINI_5MP_PLUS) || defined (OV5640_CAM)
myCAM.OV5640_set_JPEG_size(ql);
#elif defined (OV5642_MINI_5MP_PLUS) || defined (OV5642_MINI_5MP_BIT_ROTATION_FIXED) ||(defined (OV5642_CAM))
myCAM.OV5642_set_JPEG_size(ql);
#endif
delay(1000);
Serial.println("QL change to: " + server.arg("ql"));
}
}
void setup() {
uint8_t vid, pid;
uint8_t temp;
#if defined(__SAM3X8E__)
Wire1.begin();
#else
Wire.begin();
#endif
Serial.begin(115200);
Serial.println(F("ArduCAM Start!"));
//set the CS as an output:
pinMode(CS, OUTPUT);
pinMode(CAM_POWER_ON , OUTPUT);
digitalWrite(CAM_POWER_ON, HIGH);
// initialize SPI:
SPI.begin();
SPI.setFrequency(4000000); //4MHz
//Check if the ArduCAM SPI bus is OK
myCAM.write_reg(ARDUCHIP_TEST1, 0x55);
temp = myCAM.read_reg(ARDUCHIP_TEST1);
if (temp != 0x55) {
Serial.println(F("SPI1 interface Error!"));
while (1);
}
#if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
//Check if the camera module type is OV2640
myCAM.wrSensorReg8_8(0xff, 0x01);
myCAM.rdSensorReg8_8(OV2640_CHIPID_HIGH, &vid);
myCAM.rdSensorReg8_8(OV2640_CHIPID_LOW, &pid);
if ((vid != 0x26 ) && (( pid != 0x41 ) || ( pid != 0x42 )))
Serial.println(F("Can't find OV2640 module!"));
else
Serial.println(F("OV2640 detected."));
#elif defined (OV5640_MINI_5MP_PLUS) || defined (OV5640_CAM)
//Check if the camera module type is OV5640
myCAM.wrSensorReg16_8(0xff, 0x01);
myCAM.rdSensorReg16_8(OV5640_CHIPID_HIGH, &vid);
myCAM.rdSensorReg16_8(OV5640_CHIPID_LOW, &pid);
if ((vid != 0x56) || (pid != 0x40))
Serial.println(F("Can't find OV5640 module!"));
else
Serial.println(F("OV5640 detected."));
#elif defined (OV5642_MINI_5MP_PLUS) || defined (OV5642_MINI_5MP) || defined (OV5642_MINI_5MP_BIT_ROTATION_FIXED) ||(defined (OV5642_CAM))
//Check if the camera module type is OV5642
myCAM.wrSensorReg16_8(0xff, 0x01);
myCAM.rdSensorReg16_8(OV5642_CHIPID_HIGH, &vid);
myCAM.rdSensorReg16_8(OV5642_CHIPID_LOW, &pid);
if ((vid != 0x56) || (pid != 0x42)) {
Serial.println(F("Can't find OV5642 module!"));
}
else
Serial.println(F("OV5642 detected."));
#endif
//Change to JPEG capture mode and initialize the OV2640 module
myCAM.set_format(JPEG);
myCAM.InitCAM();
#if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
myCAM.OV2640_set_JPEG_size(OV2640_320x240);
#elif defined (OV5640_MINI_5MP_PLUS) || defined (OV5640_CAM)
myCAM.write_reg(ARDUCHIP_TIM, VSYNC_LEVEL_MASK); //VSYNC is active HIGH
myCAM.OV5640_set_JPEG_size(OV5640_320x240);
#elif defined (OV5642_MINI_5MP_PLUS) || defined (OV5642_MINI_5MP) || defined (OV5642_MINI_5MP_BIT_ROTATION_FIXED) ||(defined (OV5642_CAM))
myCAM.write_reg(ARDUCHIP_TIM, VSYNC_LEVEL_MASK); //VSYNC is active HIGH
myCAM.OV5640_set_JPEG_size(OV5642_320x240);
#endif
myCAM.clear_fifo_flag();
if (wifiType == 0) {
if (!strcmp(ssid, "SSID")) {
Serial.println(F("Please set your SSID"));
while (1);
}
if (!strcmp(password, "PASSWORD")) {
Serial.println(F("Please set your PASSWORD"));
while (1);
}
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print(F("Connecting to "));
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(F("."));
}
Serial.println(F("WiFi connected"));
Serial.println("");
Serial.println(WiFi.localIP());
} else if (wifiType == 1) {
Serial.println();
Serial.println();
Serial.print(F("Share AP: "));
Serial.println(AP_ssid);
Serial.print(F("The password is: "));
Serial.println(AP_password);
WiFi.mode(WIFI_AP);
WiFi.softAP(AP_ssid, AP_password);
Serial.println("");
Serial.println(WiFi.softAPIP());
}
// Start the server
server.on("/capture", HTTP_GET, serverCapture);
server.on("/stream", HTTP_GET, serverStream);
server.onNotFound(handleNotFound);
server.begin();
Serial.println(F("Server started"));
}
void loop() {
server.handleClient();
}

View File

@@ -0,0 +1,443 @@
// ArduCAM Mini demo (C)2018 Lee
// Web: http://www.ArduCAM.com
// This program is a demo of how to use most of the functions
// of the library with ArduCAM Mini camera, and can run on any Arduino platform.
// This demo was made for ArduCAM_Mini_2MP_Plus.
// It needs to be used in combination with PC software.
// It can take photo continuously as video streaming.
//
// The demo sketch will do the following tasks:
// 1. Set the camera to JPEG output mode.
// 2. Read data from Serial port and deal with it
// 3. If receive 0x00-0x08,the resolution will be changed.
// 4. If receive 0x10,camera will capture a JPEG photo and buffer the image to FIFO.Then write datas to Serial port.
// 5. If receive 0x20,camera will capture JPEG photo and write datas continuously.Stop when receive 0x21.
// 6. If receive 0x30,camera will capture a BMP photo and buffer the image to FIFO.Then write datas to Serial port.
// 7. If receive 0x11 ,set camera to JPEG output mode.
// 8. If receive 0x31 ,set camera to BMP output mode.
// This program requires the ArduCAM V4.0.0 (or later) library and ArduCAM_Mini_5MP_Plus
// and use Arduino IDE 1.6.8 compiler or above
#include <Wire.h>
#include <ArduCAM.h>
#include <SPI.h>
#include "memorysaver.h"
//This demo can only work on OV2640_MINI_2MP or OV5642_MINI_5MP or OV5642_MINI_5MP_BIT_ROTATION_FIXED platform.
//This demo can only work on OV2640_MINI_2MP or ARDUCAM_SHIELD_V2 platform.
#if !(defined (OV2640_MINI_2MP)||defined (OV5640_MINI_5MP_PLUS) || defined (OV5642_MINI_5MP_PLUS) \
|| defined (OV5642_MINI_5MP) || defined (OV5642_MINI_5MP_BIT_ROTATION_FIXED) \
||(defined (ARDUCAM_SHIELD_V2) && (defined (OV2640_CAM) || defined (OV5640_CAM) || defined (OV5642_CAM))))
#error Please select the hardware platform and camera module in the ../libraries/ArduCAM/memorysaver.h file
#endif
#define BMPIMAGEOFFSET 66
const char bmp_header[BMPIMAGEOFFSET] PROGMEM =
{
0x42, 0x4D, 0x36, 0x58, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x42, 0x00, 0x00, 0x00, 0x28, 0x00,
0x00, 0x00, 0x40, 0x01, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x01, 0x00, 0x10, 0x00, 0x03, 0x00,
0x00, 0x00, 0x00, 0x58, 0x02, 0x00, 0xC4, 0x0E, 0x00, 0x00, 0xC4, 0x0E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x00, 0x00, 0xE0, 0x07, 0x00, 0x00, 0x1F, 0x00,
0x00, 0x00
};
// set pin 7 as the slave select for the digital pot:
const int CS = 7;
bool is_header = false;
int mode = 0;
uint8_t start_capture = 0;
ArduCAM myCAM( OV2640, CS );
uint8_t read_fifo_burst(ArduCAM myCAM);
void setup() {
// put your setup code here, to run once:
uint8_t vid, pid;
uint8_t temp;
#if defined(__SAM3X8E__)
Wire1.begin();
Serial.begin(115200);
#else
Wire.begin();
Serial.begin(115200);
#endif
Serial.println(F("ACK CMD ArduCAM Start! END"));
// set the CS as an output:
pinMode(CS, OUTPUT);
digitalWrite(CS, HIGH);
// initialize SPI:
SPI.begin();
//Reset the CPLD
myCAM.write_reg(0x07, 0x80);
delay(100);
myCAM.write_reg(0x07, 0x00);
delay(100);
while (1) {
//Check if the ArduCAM SPI bus is OK
myCAM.write_reg(ARDUCHIP_TEST1, 0x55);
temp = myCAM.read_reg(ARDUCHIP_TEST1);
if (temp != 0x55) {
Serial.println(F("ACK CMD SPI interface Error!END"));
delay(1000); continue;
} else {
Serial.println(F("ACK CMD SPI interface OK.END")); break;
}
}
#if defined (OV2640_MINI_2MP)
while (1) {
//Check if the camera module type is OV2640
myCAM.wrSensorReg8_8(0xff, 0x01);
myCAM.rdSensorReg8_8(OV2640_CHIPID_HIGH, &vid);
myCAM.rdSensorReg8_8(OV2640_CHIPID_LOW, &pid);
if ((vid != 0x26 ) && (( pid != 0x41 ) || ( pid != 0x42 ))) {
Serial.println(F("ACK CMD Can't find OV2640 module!"));
delay(1000); continue;
}
else {
Serial.println(F("ACK CMD OV2640 detected.END")); break;
}
}
#endif
//Change to JPEG capture mode and initialize the OV5642 module
myCAM.set_format(JPEG);
myCAM.InitCAM();
#if defined (OV2640_MINI_2MP)
myCAM.OV2640_set_JPEG_size(OV2640_320x240);
#endif
delay(1000);
myCAM.clear_fifo_flag();
}
void loop() {
// put your main code here, to run repeatedly:
uint8_t temp = 0xff, temp_last = 0;
bool is_header = false;
if (Serial.available())
{
temp = Serial.read();
switch (temp)
{
case 0:
#if defined (OV2640_MINI_2MP)
myCAM.OV2640_set_JPEG_size(OV2640_160x120); delay(1000);
Serial.println(F("ACK CMD switch to OV2640_160x120END"));
#elif defined (OV3640_MINI_3MP)
myCAM.OV3640_set_JPEG_size(OV3640_176x144); delay(1000);
Serial.println(F("ACK CMD switch to OV2640_160x120END"));
#else
myCAM.OV5642_set_JPEG_size(OV5642_320x240); delay(1000);
Serial.println(F("ACK CMD switch to OV5642_320x240END"));
#endif
temp = 0xff;
break;
case 1:
#if defined (OV2640_MINI_2MP)
myCAM.OV2640_set_JPEG_size(OV2640_176x144); delay(1000);
Serial.println(F("ACK CMD switch to OV2640_176x144END"));
#elif defined (OV3640_MINI_3MP)
myCAM.OV3640_set_JPEG_size(OV3640_320x240); delay(1000);
Serial.println(F("ACK CMD switch to OV3640_320x240END"));
#else
myCAM.OV5642_set_JPEG_size(OV5642_640x480); delay(1000);
Serial.println(F("ACK CMD switch to OV5642_640x480END"));
#endif
temp = 0xff;
break;
case 2:
#if defined (OV2640_MINI_2MP)
myCAM.OV2640_set_JPEG_size(OV2640_320x240); delay(1000);
Serial.println(F("ACK CMD switch to OV2640_320x240END"));
#elif defined (OV3640_MINI_3MP)
myCAM.OV3640_set_JPEG_size(OV3640_352x288); delay(1000);
Serial.println(F("ACK CMD switch to OV3640_352x288END"));
#else
myCAM.OV5642_set_JPEG_size(OV5642_1024x768); delay(1000);
Serial.println(F("ACK CMD switch to OV5642_1024x768END"));
#endif
temp = 0xff;
break;
case 3:
temp = 0xff;
#if defined (OV2640_MINI_2MP)
myCAM.OV2640_set_JPEG_size(OV2640_352x288); delay(1000);
Serial.println(F("ACK CMD switch to OV2640_352x288END"));
#elif defined (OV3640_MINI_3MP)
myCAM.OV3640_set_JPEG_size(OV3640_640x480); delay(1000);
Serial.println(F("ACK CMD switch to OV3640_640x480END"));
#else
myCAM.OV5642_set_JPEG_size(OV5642_1280x960); delay(1000);
Serial.println(F("ACK CMD switch to OV5642_1280x960END"));
#endif
break;
case 4:
temp = 0xff;
#if defined (OV2640_MINI_2MP)
myCAM.OV2640_set_JPEG_size(OV2640_640x480); delay(1000);
Serial.println(F("ACK CMD switch to OV2640_640x480END"));
#elif defined (OV3640_MINI_3MP)
myCAM.OV3640_set_JPEG_size(OV3640_800x600); delay(1000);
Serial.println(F("ACK CMD switch to OV3640_800x600END"));
#else
myCAM.OV5642_set_JPEG_size(OV5642_1600x1200); delay(1000);
Serial.println(F("ACK CMD switch to OV5642_1600x1200END"));
#endif
break;
case 5:
temp = 0xff;
#if defined (OV2640_MINI_2MP)
myCAM.OV2640_set_JPEG_size(OV2640_800x600); delay(1000);
Serial.println(F("ACK CMD switch to OV2640_800x600END"));
#elif defined (OV3640_MINI_3MP)
myCAM.OV3640_set_JPEG_size(OV3640_1024x768); delay(1000);
Serial.println(F("ACK CMD switch to OV3640_1024x768END"));
#else
myCAM.OV5642_set_JPEG_size(OV5642_2048x1536); delay(1000);
Serial.println(F("ACK CMD switch to OV5642_2048x1536END"));
#endif
break;
case 6:
temp = 0xff;
#if defined (OV2640_MINI_2MP)
myCAM.OV2640_set_JPEG_size(OV2640_1024x768); delay(1000);
Serial.println(F("ACK CMD switch to OV2640_1024x768END"));
#elif defined (OV3640_MINI_3MP)
myCAM.OV3640_set_JPEG_size(OV3640_1280x960); delay(1000);
Serial.println(F("ACK CMD switch to OV3640_1280x960END"));
#else
myCAM.OV5642_set_JPEG_size(OV5642_2592x1944); delay(1000);
Serial.println(F("ACK CMD switch to OV5642_2592x1944END"));
#endif
break;
case 7:
temp = 0xff;
#if defined (OV2640_MINI_2MP)
myCAM.OV2640_set_JPEG_size(OV2640_1280x1024); delay(1000);
Serial.println(F("ACK CMD switch to OV2640_1280x1024END"));
#else
myCAM.OV3640_set_JPEG_size(OV3640_1600x1200); delay(1000);
Serial.println(F("ACK CMD switch to OV3640_1600x1200END"));
#endif
break;
case 8:
temp = 0xff;
#if defined (OV2640_MINI_2MP)
myCAM.OV2640_set_JPEG_size(OV2640_1600x1200); delay(1000);
Serial.println(F("ACK CMD switch to OV2640_1600x1200END"));
#else
myCAM.OV3640_set_JPEG_size(OV3640_2048x1536); delay(1000);
Serial.println(F("ACK CMD switch to OV3640_2048x1536END"));
#endif
break;
case 0x10:
mode = 1;
temp = 0xff;
start_capture = 1;
Serial.println(F("ACK CMD CAM start single shoot.END"));
break;
case 0x11:
temp = 0xff;
Serial.println(F("ACK CMD Change OK.END"));
myCAM.set_format(JPEG);
myCAM.InitCAM();
myCAM.OV2640_set_JPEG_size(OV2640_320x240);
break;
case 0x20:
mode = 2;
temp = 0xff;
start_capture = 2;
Serial.println(F("ACK CMD CAM start video streaming.END"));
break;
case 0x30:
mode = 3;
temp = 0xff;
start_capture = 3;
Serial.println(F("ACK CMD CAM start single shoot.END"));
break;
case 0x31:
temp = 0xff;
myCAM.set_format(BMP);
myCAM.InitCAM();
break;
default:
break;
}
}
if (mode == 1)
{
if (start_capture == 1)
{
myCAM.flush_fifo();
myCAM.clear_fifo_flag();
//Start capture
myCAM.start_capture();
start_capture = 0;
}
if (myCAM.get_bit(ARDUCHIP_TRIG, CAP_DONE_MASK))
{
Serial.println(F("ACK CMD CAM Capture Done.END"));
delay(50);
read_fifo_burst(myCAM);
//Clear the capture done flag
myCAM.clear_fifo_flag();
}
}
else if (mode == 2)
{
while (1)
{
temp = Serial.read();
if (temp == 0x21)
{
start_capture = 0;
mode = 0;
Serial.println(F("ACK CMD CAM stop video streaming.END"));
break;
}
if (start_capture == 2)
{
myCAM.flush_fifo();
myCAM.clear_fifo_flag();
//Start capture
myCAM.start_capture();
start_capture = 0;
}
if (myCAM.get_bit(ARDUCHIP_TRIG, CAP_DONE_MASK))
{
uint32_t length = 0;
length = myCAM.read_fifo_length();
if ((length >= MAX_FIFO_SIZE) | (length == 0))
{
myCAM.clear_fifo_flag();
start_capture = 2;
continue;
}
myCAM.CS_LOW();
myCAM.set_fifo_burst();//Set fifo burst mode
temp = SPI.transfer(0x00);
length --;
while ( length-- )
{
temp_last = temp;
temp = SPI.transfer(0x00);
if (is_header == true)
{
Serial.write(temp);
}
else if ((temp == 0xD8) & (temp_last == 0xFF))
{
is_header = true;
Serial.println(F("ACK CMD IMG END"));
Serial.write(temp_last);
Serial.write(temp);
}
if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
break;
delayMicroseconds(15);
}
myCAM.CS_HIGH();
myCAM.clear_fifo_flag();
start_capture = 2;
is_header = false;
}
}
}
else if (mode == 3)
{
if (start_capture == 3)
{
//Flush the FIFO
myCAM.flush_fifo();
myCAM.clear_fifo_flag();
//Start capture
myCAM.start_capture();
start_capture = 0;
}
if (myCAM.get_bit(ARDUCHIP_TRIG, CAP_DONE_MASK))
{
Serial.println(F("ACK CMD CAM Capture Done.END"));
delay(50);
uint8_t temp, temp_last;
uint32_t length = 0;
length = myCAM.read_fifo_length();
if (length >= MAX_FIFO_SIZE )
{
Serial.println(F("ACK CMD Over size.END"));
myCAM.clear_fifo_flag();
return;
}
if (length == 0 ) //0 kb
{
Serial.println(F("ACK CMD Size is 0.END"));
myCAM.clear_fifo_flag();
return;
}
myCAM.CS_LOW();
myCAM.set_fifo_burst();//Set fifo burst mode
Serial.write(0xFF);
Serial.write(0xAA);
for (temp = 0; temp < BMPIMAGEOFFSET; temp++)
{
Serial.write(pgm_read_byte(&bmp_header[temp]));
}
char VH, VL;
int i = 0, j = 0;
for (i = 0; i < 240; i++)
{
for (j = 0; j < 320; j++)
{
VH = SPI.transfer(0x00);;
VL = SPI.transfer(0x00);;
Serial.write(VL);
delayMicroseconds(12);
Serial.write(VH);
delayMicroseconds(12);
}
}
Serial.write(0xBB);
Serial.write(0xCC);
myCAM.CS_HIGH();
//Clear the capture done flag
myCAM.clear_fifo_flag();
}
}
}
uint8_t read_fifo_burst(ArduCAM myCAM)
{
uint8_t temp = 0, temp_last = 0;
uint32_t length = 0;
length = myCAM.read_fifo_length();
Serial.println(length, DEC);
if (length >= MAX_FIFO_SIZE) //512 kb
{
Serial.println(F("ACK CMD Over size.END"));
return 0;
}
if (length == 0 ) //0 kb
{
Serial.println(F("ACK CMD Size is 0.END"));
return 0;
}
myCAM.CS_LOW();
myCAM.set_fifo_burst();//Set fifo burst mode
temp = SPI.transfer(0x00);
length --;
while ( length-- )
{
temp_last = temp;
temp = SPI.transfer(0x00);
if (is_header == true)
{
Serial.write(temp);
}
else if ((temp == 0xD8) & (temp_last == 0xFF))
{
is_header = true;
Serial.println(F("ACK CMD IMG END"));
Serial.write(temp_last);
Serial.write(temp);
}
if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
break;
delayMicroseconds(15);
}
myCAM.CS_HIGH();
is_header = false;
return 1;
}

Submodule Arduino-ESP8266-Secure-Http-Azure-IoT-Hub-Client added at 4939ad928a

Binary file not shown.

248
BMP085_TEST/BMP085.cpp Executable file
View File

@@ -0,0 +1,248 @@
/****************************************************************************
* BMP085.cpp - BMP085/I2C (Digital Pressure Sensor) library for Arduino *
* Copyright 2010-2012 Filipe Vieira & various contributors *
* *
* This file is part of BMP085 Arduino library. *
* *
* This library is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************/
/****************************************************************************
* Tested on Arduino Mega with BMP085 Breakout *
* SDA -> pin 20 (no pull up resistors) *
* SCL -> pin 21 (no pull up resistors) *
* XCLR -> not connected *
* EOC -> not connected *
* GND -> pin GND *
* VCC -> pin 3.3V *
* NOTE: SCL and SDA needs pull-up resistors for each I2C bus. *
* 2.2kOhm..10kOhm, typ. 4.7kOhm *
*****************************************************************************/
#include <Wire.h>
#include "BMP085.h"
BMP085::BMP085() {
_dev_address = BMP085_ADDR;
_pressure_waittime[0] = 5; // These are maximum convertion times.
_pressure_waittime[1] = 8; // It is possible to use pin EOC (End Of Conversion)
_pressure_waittime[2] = 14;// to check if conversion is finished (logic 1)
_pressure_waittime[3] = 26;// or running (logic 0) insted of waiting for convertion times.
_cm_Offset = 0;
_Pa_Offset = 0; // 1hPa = 100Pa = 1mbar
oldEMA = 0;
}
void BMP085::init() {
init(MODE_STANDARD, 0, true);
}
void BMP085::init(byte _BMPMode, int32_t _initVal, bool _Unitmeters){
getCalData(); // initialize cal data
calcTrueTemperature(); // initialize b5
setMode(_BMPMode);
_Unitmeters ? setLocalAbsAlt(_initVal) : setLocalPressure(_initVal);
}
byte BMP085::getDevAddr() {
return _dev_address;
}
byte BMP085::getMode(){
return _oss;
}
void BMP085::setMode(byte _BMPMode){
_oss = _BMPMode;
}
void BMP085::setLocalPressure(int32_t _Pa){
int32_t tmp_alt;
_param_datum = _Pa;
getAltitude(&tmp_alt); // calc altitude based on current pressure
_param_centimeters = tmp_alt;
}
void BMP085::setLocalAbsAlt(int32_t _centimeters){
int32_t tmp_Pa;
_param_centimeters = _centimeters;
getPressure(&tmp_Pa); // calc pressure based on current altitude
_param_datum = tmp_Pa;
}
void BMP085::setAltOffset(int32_t _centimeters){
_cm_Offset = _centimeters;
}
void BMP085::sethPaOffset(int32_t _Pa){
_Pa_Offset = _Pa;
}
void BMP085::zeroCal(int32_t _Pa, int32_t _centimeters){
setAltOffset(_centimeters - _param_centimeters);
sethPaOffset(_Pa - _param_datum);
}
void BMP085::getPressure(int32_t *_Pa){
long TruePressure;
calcTruePressure(&TruePressure);
*_Pa = TruePressure / pow((1 - (float)_param_centimeters / 4433000), 5.255) + _Pa_Offset;
// converting from float to int32_t truncates toward zero, 1010.999985 becomes 1010 resulting in 1 Pa error (max).
// Note that BMP085 abs accuracy from 700...1100hPa and 0..+65<36>C is +-100Pa (typ.)
}
void BMP085::getAltitude(int32_t *_centimeters){
long TruePressure;
calcTruePressure(&TruePressure);
*_centimeters = 4433000 * (1 - pow((TruePressure / (float)_param_datum), 0.1903)) + _cm_Offset;
// converting from float to int32_t truncates toward zero, 100.999985 becomes 100 resulting in 1 cm error (max).
}
void BMP085::getTemperature(int32_t *_Temperature) {
calcTrueTemperature(); // force b5 update
*_Temperature = ((b5 + 8) >> 4);
}
void BMP085::calcTrueTemperature(){
long ut,x1,x2;
//read Raw Temperature
writemem(CONTROL, READ_TEMPERATURE);
delay(5); // min. 4.5ms read Temp delay
readmem(CONTROL_OUTPUT, 2, _buff);
ut = ((long)_buff[0] << 8 | ((long)_buff[1])); // uncompensated temperature value
// calculate temperature
x1 = ((long)ut - ac6) * ac5 >> 15;
x2 = ((long)mc << 11) / (x1 + md);
b5 = x1 + x2;
}
void BMP085::calcTruePressure(long *_TruePressure) {
long up,x1,x2,x3,b3,b6,p;
unsigned long b4,b7;
int32_t tmp;
#if AUTO_UPDATE_TEMPERATURE
calcTrueTemperature(); // b5 update
#endif
//read Raw Pressure
writemem(CONTROL, READ_PRESSURE+(_oss << 6));
delay(_pressure_waittime[_oss]);
readmem(CONTROL_OUTPUT, 3, _buff);
up = ((((long)_buff[0] <<16) | ((long)_buff[1] <<8) | ((long)_buff[2])) >> (8-_oss)); // uncompensated pressure value
// calculate true pressure
b6 = b5 - 4000; // b5 is updated by calcTrueTemperature().
x1 = (b2* (b6 * b6 >> 12)) >> 11;
x2 = ac2 * b6 >> 11;
x3 = x1 + x2;
tmp = ac1;
tmp = (tmp * 4 + x3) << _oss;
b3 = (tmp + 2) >> 2;
x1 = ac3 * b6 >> 13;
x2 = (b1 * (b6 * b6 >> 12)) >> 16;
x3 = ((x1 + x2) + 2) >> 2;
b4 = (ac4 * (uint32_t) (x3 + 32768)) >> 15;
b7 = ((uint32_t)up - b3) * (50000 >> _oss);
p = b7 < 0x80000000 ? (b7 << 1) / b4 : (b7 / b4) << 1;
x1 = (p >> 8) * (p >> 8);
x1 = (x1 * 3038) >> 16;
x2 = (-7357 * p) >> 16;
*_TruePressure = p + ((x1 + x2 + 3791) >> 4);
}
void BMP085::dumpCalData() {
Serial.println("---cal data start---");
Serial.print("ac1:");
Serial.println(ac1,DEC);
Serial.print("ac2:");
Serial.println(ac2,DEC);
Serial.print("ac3:");
Serial.println(ac3,DEC);
Serial.print("ac4:");
Serial.println(ac4,DEC);
Serial.print("ac5:");
Serial.println(ac5,DEC);
Serial.print("ac6:");
Serial.println(ac6,DEC);
Serial.print("b1:");
Serial.println(b1,DEC);
Serial.print("b2:");
Serial.println(b2,DEC);
Serial.print("mb:");
Serial.println(mb,DEC);
Serial.print("mc:");
Serial.println(mc,DEC);
Serial.print("md:");
Serial.println(md,DEC);
Serial.println("---cal data end---");
}
//PRIVATE methods
void BMP085::getCalData() {
readmem(CAL_AC1, 2, _buff);
ac1 = ((int)_buff[0] <<8 | ((int)_buff[1]));
readmem(CAL_AC2, 2, _buff);
ac2 = ((int)_buff[0] <<8 | ((int)_buff[1]));
readmem(CAL_AC3, 2, _buff);
ac3 = ((int)_buff[0] <<8 | ((int)_buff[1]));
readmem(CAL_AC4, 2, _buff);
ac4 = ((unsigned int)_buff[0] <<8 | ((unsigned int)_buff[1]));
readmem(CAL_AC5, 2, _buff);
ac5 = ((unsigned int)_buff[0] <<8 | ((unsigned int)_buff[1]));
readmem(CAL_AC6, 2, _buff);
ac6 = ((unsigned int)_buff[0] <<8 | ((unsigned int)_buff[1]));
readmem(CAL_B1, 2, _buff);
b1 = ((int)_buff[0] <<8 | ((int)_buff[1]));
readmem(CAL_B2, 2, _buff);
b2 = ((int)_buff[0] <<8 | ((int)_buff[1]));
readmem(CAL_MB, 2, _buff);
mb = ((int)_buff[0] <<8 | ((int)_buff[1]));
readmem(CAL_MC, 2, _buff);
mc = ((int)_buff[0] <<8 | ((int)_buff[1]));
readmem(CAL_MD, 2, _buff);
md = ((int)_buff[0] <<8 | ((int)_buff[1]));
}
void BMP085::writemem(uint8_t _addr, uint8_t _val) {
Wire.beginTransmission(_dev_address); // start transmission to device
Wire.write(_addr); // send register address
Wire.write(_val); // send value to write
Wire.endTransmission(); // end transmission
}
void BMP085::readmem(uint8_t _addr, uint8_t _nbytes, uint8_t __buff[]) {
Wire.beginTransmission(_dev_address); // start transmission to device
Wire.write(_addr); // sends register address to read from
Wire.endTransmission(); // end transmission
Wire.beginTransmission(_dev_address); // start transmission to device
Wire.requestFrom(_dev_address, _nbytes);// send data n-bytes read
uint8_t i = 0;
while (Wire.available()) {
__buff[i] = Wire.read(); // receive DATA
i++;
}
Wire.endTransmission(); // end transmission
}

142
BMP085_TEST/BMP085.h Executable file
View File

@@ -0,0 +1,142 @@
/****************************************************************************
* BMP085.h - BMP085/I2C (Digital Pressure Sensor) library for Arduino *
* Copyright 2010-2012 Filipe Vieira & various contributors *
* *
* This file is part of BMP085 Arduino library. *
* *
* This library is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************/
/****************************************************************************
* Tested on Arduino Mega with BMP085 Breakout *
* SDA -> pin 20 (no pull up resistors) *
* SCL -> pin 21 (no pull up resistors) *
* XCLR -> not connected *
* EOC -> not connected *
* GND -> pin GND *
* VCC -> pin 3.3V *
* NOTE: SCL and SDA needs pull-up resistors for each I2C bus. *
* 2.2kOhm..10kOhm, typ. 4.7kOhm *
*****************************************************************************/
#ifndef BMP085_h
#define BMP085_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#define BMP085_ADDR 0x77 //0x77 default I2C address
#define BUFFER_SIZE 3
#define AUTO_UPDATE_TEMPERATURE true //default is true
// when true, temperature is measured everytime pressure is measured (Auto).
// when false, user chooses when to measure temperature (just call calcTrueTemperature()).
// used for dynamic measurement to increase sample rate (see BMP085 modes below).
/* ---- Registers ---- */
#define CAL_AC1 0xAA // R Calibration data (16 bits)
#define CAL_AC2 0xAC // R Calibration data (16 bits)
#define CAL_AC3 0xAE // R Calibration data (16 bits)
#define CAL_AC4 0xB0 // R Calibration data (16 bits)
#define CAL_AC5 0xB2 // R Calibration data (16 bits)
#define CAL_AC6 0xB4 // R Calibration data (16 bits)
#define CAL_B1 0xB6 // R Calibration data (16 bits)
#define CAL_B2 0xB8 // R Calibration data (16 bits)
#define CAL_MB 0xBA // R Calibration data (16 bits)
#define CAL_MC 0xBC // R Calibration data (16 bits)
#define CAL_MD 0xBE // R Calibration data (16 bits)
#define CONTROL 0xF4 // W Control register
#define CONTROL_OUTPUT 0xF6 // R Output registers 0xF6=MSB, 0xF7=LSB, 0xF8=XLSB
// unused registers
#define SOFTRESET 0xE0
#define VERSION 0xD1 // ML_VERSION pos=0 len=4 msk=0F AL_VERSION pos=4 len=4 msk=f0
#define CHIPID 0xD0 // pos=0 mask=FF len=8
// BMP085_CHIP_ID=0x55
/************************************/
/* REGISTERS PARAMETERS */
/************************************/
// BMP085 Modes
#define MODE_ULTRA_LOW_POWER 0 //oversampling=0, internalsamples=1, maxconvtimepressure=4.5ms, avgcurrent=3uA, RMSnoise_hPA=0.06, RMSnoise_m=0.5
#define MODE_STANDARD 1 //oversampling=1, internalsamples=2, maxconvtimepressure=7.5ms, avgcurrent=5uA, RMSnoise_hPA=0.05, RMSnoise_m=0.4
#define MODE_HIGHRES 2 //oversampling=2, internalsamples=4, maxconvtimepressure=13.5ms, avgcurrent=7uA, RMSnoise_hPA=0.04, RMSnoise_m=0.3
#define MODE_ULTRA_HIGHRES 3 //oversampling=3, internalsamples=8, maxconvtimepressure=25.5ms, avgcurrent=12uA, RMSnoise_hPA=0.03, RMSnoise_m=0.25
// "Sampling rate can be increased to 128 samples per second (standard mode) for
// dynamic measurement.In this case it is sufficient to measure temperature only
// once per second and to use this value for all pressure measurements during period."
// (from BMP085 datasheet Rev1.2 page 10).
// To use dynamic measurement set AUTO_UPDATE_TEMPERATURE to false and
// call calcTrueTemperature() from your code.
// Control register
#define READ_TEMPERATURE 0x2E
#define READ_PRESSURE 0x34
//Other
#define MSLP 101325 // Mean Sea Level Pressure = 1013.25 hPA (1hPa = 100Pa = 1mbar)
class BMP085 {
public:
BMP085();
// BMP initialization
void init(); // sets current elevation above ground level to 0 meters
void init(byte _BMPMode, int32_t _initVal, bool _centimeters); // sets a reference datum
// if _centimeters=false _initVal is Pa
// Who Am I
byte getDevAddr();
// BMP mode
byte getMode();
void setMode(byte _BMPMode); // BMP085 mode
// initialization
void setLocalPressure(int32_t _Pa); // set known barometric pressure as reference Ex. QNH
void setLocalAbsAlt(int32_t _centimeters); // set known altitude as reference
void setAltOffset(int32_t _centimeters); // altitude offset
void sethPaOffset(int32_t _Pa); // pressure offset
void zeroCal(int32_t _Pa, int32_t _centimeters);// zero Calibrate output to a specific Pa/altitude
// BMP Sensors
void getPressure(int32_t *_Pa); // pressure in Pa + offset
void getAltitude(int32_t *_centimeters); // altitude in centimeters + offset
void getTemperature(int32_t *_Temperature); // temperature in C<>
void calcTrueTemperature(); // calc temperature data b5 (only needed if AUTO_UPDATE_TEMPERATURE is false)
void calcTruePressure(long *_TruePressure); // calc Pressure in Pa
// dummy stuff
void dumpCalData(); // debug only
void writemem(uint8_t _addr, uint8_t _val);
void readmem(uint8_t _addr, uint8_t _nbytes, uint8_t __buff[]);
private:
int ac1,ac2,ac3,b1,b2,mb,mc,md; // cal data
unsigned int ac4,ac5,ac6; // cal data
long b5, oldEMA; // temperature data
uint8_t _dev_address;
byte _buff[BUFFER_SIZE]; // buffer MSB LSB XLSB
int _oss; // OverSamplingSetting
int _pressure_waittime[4]; // Max. Conversion Time Pressure is ms for each mode
int32_t _cm_Offset, _Pa_Offset;
int32_t _param_datum, _param_centimeters;
void getCalData();
};
#endif

44
BMP085_TEST/BMP085_TEST.ino Executable file
View File

@@ -0,0 +1,44 @@
// BMP085_test1
// by Filipe Vieira
// Simple test of BMP085 output using default settings.
// This example requires AUTO_UPDATE_TEMPERATURE to be true in bmp085.h otherwise temperature will not update.
// IMPORTANT!! To get correct values you MUST CHANGE init() parameters, in
// this example I've set 250m based on GPS data for my location.
#include <Wire.h>
#include "BMP085.h"
BMP085 dps = BMP085(); // Digital Pressure Sensor
long Temperature = 0, Pressure = 0, Altitude = 0;
void setup(void) {
Serial.begin(9600);
Wire.begin();
delay(1000);
// uncomment for different initialization settings
//dps.init(); // QFE (Field Elevation above ground level) is set to 0 meters.
// same as init(MODE_STANDARD, 0, true);
//dps.init(MODE_STANDARD, 101850, false); // 101850Pa = 1018.50hPa, false = using Pa units
// this initialization is useful for normalizing pressure to specific datum.
// OR setting current local hPa information from a weather station/local airport (QNH).
dps.init(MODE_ULTRA_HIGHRES, 25000, true); // 250 meters, true = using meter units
// this initialization is useful if current altitude is known,
// pressure will be calculated based on TruePressure and known altitude.
// note: use zeroCal only after initialization.
// dps.zeroCal(101800, 0); // set zero point
}
void loop(void) {
dps.getPressure(&Pressure);
dps.getAltitude(&Altitude);
Serial.print(" Alt(cm):");
Serial.print(Altitude);
Serial.print(" Pressure(Pa):");
Serial.println(Pressure);
}

138
BMP180/BMP180.ino Executable file
View File

@@ -0,0 +1,138 @@
// adapted sketch by niq_ro from http://nicuflorica.blogspot.ro/ & http://arduinotehniq.blogspot.com/
// https://github.com/adafruit/Adafruit-BMP085-Library
#include <Wire.h>
#include <Adafruit_BMP085.h>
/***************************************************
This is an example for the BMP085 Barometric Pressure & Temp Sensor
Designed specifically to work with the Adafruit BMP085 Breakout
----> https://www.adafruit.com/products/391
These displays use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
// Connect VCC of the BMP085 sensor to 3.3V (NOT 5.0V!)
// Connect GND to Ground
// Connect SCL to i2c clock - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 5
// Connect SDA to i2c data - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 4
// EOC is not used, it signifies an end of conversion
// XCLR is a reset pin, also not used here
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
/* -------------------
| LCD | Arduino |
-------------------
LCD RS pin to digital pin 7 | RS | D7 |
LCD Enable pin to digital pin 6 | E | D6 |
LCD D4 pin to digital pin 5 | D4 | D6 |
LCD D5 pin to digital pin 4 | D5 | D4 |
LCD D6 pin to digital pin 3 | D6 | D3 |
LCD D7 pin to digital pin 2 | D7 | D2 |
LCD R/W pin to ground | R/W | GND |
-------------------
*/
Adafruit_BMP085 bmp;
void setup() {
lcd.begin(16, 2);
// Print a logo message to the LCD.
lcd.print("www.tehnic.go.ro");
lcd.setCursor(0, 1);
lcd.print("creat de niq_ro");
delay (2500);
lcd.clear();
// Print another message to the LCD.
lcd.setCursor(2, 0);
lcd.print("Thermometre -");
lcd.setCursor(0, 1);
lcd.print("barometre ver1.0");
delay (2500);
lcd.clear();
Serial.begin(9600);
if (!bmp.begin()) {
Serial.println("nu exita senzor compatibil BMP085 sau BMP180");
while (1) {}
}
}
void loop() {
Serial.print("Temperature = ");
Serial.print(bmp.readTemperature());
Serial.println(" *C");
Serial.print("Pression = ");
Serial.print(bmp.readPressure());
Serial.print(" Pa / ");
// Serial.print("Presiune = ");
float pression = bmp.readPressure()/101.325;
pression = pression * 0.760;
Serial.print(pression);
Serial.println(" mmHg");
// Calculate altitude assuming 'standard' barometric
// pressure of 1013.25 millibar = 101325 Pascal
Serial.print("Altitude = ");
Serial.print(bmp.readAltitude());
Serial.println(" m");
Serial.print("Pression au niveau de la mer (calculée) = ");
Serial.print(bmp.readSealevelPressure());
Serial.print(" Pa / ");
// http://en.wikipedia.org/wiki/Atmospheric_pressure#Mean_sea_level_pressure
// Serial.print("Presiure la nivelul marii (calculata) = ");
float presiune = bmp.readSealevelPressure()/101.325;
presiune = presiune * 0.760;
Serial.print(presiune);
Serial.println(" mmHg");
// you can get a more precise measurement of altitude
// if you know the current sea level pressure which will
// vary with weather and such. If it is 1015 millibars
// that is equal to 101500 Pascals.
Serial.print("Altitude réelle = ");
Serial.print(bmp.readAltitude(101500));
Serial.println(" m");
Serial.println();
lcd.setCursor(1, 0);
lcd.print("temp.= ");
if ( bmp.readTemperature() < 10)
{
lcd.print(" ");
lcd.print(bmp.readTemperature());
}
else
{
lcd.print(bmp.readTemperature(),1);
}
lcd.write(0b11011111);
lcd.print("C ");
lcd.setCursor(1, 1);
lcd.print("pres.= p");
lcd.print(presiune,0);
lcd.print("mmHg ");
delay(2500);
}

103
Blink/Blink.ino Executable file
View File

@@ -0,0 +1,103 @@
/*
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 11. If you're unsure what
pin the on-board LED is connected to on your Arduino model, check
the documentation at http://arduino.cc
This example code is in the public domain.
modified 8 May 2014
by Scott Fitzgerald
*/
#include <RCSwitch.h>
boolean started = false;
int id = 0;
RCSwitch mySwitch = RCSwitch();
// Cas
// 12 = Courant général 0 éteint 1 allumé
// 11 = Mode radiateur 0 hors gel 1 confort
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 11 as an output.
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
digitalWrite(11, HIGH);
digitalWrite(12, HIGH);
Serial.begin(9600);
mySwitch.enableReceive(0); // Receiver on inerrupt 0 => that is pin #2
}
void loop() {
if (mySwitch.available()) {
int value = mySwitch.getReceivedValue();
if (value == 0) {
Serial.print("Unknown encoding");
} else {
long data = mySwitch.getReceivedValue();
//Serial.print("Received ");
//Serial.print( data );
// Serial.print(" / ");
// Serial.print( mySwitch.getReceivedBitlength() );
// Serial.print("bit ");
// Serial.print("Protocol: ");
// Serial.println( mySwitch.getReceivedProtocol() );
//Serial.println("");
//delay(1000); // wait for a second
if (data == 111269) {
started = true;
// id = 0;
//Serial.println("started");
} else if (data == 962111) {
started = false;
id = 0;
//Serial.println("Arret");
} else if (data == 1969 || data == 2069 || data == 2169 || data == 2269) {
//Serial.print("id=");
//Serial.println(data);
// if (id == 0) {
id = data;
// } else {
// started = false;
// id = 0;
// }
} else {
if (started && id == 1969) {
Serial.print("Demarré ");
Serial.print("id=");
Serial.print(id);
Serial.print(" data=");
Serial.println(data);
//
if (data >= 1800) {
digitalWrite(11, HIGH);
digitalWrite(12, HIGH);
Serial.println("HIGH");
// delay(2000);
} else if (data > 1200) {
digitalWrite(11, LOW);
digitalWrite(12, LOW);
Serial.println("LOW");
//delay(2000);
}
}
}
}
mySwitch.resetAvailable();
}
}

View File

@@ -0,0 +1,27 @@
#include <ELECHOUSE_CC1101.h>
void setup()
{
Serial.begin(9600);
ELECHOUSE_cc1101.Init();
ELECHOUSE_cc1101.SetReceive();
}
byte RX_buffer[61]={0};
byte size,i,flag;
void loop()
{
if(ELECHOUSE_cc1101.CheckReceiveFlag())
{
size=ELECHOUSE_cc1101.ReceiveData(RX_buffer);
for(i=0;i<size;i++)
{
Serial.print(RX_buffer[i],DEC);
Serial.print(' ',BYTE);
}
Serial.println("");
ELECHOUSE_cc1101.SetReceive();
}
}

View File

@@ -0,0 +1,87 @@
#include "EEPROM.h"
#include "cc1101.h"
//Arduino GND <-> CC1101 GND
//Arduino VCC (+3.3v) <-> CC1101 VCC
//Arduino 10 <-> CC1101 CSN (SS)
//Arduino 11 <-> CC1101 SI (MOSI)
//Arduino 12 <-> CC1101 SO (MISO)
//Arduino 13 <-> CC1101 SCK
//Arduino 02 <-> CC1101 GD0
CC1101 cc1101;
#define LEDOUTPUT 7
// counter to get increment in each loop
byte counter;
byte b;
byte syncWord = 199;
void blinker(){
digitalWrite(LEDOUTPUT, HIGH);
delay(100);
digitalWrite(LEDOUTPUT, LOW);
delay(100);
}
void setup()
{
Serial.begin(9600);
Serial.println("start");
// setup the blinker output
pinMode(LEDOUTPUT, OUTPUT);
digitalWrite(LEDOUTPUT, LOW);
// blink once to signal the setup
blinker();
// reset the counter
counter=0;
Serial.println("initializing...");
// initialize the RF Chip
cc1101.init();
cc1101.reset();
cc1101.setSyncWord(&syncWord, false);
//cc1101.setCarrierFreq(CFREQ_433);
cc1101.setCarrierFreq(CFREQ_868);
cc1101.disableAddressCheck();
Serial.print("CC1101_PARTNUM "); //cc1101=0
b=cc1101.readReg(CC1101_PARTNUM, CC1101_STATUS_REGISTER);
Serial.println(b);
b=cc1101.readReg(CC1101_VERSION, CC1101_STATUS_REGISTER);
Serial.print("CC1101_VERSION "); //cc1101=4
Serial.println(b);
Serial.print("CC1101_MARCSTATE ");
Serial.println(cc1101.readReg(CC1101_MARCSTATE, CC1101_STATUS_REGISTER) & 0x1f);
Serial.println("device initialized");
}
void send_data() {
CCPACKET data;
data.length=1;
byte blinkCount=counter++;
data.data[0]=blinkCount;
Serial.print("CC1101_MARCSTATE ");
Serial.println(cc1101.readReg(CC1101_MARCSTATE, CC1101_STATUS_REGISTER) & 0x1f);
if(cc1101.sendData(data)){
Serial.print("sent ok :)");
blinker();
}else{
Serial.print("sent failed :(");
blinker();
blinker();
}
}
void loop()
{
send_data();
Serial.println("loop done");
delay(1000);
}

View File

@@ -0,0 +1,92 @@
#include "EEPROM.h"
#include "cc1101.h"
//Arduino GND <-> CC1101 GND
//Arduino VCC (+5v ou 3,3 ?<-> CC1101 VCC
//Arduino 10 <-> CC1101 CSN (SS)
//Arduino 11 <-> CC1101 SI (MOSI)
//Arduino 12 <-> CC1101 SO (MISO)
//Arduino 13 <-> CC1101 SCK
//Arduino 02 <-> CC1101 GD0
CC1101 cc1101;
// The LED is wired to the Arduino Output 4 (physical panStamp pin 19)
#define LEDOUTPUT 7
// counter to get increment in each loop
byte counter;
byte b;
//byte syncWord = 199;
byte syncWord[2] = {199, 0};
void blinker(){
digitalWrite(LEDOUTPUT, HIGH);
delay(100);
digitalWrite(LEDOUTPUT, LOW);
delay(100);
}
void setup()
{
Serial.begin(9600);
Serial.println("start");
// setup the blinker output
pinMode(LEDOUTPUT, OUTPUT);
digitalWrite(LEDOUTPUT, LOW);
// blink once to signal the setup
blinker();
// reset the counter
counter=0;
Serial.println("initializing...");
// initialize the RF Chip
cc1101.init();
//cc1101.setSyncWord(&syncWord, false);
cc1101.setSyncWord(syncWord, false);
cc1101.setCarrierFreq(CFREQ_433);
cc1101.disableAddressCheck();
//cc1101.setTxPowerAmp(PA_LowPower);
delay(1000);
Serial.print("CC1101_PARTNUM "); //cc1101=0
Serial.println(cc1101.readReg(CC1101_PARTNUM, CC1101_STATUS_REGISTER));
Serial.print("CC1101_VERSION "); //cc1101=4
Serial.println(cc1101.readReg(CC1101_VERSION, CC1101_STATUS_REGISTER));
Serial.print("CC1101_MARCSTATE ");
Serial.println(cc1101.readReg(CC1101_MARCSTATE, CC1101_STATUS_REGISTER) & 0x1f);
Serial.println("device initialized");
//Serial.println("done");
}
void send_data() {
CCPACKET data;
data.length=10;
byte blinkCount=counter++;
data.data[0]=5;
data.data[1]=blinkCount;data.data[2]=0;
data.data[3]=1;data.data[4]=0;
//cc1101.flushTxFifo ();
Serial.print("CC1101_MARCSTATE ");
Serial.println(cc1101.readReg(CC1101_MARCSTATE, CC1101_STATUS_REGISTER) & 0x1f);
if(cc1101.sendData(data)){
Serial.print(blinkCount,HEX);
Serial.println(" sent ok :)");
blinker();
}else{
Serial.println("sent failed :(");
blinker();
blinker();
}
}
void loop()
{
send_data();
delay(4000);
}

273
CC1101_OREGON/CC1101_OREGON.ino Executable file
View File

@@ -0,0 +1,273 @@
#include "cc1101.h"
class C1101Receiver : public CC1101
{
enum
{
SS = 10,
MOSI = 11,
MISO = 12,
SCK = 13,
GDO0 = 2
};
public:
C1101Receiver()
{
}
bool Init()
{
CC1101::init(CFREQ_433, 0);
// http://ygorshko.blogspot.sk/2015/04/finally-set-up-c1101-to-receive-oregon.html
CC1101::writeReg(CC1101_FIFOTHR, 0x47); // FIFOTHR: RX FIFO and TX FIFO Thresholds
CC1101::writeReg(CC1101_SYNC1, 0x55); // SYNC1: Sync Word, High Byte
CC1101::writeReg(CC1101_SYNC0, 0x99); // SYNC0: Sync Word, Low Byte
CC1101::writeReg(CC1101_PKTLEN, 0x11); // PKTLEN: Packet Length
CC1101::writeReg(CC1101_PKTCTRL0, 0x04); // PKTCTRL0: Packet Automation Control
CC1101::writeReg(CC1101_FSCTRL1, 0x06); // FSCTRL1: Frequency Synthesizer Control
CC1101::writeReg(CC1101_FREQ2, 0x10); // FREQ2: Frequency Control Word, High Byte
CC1101::writeReg(CC1101_FREQ1, 0xb0); // FREQ1: Frequency Control Word, Middle Byte
CC1101::writeReg(CC1101_FREQ0, 0x71); // FREQ0: Frequency Control Word, Low Byte
CC1101::writeReg(CC1101_MDMCFG4, 0xf6); // MDMCFG4: Modem Configuration
CC1101::writeReg(CC1101_MDMCFG3, 0x4a); // MDMCFG3: Modem Configuration
CC1101::writeReg(CC1101_MDMCFG2, 0x3e); // MDMCFG2: Modem Configuration
CC1101::writeReg(CC1101_DEVIATN, 0x15); // DEVIATN: Modem Deviation Setting
CC1101::writeReg(CC1101_MCSM0, 0x18); // MCSM0: Main Radio Control State Machine Configuration
CC1101::writeReg(CC1101_FOCCFG, 0x16); // FOCCFG: Frequency Offset Compensation Configuration
CC1101::writeReg(CC1101_AGCCTRL2, 0x05); // AGCCTRL2: AGC Control
CC1101::writeReg(CC1101_AGCCTRL1, 0x00); // AGCCTRL1: AGC Control
CC1101::writeReg(CC1101_WORCTRL, 0xfb); // WORCTRL: Wake On Radio Control
CC1101::writeReg(CC1101_FREND0, 0x11); // FREND0: Front End TX Configuration
CC1101::writeReg(CC1101_FSCAL3, 0xe9); // FSCAL3: Frequency Synthesizer Calibration
CC1101::writeReg(CC1101_FSCAL2, 0x2a); // FSCAL2: Frequency Synthesizer Calibration
CC1101::writeReg(CC1101_FSCAL1, 0x00); // FSCAL1: Frequency Synthesizer Calibration
CC1101::writeReg(CC1101_FSCAL0, 0x1f); // FSCAL0: Frequency Synthesizer Calibration
CC1101::writeReg(CC1101_TEST2, 0x81); // TEST2: Various Test Settings
CC1101::writeReg(CC1101_TEST1, 0x35); // TEST1: Various Test Settings
CC1101::writeReg(CC1101_TEST0, 0x09); // TEST0: Various Test Settings
CC1101::setRxState();
CC1101::writeReg(CC1101_MDMCFG4, 0xC8);
CC1101::writeReg(CC1101_MDMCFG3, 0x4A);
CC1101::writeReg(CC1101_MDMCFG2, 0x30);
CC1101::writeReg(CC1101_MDMCFG1, 0x42);
CC1101::writeReg(CC1101_MDMCFG0, 0xF8);
CC1101::writeReg(CC1101_PKTCTRL0, 0x30); // asynchronous serial mode
CC1101::writeReg(CC1101_IOCFG0, 0x0d); // GD0 output
return CC1101::readReg(CC1101_TEST1, CC1101_CONFIG_REGISTER) == 0x35;
}
byte read()
{
return digitalRead(GDO0);
}
};
class CPinReceiver
{
enum {
RxPin = 7
};
public:
void Init()
{
pinMode(5, OUTPUT); digitalWrite(5, 0);
pinMode(6, OUTPUT); digitalWrite(6, 1);
pinMode(RxPin, INPUT);
}
byte read()
{
return digitalRead(RxPin);
}
};
//CReceiver Receiver;
C1101Receiver Receiver;
class COregon
{
public:
enum
{
RxPin = 7,
sDelay = 230,
lDelay = 460,
PacketLength = 10,
HeaderBits = 20
};
bool WaitHeader()
{
return Receiver.read() == 0;
}
bool GetHeader()
{
byte headerHits = 0;
long lTimeout = millis() + 100;
while (1)
{
delayMicroseconds(sDelay);
if (Receiver.read() == 0)
{
delayMicroseconds(lDelay);
if (Receiver.read() == 0)
return false;
headerHits ++;
if (headerHits == HeaderBits)
return true;
}
do
{
if ( millis() > lTimeout )
return false;
} while (Receiver.read()==1);
}
return false; // make sure we look for another header
}
byte ReceivePacket(byte* manchester)
{
// https://github.com/robwlakes/ArduinoWeatherOS/blob/master/Arduino_OS_WeatherV26.ino
boolean logic = 1; // look for rest of header 1's, these must be soaked up intil first 0 arrives to denote start of data
byte signal = 0; //RF Signal is at 0 after 1's 1->0 transition, inverted Manchester (see Wiki, it is a matter of opinion)
boolean firstZero = false; //The first zero is not immediately found, but is flagged when found
boolean test230 = false;
boolean test460 = false;
int nosBytes = 0; //counter for the data bytes required
byte dataByte = 0; //accumulates the bits of the signal
byte dataMask = 16; //rotates, so allows nybbles to be reversed
byte nosBits = 0; //counts the shifted bits in the dataByte
int maxBytes = 10; //sets the limits of how many data bytes will be required
while (1)
{
//now get last of the header, and then store the data after trigger bit 0 arrives, and data train timing remains valid
long lTimeout = millis() + 100;
while (Receiver.read()!=signal)
{ //halt here while signal matches inverse of logic, if prev=1 wait for sig=0
if ( millis() > lTimeout )
{
return 0;
}
}//exits when signal==logic
delayMicroseconds(sDelay); //wait for first 1/4 of a bit pulse
test230 = Receiver.read();//snapshot of the input
if ((test230 == signal)&&(nosBytes < maxBytes)){ //after a wait the signal level is the same, so all good, continue!
delayMicroseconds(lDelay); //wait for second 1/2 of a bit pulse
test460=Receiver.read();//snapshot of the input
if (test230==test460){ // finds a long pulse, so the logic to look for will change, so flip the logic value
//Assuming the manchester encoding, a long pulse means data flips, otherwise data stays the same
logic = logic^1;
signal = signal^1;
if (!firstZero){ //if this is the first 0-1 data transition then is the sync 0
firstZero = true; //flag that legit data has begun
//VIP OS Seems to put the Synch '0' bit into the data, as it causes the rest to align onto byte boundaries
dataByte = B00000000; // set the byte as 1's (just reflects the header bit that have preceded the trigger bit=0)
dataMask = B00010000; // set the byte as 1's (just reflects the header bit that have preceded the trigger bit=0)
nosBits = 0; // preset bit counter so we have 7 bits counted already
}
}
//data stream has been detected begin packing bits into bytes
if (firstZero){
if (logic){
dataByte = dataByte | dataMask; //OR the data bit into the dataByte
}
dataMask = dataMask << 1;//rotate the data bit
if (dataMask==0){
dataMask=1;//make it roll around, is there a cleaner way than this? eg dataMask *=2?
}
nosBits++;
if (nosBits == 8){ //one byte created, so move onto the next one
manchester[nosBytes] = dataByte; //store this byte
nosBits = 0; //found 8, rezero and get another 8
dataByte = 0; //hold the bits in this one
dataMask = 16; //mask to do reversed nybbles on the fly
nosBytes++; //keep a track of how many bytes we have made
}
}
}
else {
//non valid data found, or maxBytes equalled by nosBytes, reset all pointers and exit the while loop
return 0;
}
if (nosBytes == maxBytes)
{
return nosBytes;
}
}
return 0;
}
};
COregon Oregon;
void setup()
{
Serial.begin(38400);
Serial.println("Valky.eu Oregon Decoder " __DATE__ " " __TIME__);
while (!Receiver.Init())
{
Serial.print("Cannot initialize receiver!\n");
delay(1000);
}
}
void debug()
{
static long ltime = 0;
long lcur = millis();
if ( lcur - ltime > 10 )
ltime = lcur;
else
return;
static int q= 0;
if ( q++ == 80 )
{
q = 0;
Serial.print("\n");
}
Serial.print(Receiver.read());
}
void loop()
{
//debug();
if ( Oregon.WaitHeader() )
{
if ( Oregon.GetHeader() )
{
byte buffer[COregon::PacketLength] = {0};
byte received = Oregon.ReceivePacket(buffer);
if ( received )
{
const char hex[] = "0123456789abcdef";
Serial.print("Received buffer: ");
for( int i=0; i < received; i++)
{
Serial.print(hex[buffer[i] >> 4]);
Serial.print(hex[buffer[i] & 15]);
}
Serial.print("\n");
} else
Serial.print("Receive error\n");
}
}
}

View File

@@ -0,0 +1,271 @@
#include "cc1101.h"
class C1101Receiver : public CC1101
{
enum
{
SS = 10,
MOSI = 11,
MISO = 12,
SCK = 13,
GDO0 = 2
};
C1101Receiver()
{
}
bool Init()
{
CC1101::init(CFREQ_433, 0);
// http://ygorshko.blogspot.sk/2015/04/finally-set-up-c1101-to-receive-oregon.html
CC1101::writeReg(CC1101_FIFOTHR, 0x47); // FIFOTHR: RX FIFO and TX FIFO Thresholds
CC1101::writeReg(CC1101_SYNC1, 0x55); // SYNC1: Sync Word, High Byte
CC1101::writeReg(CC1101_SYNC0, 0x99); // SYNC0: Sync Word, Low Byte
CC1101::writeReg(CC1101_PKTLEN, 0x11); // PKTLEN: Packet Length
CC1101::writeReg(CC1101_PKTCTRL0, 0x04); // PKTCTRL0: Packet Automation Control
CC1101::writeReg(CC1101_FSCTRL1, 0x06); // FSCTRL1: Frequency Synthesizer Control
CC1101::writeReg(CC1101_FREQ2, 0x10); // FREQ2: Frequency Control Word, High Byte
CC1101::writeReg(CC1101_FREQ1, 0xb0); // FREQ1: Frequency Control Word, Middle Byte
CC1101::writeReg(CC1101_FREQ0, 0x71); // FREQ0: Frequency Control Word, Low Byte
CC1101::writeReg(CC1101_MDMCFG4, 0xf6); // MDMCFG4: Modem Configuration
CC1101::writeReg(CC1101_MDMCFG3, 0x4a); // MDMCFG3: Modem Configuration
CC1101::writeReg(CC1101_MDMCFG2, 0x3e); // MDMCFG2: Modem Configuration
CC1101::writeReg(CC1101_DEVIATN, 0x15); // DEVIATN: Modem Deviation Setting
CC1101::writeReg(CC1101_MCSM0, 0x18); // MCSM0: Main Radio Control State Machine Configuration
CC1101::writeReg(CC1101_FOCCFG, 0x16); // FOCCFG: Frequency Offset Compensation Configuration
CC1101::writeReg(CC1101_AGCCTRL2, 0x05); // AGCCTRL2: AGC Control
CC1101::writeReg(CC1101_AGCCTRL1, 0x00); // AGCCTRL1: AGC Control
CC1101::writeReg(CC1101_WORCTRL, 0xfb); // WORCTRL: Wake On Radio Control
CC1101::writeReg(CC1101_FREND0, 0x11); // FREND0: Front End TX Configuration
CC1101::writeReg(CC1101_FSCAL3, 0xe9); // FSCAL3: Frequency Synthesizer Calibration
CC1101::writeReg(CC1101_FSCAL2, 0x2a); // FSCAL2: Frequency Synthesizer Calibration
CC1101::writeReg(CC1101_FSCAL1, 0x00); // FSCAL1: Frequency Synthesizer Calibration
CC1101::writeReg(CC1101_FSCAL0, 0x1f); // FSCAL0: Frequency Synthesizer Calibration
CC1101::writeReg(CC1101_TEST2, 0x81); // TEST2: Various Test Settings
CC1101::writeReg(CC1101_TEST1, 0x35); // TEST1: Various Test Settings
CC1101::writeReg(CC1101_TEST0, 0x09); // TEST0: Various Test Settings
CC1101::setRxState();
CC1101::writeReg(CC1101_MDMCFG4, 0xC8);
CC1101::writeReg(CC1101_MDMCFG3, 0x4A);
CC1101::writeReg(CC1101_MDMCFG2, 0x30);
CC1101::writeReg(CC1101_MDMCFG1, 0x42);
CC1101::writeReg(CC1101_MDMCFG0, 0xF8);
CC1101::writeReg(CC1101_PKTCTRL0, 0x30); // asynchronous serial mode
CC1101::writeReg(CC1101_IOCFG0, 0x0d); // GD0 output
return CC1101::readReg(CC1101_TEST1, CC1101_CONFIG_REGISTER) == 0x35;
}
byte read()
{
return digitalRead(GDO0);
}
};
class CPinReceiver
{
enum {
RxPin = 7
};
public:
void Init()
{
pinMode(5, OUTPUT); digitalWrite(5, 0);
pinMode(6, OUTPUT); digitalWrite(6, 1);
pinMode(RxPin, INPUT);
}
byte read()
{
return digitalRead(RxPin);
}
};
//CReceiver Receiver;
C1101Receiver Receiver;
class COregon
{
public:
enum
{
RxPin = 7,
sDelay = 230,
lDelay = 460,
PacketLength = 10,
HeaderBits = 20
};
bool WaitHeader()
{
return Receiver.read() == 0;
}
bool GetHeader()
{
byte headerHits = 0;
long lTimeout = millis() + 100;
while (1)
{
delayMicroseconds(sDelay);
if (Receiver.read() == 0)
{
delayMicroseconds(lDelay);
if (Receiver.read() == 0)
return false;
headerHits ++;
if (headerHits == HeaderBits)
return true;
}
do
{
if ( millis() > lTimeout )
return false;
} while (Receiver.read()==1);
}
return false; // make sure we look for another header
}
byte ReceivePacket(byte* manchester)
{
// https://github.com/robwlakes/ArduinoWeatherOS/blob/master/Arduino_OS_WeatherV26.ino
boolean logic = 1; // look for rest of header 1's, these must be soaked up intil first 0 arrives to denote start of data
byte signal = 0; //RF Signal is at 0 after 1's 1->0 transition, inverted Manchester (see Wiki, it is a matter of opinion)
boolean firstZero = false; //The first zero is not immediately found, but is flagged when found
boolean test230 = false;
boolean test460 = false;
int nosBytes = 0; //counter for the data bytes required
byte dataByte = 0; //accumulates the bits of the signal
byte dataMask = 16; //rotates, so allows nybbles to be reversed
byte nosBits = 0; //counts the shifted bits in the dataByte
int maxBytes = 10; //sets the limits of how many data bytes will be required
while (1)
{
//now get last of the header, and then store the data after trigger bit 0 arrives, and data train timing remains valid
long lTimeout = millis() + 100;
while (Receiver.read()!=signal)
{ //halt here while signal matches inverse of logic, if prev=1 wait for sig=0
if ( millis() > lTimeout )
{
return 0;
}
}//exits when signal==logic
delayMicroseconds(sDelay); //wait for first 1/4 of a bit pulse
test230 = Receiver.read();//snapshot of the input
if ((test230 == signal)&&(nosBytes < maxBytes)){ //after a wait the signal level is the same, so all good, continue!
delayMicroseconds(lDelay); //wait for second 1/2 of a bit pulse
test460=Receiver.read();//snapshot of the input
if (test230==test460){ // finds a long pulse, so the logic to look for will change, so flip the logic value
//Assuming the manchester encoding, a long pulse means data flips, otherwise data stays the same
logic = logic^1;
signal = signal^1;
if (!firstZero){ //if this is the first 0-1 data transition then is the sync 0
firstZero = true; //flag that legit data has begun
//VIP OS Seems to put the Synch '0' bit into the data, as it causes the rest to align onto byte boundaries
dataByte = B00000000; // set the byte as 1's (just reflects the header bit that have preceded the trigger bit=0)
dataMask = B00010000; // set the byte as 1's (just reflects the header bit that have preceded the trigger bit=0)
nosBits = 0; // preset bit counter so we have 7 bits counted already
}
}
//data stream has been detected begin packing bits into bytes
if (firstZero){
if (logic){
dataByte = dataByte | dataMask; //OR the data bit into the dataByte
}
dataMask = dataMask << 1;//rotate the data bit
if (dataMask==0){
dataMask=1;//make it roll around, is there a cleaner way than this? eg dataMask *=2?
}
nosBits++;
if (nosBits == 8){ //one byte created, so move onto the next one
manchester[nosBytes] = dataByte; //store this byte
nosBits = 0; //found 8, rezero and get another 8
dataByte = 0; //hold the bits in this one
dataMask = 16; //mask to do reversed nybbles on the fly
nosBytes++; //keep a track of how many bytes we have made
}
}
}
else {
//non valid data found, or maxBytes equalled by nosBytes, reset all pointers and exit the while loop
return 0;
}
if (nosBytes == maxBytes)
{
return nosBytes;
}
}
return 0;
}
};
COregon Oregon;
void setup()
{
Serial.begin(38400);
Serial.println("Valky.eu Oregon Decoder " __DATE__ " " __TIME__);
while (!Receiver.Init())
{
Serial.print("Cannot initialize receiver!\n");
delay(1000);
}
}
void debug()
{
static long ltime = 0;
long lcur = millis();
if ( lcur - ltime > 10 )
ltime = lcur;
else
return;
static int q= 0;
if ( q++ == 80 )
{
q = 0;
Serial.print("\n");
}
Serial.print(Receiver.read());
}
void loop()
{
//debug();
if ( Oregon.WaitHeader() )
{
if ( Oregon.GetHeader() )
{
byte buffer[COregon::PacketLength] = {0};
byte received = Oregon.ReceivePacket(buffer);
if ( received )
{
const char hex[] = "0123456789abcdef";
Serial.print("Received buffer: ");
for( int i=0; i < received; i++)
{
Serial.print(hex[buffer[i] >> 4]);
Serial.print(hex[buffer[i] & 15]);
}
Serial.print("\n");
} else
Serial.print("Receive error\n");
}
}
}

View File

@@ -0,0 +1,140 @@
#include "EEPROM.h"
#include "cc1101.h"
// The LED is wired to the Arduino Output 4 (physical panStamp pin 19)
#define LEDOUTPUT 4
// The connection to the hardware chip CC1101 the RF Chip
CC1101 cc1101;
byte b;
byte i;
byte syncWord = 199;
long counter=0;
byte chan=0;
// a flag that a wireless packet has been received
boolean packetAvailable = false;
void blinker(){
digitalWrite(LEDOUTPUT, HIGH);
delay(100);
digitalWrite(LEDOUTPUT, LOW);
delay(100);
}
/* Handle interrupt from CC1101 (INT0) gdo0 on pin2 */
void cc1101signalsInterrupt(void){
// set the flag that a package is available
packetAvailable = true;
}
void setup()
{
Serial.begin(9600);
Serial.println("start");
// setup the blinker output
pinMode(LEDOUTPUT, OUTPUT);
digitalWrite(LEDOUTPUT, LOW);
// blink once to signal the setup
blinker();
// initialize the RF Chip
cc1101.init();
cc1101.setSyncWord(&syncWord, false);
cc1101.setCarrierFreq(CFREQ_433);
cc1101.disableAddressCheck(); //if not specified, will only display "packet received"
//cc1101.setTxPowerAmp(PA_LowPower);
Serial.print("CC1101_PARTNUM "); //cc1101=0
Serial.println(cc1101.readReg(CC1101_PARTNUM, CC1101_STATUS_REGISTER));
Serial.print("CC1101_VERSION "); //cc1101=4
Serial.println(cc1101.readReg(CC1101_VERSION, CC1101_STATUS_REGISTER));
Serial.print("CC1101_MARCSTATE ");
Serial.println(cc1101.readReg(CC1101_MARCSTATE, CC1101_STATUS_REGISTER) & 0x1f);
attachInterrupt(0, cc1101signalsInterrupt, FALLING);
Serial.println("device initialized");
}
void ReadLQI()
{
byte lqi=0;
byte value=0;
lqi=(cc1101.readReg(CC1101_LQI, CC1101_STATUS_REGISTER));
value = 0x3F - (lqi & 0x3F);
Serial.print("CC1101_LQI ");
Serial.println(value);
}
void ReadRSSI()
{
byte rssi=0;
byte value=0;
rssi=(cc1101.readReg(CC1101_RSSI, CC1101_STATUS_REGISTER));
if (rssi >= 128)
{
value = 255 - rssi;
value /= 2;
value += 74;
}
else
{
value = rssi/2;
value += 74;
}
Serial.print("CC1101_RSSI ");
Serial.println(value);
}
void loop()
{
if(packetAvailable){
Serial.println("packet received");
// Disable wireless reception interrupt
detachInterrupt(0);
ReadRSSI();
ReadLQI();
// clear the flag
packetAvailable = false;
CCPACKET packet;
if(cc1101.receiveData(&packet) > 0){
// Serial.println("\r\n--------------------------------");
// Serial.print("CC1101 have news! - ");
// Serial.print("Package len = ");
// Serial.print(packet.length);
// Serial.print(" lgi=");
// Serial.print(packet.lqi);
// Serial.print(" rssi=");
// Serial.print(packet.rssi);
// Serial.print(" CRC=");
// Serial.println(packet.crc_ok);
//
if(!packet.crc_ok) {
Serial.println("crc not ok");
}
if(packet.length > 0){
Serial.print("packet: len ");
Serial.print(packet.length);
Serial.print(" data: ");
for(int j=0; j<packet.length; j++){
Serial.print(packet.data[j],HEX);
Serial.print(" ");
}
Serial.println(".");
}
}
// Enable wireless reception interrupt
attachInterrupt(0, cc1101signalsInterrupt, FALLING);
}
}

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