/* #########################################################################
#################### Esp8266 Serial to WiFi Monitor #####################
########################## WEMOS D1 MINI ################################
############################### for #####################################
################### ARDUINO NANO SMART GROW CONTROLLER ##################
################# ##########################
############################ |WWWW| #####################################
############################ \O_O/ ######################################
# CAN BE USED AS A GENERAL PURPOSE MONITOR FOR ANYTHING WITH A TX PIN ##
############# AFTER SOME MODIFICATIONS ####################
*/
/* #########################################################################
I'll improve it as i learn more
#########################################################################
// PLEASE LIKE AND SUBSCRIBE
// MY YOUTUBE CHANNEL
// YOUTUBE.COM/CRAZYGUYOFFICIAL
// Visit Blog for Sketch Updates and more Sketches and "things"
// Set Port forward from your router to this Webserver at port 80
// to monitor it from anywhere**
// This server is not secure
// controlling things should NEVER be done using
// an UN-encrypted webserver like this
// It's only good for Monitoring
// Subscribe to my channel for updates for this sketch
// and other sketches related to this project
// because i'll add more things to it gradually
#########################################################################
#########################################################################
*/
#include <ESP8266WiFi.h> // Version 1.0.0
#include <SoftwareSerial.h> // Version 1.0.0
const char* ssid = "SQUANCHY01";
const char* password ="c137gsasotf";
char Time[9]; // Character Arrays or C-strings
char Day; // size should be the total number of Chars to be stored +1 for null char
char Date[3];
char Mon[3];
char Year[5];
char Status[13];
char Temp1[6];
char Temp2[6];
char Hum[6];
unsigned long Secs = 0;
bool newData = 0;
bool err =1;
bool Lsts =0;
bool Csts =0;
bool Hsts =0;
bool Fsts =0;
bool Ssts =0;
bool DHTerr=0;
bool RTCerr=0;
WiFiServer server(80);
SoftwareSerial swSer(D1, D2, false, 256); // "swSer can be changed it will be the name for the Software Serial
// Software Serial Library Enables Esp8266's GPIO D1 and D2
// to be used as Rx and Tx pins RESPECTIVELY
// ONLY Rx is used and is connected to the Tx of a 5V Arduino Nano
void setup() { // using a Voltage Divider circuit 1K and 2K Resistors
// And Ground of esp to Ground of Arduino
Serial.begin(115200); // This is the baud rate for ESP's Serial at USB which can be viewed in Arduino IDE Serial monitor
swSer.begin(9600); // This is the baud rate for esps Software serial at pins D1 and D2 so it can communicate with arduino
// it's slow because of Arduino Nano's slow speed as compared to Esp
// can change the name swSer from above
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
server.begin();
Serial.println("Waiting for the IP Add...");
delay(5000);
Serial.println(WiFi.localIP());
}
/*##############################################################################################
###############################################################################################
################ SETUP END ####################################################################
###############################################################################################
*/
/*##############################################################################################
###############################################################################################
################ LOOP BEGINS ##################################################################
###############################################################################################
*/
void loop()
{
char data[53];
byte i = 0 ;
byte x = 0 ;
if (swSer.available() > 0 )
{
char Z = swSer.read();
if(Z=='Z') // match first Character to check "validity"
{ // and this letter 'Z' is not stored in the array below
newData=1;
Secs=millis()/1000;
for(i= 0; i< 52; )
{
data[i] = swSer.read();
i++;
data[i] = '\0';
}
for(i=0; i<52;)
{ // serial print to arduino ide monitor via usb,all the chars stored in data array
Serial.print("char number: "); // and print char number the INDEX number starting from zero
// the actual first char is the Letter "Z' which is not stored
Serial.println(i);
Serial.println(data[i]);
i++;
}
}
else
{
err=1;
}
}
//############# GET TIME #######################################################################
if(newData)
{
// get time from the data array
for( i = 0; i < 8; )
{
Time[i] = data[i];
i++;
}
Serial.print("Time :");
Serial.println(Time); // serial print all the chars stored in the time array
//############# GET DAY OF THE WEEK #############################################################
if( data[8]=='W' )
{
err=0;
Day = data[9];
Serial.print("Day :");
Serial.println(Day); // serial print all the chars stored in the day array
}
else
{
err=1;
}
//############# GET DATE #######################################################################
if(data[10]=='D')
{
err=0;
x=0;
for( i = 11; i < 13; )
{
Date[x] = data[i];
i++;
x++;
}
Serial.print("Date :");
Serial.println(Date); // serial print all the chars stored in the Date array
}
else
{
err=1;
}
//############# GET MONTH #######################################################################
if(data[13]=='M')
{
err=0;
x=0;
for( i =14 ; i < 16; )
{
Mon[x] = data[i];
i++;
x++;
}
Serial.print("Month :");
Serial.println(Mon); // serial print all the chars stored in the month / mon array
}
else
{
err=1;
}
//############# GET YEAR #######################################################################
if(data[16]=='Y')
{
err=0;
x=0;
for( i = 17; i < 21; )
{
Year[x] = data[i];
i++;
x++;
}
Serial.print("Year :");
Serial.println(Year); // serial print all the chars stored in the Year array
}
else
{
err=1;
}
//############# GET STATUS #######################################################################
if(data[21]=='L')
{
err=0;
x=0;
for( i = 22; i < 34; )
{
Status[x] = data[i];
i++;
x++;
}
Serial.print("Status :");
Serial.println(Status); // serial print all the chars stored in the Status array
}
else
{
err=1;
}
//############# GET T1 ###########################################################################
if(data[34]=='t')
{
err=0;
x=0;
for( i = 35; i < 40; )
{
Temp1[x] = data[i];
i++;
x++;
}
Serial.print("Temp 1 :");
Serial.println(Temp1); // serial print all the chars stored in the temperature / temp1 array
}
else
{
err=1;
}
//############# GET Hum #######################################################################
if(data[40]=='h')
{
err=0;
x=0;
for( i = 41; i < 46; )
{
Hum[x] = data[i];
i++;
x++;
}
Serial.print("Humidity :");
Serial.println(Hum); // serial print all the chars stored in the Humidity / Hum array
}
else
{
err=1;
}
//############# GET T2 #######################################################################
if(data[46]=='r')
{
err=0;
x=0;
for( i = 47; i < 52; )
{
Temp2[x] = data[i];
i++;
x++;
}
Serial.print("Temp2 :");
Serial.println(Temp2); // serial print all the chars stored in time array
}
else
{
err=1;
}
newData=0;
}
setStatus();
sendHtml();
if(millis()/1000 -Secs > 30 )
{
Serial.println("Resetting Arrays");
Serial.println(Secs);
ResetArrays();
Secs=millis()/1000;
}
}
//####################################################################################
//##################### END OF LOOP #######################################
//####################################################################################
void setStatus()
{
if(!err)
{
Lsts=Status[0]-'0';
Csts=Status[2]-'0';
Hsts=Status[4]-'0';
Fsts=Status[6]-'0';
Ssts=Status[8]-'0';
DHTerr=Status[10]-'0';
RTCerr=Status[11]-'0';
}
}
void sendHtml()
{
WiFiClient client = server.available();
if (client)
{
Serial.println("New client");
boolean blank_line = true;
while (client.connected())
{
if (client.available())
{
char c = client.read();
if (c == '\n' && blank_line)
{
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<head><meta http-equiv='refresh' content='5'/></head><body><h1>Esp8266 Serial to Wifi Monitor Ver: 1.0</h1>");
client.println("<h2>>>>> ---- Time :");
client.println(Time);
client.println("--<<< >>> ---- Day : ");
client.println(Day);
client.println("--<<< >>> ---- Date : ");
client.println(Date);
client.println("-");
client.println(Mon);
client.println("-");
client.println(Year);
client.println("---- <<<<<");
client.println("</h2>");
client.println("<br />");
client.println("<h2>Temp 1 :");
client.println(Temp1);
client.println("\260C</h2>");
client.println("<h2>Temp 2 :");
client.println(Temp2);
client.println("\260C</h2>");
client.println("<h2>Humidity :");
client.println(Hum);
client.println("%</h2>");
client.println("<br />");
client.println("<h1>Current States of Switches</h1>");
client.println("<br />");
client.println("<h3>LIGHT:>>> ");
if(!err)
{
if(Lsts)
{
client.println("ON </h3>");
}
else
{
client.println("OFF </h3>");
}
}
else
{
client.println("UNKNOWN </h3>");
}
client.println("<h3>COOLER:>>>");
if(!err)
{
if(Csts)
{
client.println("ON </h3>");
}
else
{
client.println("OFF </h3>");
}
}
else
{
client.println("UNKNOWN </h3>");
}
client.println("<h3>HEATER:>>>");
if(!err)
{
if(Hsts)
{
client.println("ON </h3>");
}
else
{
client.println("OFF </h3>");
}
}
else
{
client.println("UNKNOWN </h3>");
}
client.println("<h3>FAN:>>>");
if(!err)
{
if(Fsts)
{
client.println("ON </h3>");
}
else
{
client.println("OFF </h3>");
}
}
else
{
client.println("UNKNOWN </h3>");
}
client.println("<h3>HUMIDIFIER:>>>");
if(!err)
{
if(Ssts)
{
client.println("ON </h3>");
}
else
{
client.println("OFF </h3>");
}
}
else
{
client.println("UNKNOWN </h3>");
}
client.println("<br />");
client.println("<h4>DHT Err:>>>");
if(!err)
{
if(DHTerr)
{
client.println("TRUE </h4>");
}
else
{
client.println("FALSE </h4>");
}
}
else
{
client.println("UNKNOWN </h4>");
}
client.println("<h4>RTC Err:>>>");
if(!err)
{
if(RTCerr)
{
client.println("TRUE </h4>");
}
else
{
client.println("FALSE </h4>");
}
}
else
{
client.println("UNKNOWN </h4>");
}
client.println("<br />");
client.println("<h4>Serial Read Error:>>>");
if(err)
{
client.println("TRUE ----OH JEEZ </h4>");
}
else
{
client.println("FALSE </h4>");
}
char LinkOne[]= "https://youtube.com/crazyguyofficial";
client.println("<h3><a href=");
client.print(LinkOne);
client.print(">CHANNEL</a></h3>");
char LinkTwo[]= "https://amkdiyprojects.blogspot.com";
client.println("<h3><a href=");
client.print(LinkTwo);
client.print(">BLOG</a></h3>");
client.println("</body></html>");
break;
}
if (c == '\n')
{
blank_line = true;
}
else if (c != '\r')
{
blank_line = false;
}
}
}
delay(1);
client.stop(); // closing the client connection
Serial.println("Client disconnected.");
}
}
void ResetArrays()
{
//Serial.flush();
err=1;
// data[0] ='\0';
Time[0] ='\0'; // Character Arrays or C-strings
Day ='\0'; // size should be the total number of Chars to be stored +1 for null char
Date[0] ='\0';
Mon[0] ='\0';
Year[0] ='\0';
Status[0] ='\0';
Temp1[0] ='\0';
Temp2[0] ='\0';
Hum[0] ='\0';
}
Do-it-yourself,DIY,How-To,Electronics,Arduino,Esp,Raspberry-Pi,Programming,Hacking Stuff,Gardening,Photography,Hobby,Fun
Showing posts with label controller. Show all posts
Showing posts with label controller. Show all posts
Esp8266 Wemos D1 Mini Serial to Wifi Html WebServer Monitor for Arduino Smart Grow Box Controller [OUT-DATED]
Labels:
arduino,
automation,
controller,
cool,
dht,
esp8266,
green house,
html,
humidity,
monitor,
oled,
plant,
relay,
relays,
rtc,
serial,
thermistor,
timer,
webserver.grow box,
wifi
D.I.Y. Arduino Timer Auto Lights Switch using arduino Nano,Ds3231rtc,relays v1.0 [OUT-DATED]
//*****************************************************************************************************************
//*****************************************************************************************************************
//************<<<< Arduino Nano, DS3231 Real Time Clock & Two Relay Module Lights Timer V1.0 >>>>******************
//*****************************************************************************************************************
//*****************************************************************************************************************
//UPDATED ON DEC 2017
//*****************************************************************************************************************
//*********************<<<< PLEASE VISIT / SUBSCRIBE MY YOUTUBE CHANNEL >>>>***************************************
//*********************<<<< Youtube.com/CrazyGuyOfficial >>>>*****************************************
//*****************************************************************************************************************
//**********************//**********************//**********************
// PINS AND CONNECTIONS
//**********************//**********************//**********************
const byte lightone = 5; // Light one relay (LOW Level Relay)
const byte lighttwo = 6 ; // Light Two Relay
const byte lightthree = 4 ; // Status Led // 13 for arduino builtin LED
// DS3231 RTC "SDA to A4", "SCL to A5" "Vcc to 5V arduino pin Gnd to Gnd"
//**********************//**********************//**********************
// Timer ON/OFF Time Settings
//**********************//**********************//**********************
const int OnTime = 14 ; // Hour when Light will turn ON (24 hr format NO zeros before single digits)
const int OffTime = 8 ; // Hour when Light will turn OFF (24 hr format NO zeros before single digits)
//*****************************************************************************************************************
bool LightStatus = 0 ;
//*****************************************************************************************************************
// INCLUDE LIBRARIES
//*****************************************************************************************************************
#include <Time.h> // Time Manipulation
#include <Wire.h>
#include <DS1307RTC.h> // DS1307 RTC
#include <TimeAlarms.h> // time alarm library //Changed Number of alarms " dtNBR_ALARMS to 30 "
//"BY EDITING TIMEALARM.H FILE IN LIBRARIES FOLDER.
//increasing this number increases size of the sketch too
#define DS1307_ID 0x68 //Address of the RTC
//*****************************************************************************************************************
// SETUP BEGINS
//*****************************************************************************************************************
void setup() {
pinMode(lightone, OUTPUT);
pinMode(lighttwo, OUTPUT);
pinMode(lightthree, OUTPUT);
// THIS WILL PREVENT STARTUP RELAY TRIGGERING PROBLEM
digitalWrite (lightone, HIGH);
digitalWrite (lighttwo, HIGH); // turn the relay "OFF" and turning the pin "LOW" turns the relay "ON"
//**********************//**********************//***********************//**********************
//Check to see if the RTC is present.if yes then Set the ARDUINO's INTERNAL clock accordingly
//**********************//**********************//***********************//**********************
// when using timer library the Arduino's "internal clock " is used for getting "current time"
// Arduino's internal clock is NOT so accurate and gets off time so we use time from RTC (which IS
//accurate atleast for our use) and we sync Arduino's internal Clock with the time from RTC and we
//have to do this periodically (atleast once in every 24 hrs )so our tasks can be completed according
//to the correct time // we can put the sync command in the Loop and Alarm Functions too
Wire.beginTransmission(DS1307_ID);
Wire.write((uint8_t)0x00);
setSyncProvider(RTC.get); //Yes it did, Sync the time from the RTC
setSyncInterval(60);
Serial.begin(9600);
//***********************//**********************//***********************//**********************
// TIMER ALARM THAT RUNS OVER AND OVER AFTER SECONDS (used for status led)
//***********************//**********************//***********************//**********************
Alarm.timerRepeat(10, Repeats); // timer for every 10 seconds blinking LIGHT (status LED)
}
//*****************************************************************************************************************
// SETUP END
//*****************************************************************************************************************
//***********************//**********************//***********************//**********************
//************// Function Called When Repeating Timer alarm triggers //*******************
//***********************//**********************//***********************//**********************
void Repeats() {
Serial.println("******10 second timer******");
digitalWrite(lightthree, HIGH);
Alarm.delay(30);
digitalWrite(lightthree, LOW);
digitalClockDisplay(); // Calls the function to Display the Clock IN SERIAL MONITOR
if (LightStatus ==1) {
Serial.println ("< Lights ON >");
}
else {
Serial.println ("< Lights OFF >");
}
}
//*****************************************************************************************************************
// LOOP BEGINS
//*****************************************************************************************************************
void loop() {
Alarm.delay (2000);
if (hour() == 0 && minute() == 0 && second() == 0) // at 00:00:00 MIDNIGHT UPDATE the Arduino's INTERNAL Clock
{
setSyncProvider(RTC.get); //It's time, sync the Arduino's INTERNAL Clock to the RTC
}
//**********************************************************
// Turn Lights On/Off
//**********************************************************
if (OffTime > OnTime) { // Same Day
if (hour() >= OnTime && hour () <= OffTime - 1) {
// if current hour is equal or greater than ON time
// AND equal to or less than OFF time minus 1 then turn the
// lights ON (by turning pins LOW because of using LOW level Relays)
// Minus 1 from OFF time because we are not using Minutes here
// For Example turn off time is "16" (4 PM) the hour number will be "16" from
// 16:00 till 16:59 (4:00 till 4:59)
digitalWrite(lightone, LOW);
Alarm.delay (1000);
digitalWrite(lighttwo, LOW);
LightStatus = 1 ;
}
else {
digitalWrite(lightone, HIGH);
digitalWrite(lighttwo, HIGH);
LightStatus = 0 ;
}
}
//**********************************************************
if (OffTime < OnTime) { // Different Day
if (hour() >= OnTime || hour () <= OffTime - 1) {
// if current hour is equal or greater than ON time
// OR equal to or less than OFF time minus 1 then turn the
// lights ON (by turning pins LOW because of using LOW level Relays)
// Minus 1 from OFF time because we are not using Minutes here
// For Example turn off time is "16" (4 PM) the hour number will be "16" from
// 16:00 till 16:59 (4:00 till 4:59)
// Minutes,Seconds even day,date,year can be used by adding code
digitalWrite(lightone, LOW);
Alarm.delay (1000);
digitalWrite(lighttwo, LOW);
LightStatus = 1;
}
else {
digitalWrite(lightone, HIGH);
digitalWrite(lighttwo, HIGH);
LightStatus = 0 ;
}
}
//*****************************************************************************************************************
// DAILY TIMED ALARMS THAT TRIGGER ON SPECIFIED TIMES
// these alarms will trigger once and will do "stuff" mentioned in the alarm functions at the end of the loop
// IF Alarm function is used to Turn Pins ON/OFF it will but there's a Reset/Power Dwn/Up cycle it will not work after
// the Specified Alarm time has passed and pin will go back to it's initial state untill alarm changes it again
//*****************************************************************************************************************
Alarm.alarmRepeat(3, 0, 0, ONAlarm); // daily Alarm 1 an alarm on ""03:00:00"" in the morning
Alarm.alarmRepeat(4, 0, 0, ONAlarm); // daily Alarm 2 an alarm on ""04:00:00"" in the morning
Alarm.alarmRepeat(5, 0, 0, ON2Alarm); // daily Alarm 3
Alarm.alarmRepeat(6, 0, 0, ONAlarm); // daily Alarm 4
Alarm.alarmRepeat(7, 0, 0, ONAlarm); // daily Alarm 5
Alarm.alarmRepeat(8, 0, 0, ON2Alarm); // daily Alarm 6
Alarm.alarmRepeat(9, 0, 0, ONAlarm); // daily Alarm 7
Alarm.alarmRepeat(10, 0, 0, ONAlarm); // daily Alarm 8
Alarm.alarmRepeat(11, 0, 0, ON2Alarm); // daily Alarm 9
Alarm.alarmRepeat(12, 0, 0, ONAlarm); // daily Alarm 10
Alarm.alarmRepeat(13, 0, 0, ONAlarm); // daily Alarm 11
Alarm.alarmRepeat(14, 0, 0, ON2Alarm); // daily Alarm 12
Alarm.alarmRepeat(15, 0, 0, ONAlarm); // daily Alarm 13
Alarm.alarmRepeat(16, 0, 0, ONAlarm); // daily Alarm 14
Alarm.alarmRepeat(17, 0, 0, ON2Alarm); // daily Alarm 15
Alarm.alarmRepeat(18, 0, 0, ONAlarm); // daily Alarm 16
Alarm.alarmRepeat(19, 0, 0, ONAlarm); // daily Alarm 17
Alarm.alarmRepeat(20, 0, 0, ON2Alarm); // daily Alarm 18
Alarm.alarmRepeat(21, 0, 0, OFFAlarm); // daily Alarm 19
Alarm.alarmRepeat(22, 0, 0, OFFAlarm); // daily Alarm 20
Alarm.alarmRepeat(23, 0, 0, OFF2Alarm); // daily Alarm 21
Alarm.alarmRepeat(0, 0, 0, OFFAlarm); // daily Alarm 22
Alarm.alarmRepeat(1, 0, 0, OFFAlarm); // daily Alarm 23
Alarm.alarmRepeat(2, 0, 0, OFF2Alarm); // daily Alarm 24
}
//**********************//**********************//**********************
// LOOP END
//**********************//**********************//**********************
//**********************//**********************//**********************//**********************
//Functions called when daily time specific alarms (above in the loop) triggers:
//***********************************************//**********************//**********************
void ONAlarm() {
}
void ON2Alarm() {
setSyncProvider(RTC.get); //It's time, sync the Arduino's INTERNAL Clock to the RTC
Serial.println("TIME SYNCHRONIZED");
}
void OFFAlarm() {
}
void OFF2Alarm() {
setSyncProvider(RTC.get); //It's time, sync the Arduino's INTERNAL Clock to the RTC
Serial.println("TIME SYNCHRONIZED");
}
//**********************//**********************//**********************//**********************
//Function for digital clock display (in the SERIAL MONITOR )
//**********************//**********************//**********************//**********************
void digitalClockDisplay() { // digital clock display of the time 24hr format
Serial.print(hour());
printDigits(minute());
printDigits(second());
Serial.println("");
Serial.println(dayStr(weekday()));
Serial.print(monthStr(month()));
Serial.print(" ");
Serial.print(day());
Serial.print(" ");
Serial.println(year());
}
void printDigits(int digits) {
Serial.print(":");
if (digits < 10)
Serial.print('0');
Serial.print(digits);
}
//***********************************************//**********************//**********************
// Un comment the function below and comment the above only one can be used in the code or change names
/*void digitalClockDisplay() //// digital clock display of the time 12hr format
{
Serial.print(hourFormat12());
printDigits(minute());
printDigits(second());
Serial.println("");
Serial.println(dayStr(weekday()));
Serial.print(monthStr(month()));
Serial.print(" ");
Serial.print(day());
Serial.print(" ");
Serial.println(year());
//Alarm.delay(1000);
}
void printDigits(int digits)
{
Serial.print(":");
if (digits < 10) {
Serial.print('0');
}
Serial.print(digits);
}
*/
ESP8266 Node MCU (12E) Internet/WiFi Controlled robot/rover using Lm298 H-bridge Motor driver TEST-01
//****************************************************
// Android/fruitPhone Controlled WiFi Car
//****************************************************
// ESP 8266 NodeMcu V1.0 PWM Servo/ LM298 H-bridge Control Via WiFi UDP
//*************************************************
//*************************************************
// TEST SKETCH
// USING LM298's ONLY ONE CHANNEL
//*************************************************
//*************************************************
//****************************************************
// Using Free Android or iOS App "RoboRemo"
//****************************************************
//***************************************************************
// PLEASE VISIT
//****************************************************************
// My Blog : https://amkDiyProjects.BlogSpot.com
// My youtube Channel: https://youtube.com/CrazyGuyOfficial
//****************************************************************
//************************************************************
// Libraries Required for this to work
//************************************************************
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <Servo.h>
//************************************************************
// Settings for the WIFI:
//************************************************************
const char* ssid = "myWifi"; // Set WiFi Name of WiFi Router/AP/HotSpot AND Esp8266 will connect TO it
const char* password = "12345678"; // Set PassWord For WiFi
unsigned int localPort = 9876; // Set port number
//************************************************************
// Settings for Servo using Servo library
//************************************************************
const int chCount = 3;
Servo servoCh[chCount];
int chPin[] = {5, 4, 14};
int chVal[] = {1600, 1600, 1600}; // default value in microSeconds for PWM signals (middle)
int usMin = 700; // min pulse micro seconds
int usMax = 2600; // max pulse micro seconds
//***************************************************************
// LM298 H-bridge Motor Driver Pins and Settings for one channel
//***************************************************************
int enA = 12 ; // Pwm signal Pin used to control Motor Speed (Lm298)
int IN1 = 13 ; // IN1 IN2 pins on lm298 to control Motor's direction of rotation
int IN2 = 15 ;
int mid = 1024 ; // Default PWM value for enA pin
//***************************************************************
char cmd[40];
// Make a character array/C string to store the Contents Read from the received UDP Packet
// Cmd is the name of the UDP packet Buffer in which the command which is received is stored
unsigned long lastCmdTime = 60000;
unsigned long aliveSentTime = 0;
//***************************************************************
WiFiUDP port;
//************************************************************
// SETUP BEGINS
//************************************************************
void setup() {
pinMode(enA, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
digitalWrite(enA, LOW);
digitalWrite(IN1, LOW);
digitalWrite (IN2, LOW);
delay(500);
Serial.begin(115200);
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA); //Set Esp8266 in Station mode
//it can work without this line but necessary for preventing Ap mode (happened in my case )
WiFi.begin(ssid, password); // Connect to WiFi network
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("trying to connect");
delay(500);
}
Serial.println("");
Serial.println("WiFi connected");
port.begin(localPort);
Serial.print("Use this Ip and Port in RoboRemoApp to connect: "); //Print the IP address and port number
Serial.print(WiFi.localIP());
Serial.print(":");
Serial.print(localPort);
}
//*************************************************
// SETUP END
//*************************************************
//************************************************************
// LOOP BEGINS
//************************************************************
void loop() {
//*************************************************
if (millis() - lastCmdTime > 500) {
//*************************************************
analogWrite(enA, 0); // Write 0 or turn off the pwm signal to the lm298's enA pin so motor stops
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
//*************************************************
for (int i = 0; i <= 2; ) {
servoCh[i].detach(); // Turns OFF all the Pins declared in servo library settings above
i++;
}
}
//*************************************************
int packetSize = port.parsePacket(); // Declaring an int for getting Packet Size
if (packetSize > 0) {
port.read(cmd, 40);
//Serial.print("CMD");
//Serial.println(cmd); // Print the recieved cmd
//*************************************************
if (cmd[0] == 'f' && cmd[1] == 'b') { // if the recieved command string contains the channel id "fb" (forward/backwards)
exeFB(); // execute the function "FB" so all the pins required to control lm298 can operate
}
if (cmd[0] == 'c' && cmd[1] == 'h') { // if the recieved command string contains the channel id "ch"
exeServo(); // execute the servo function
//so Pwm signals according to the channel number can be sent to servos
// via the GPIO pins declared above in the servo library settings
}
//*************************************************
if (millis() - aliveSentTime > 1000) {
// an "alive" signal is sent periodically to the phone to know the connection state
// in the RoboRemo app from "edit UI" option add an "led" or a "text log box" set the ID
// to "alive" or can be changed but for the text box if left empty the received text will be shown
exeReply(); // Execute exeReply function At the end of the loop
}
}
}
//*************************************************
// LOOP ENDS
//*************************************************
//************************************************************************************
// FUNCTIONS
//************************************************************************************
void exeFB() {
lastCmdTime = millis();
int fb = cmd[2] - '0' ;
int fbVl = 0;
int i = 4;
while ( isdigit( cmd[i] ) ) { // if the 4th character in the Array is a Number
//get the number and Calculate all the digits in to a single 4 digit number
fbVl = (fbVl * 10) + (cmd[i] - '0');
i++;
}
if (fb == 3 && cmd[3] == ' ' && fbVl > mid) { // forward motor direction
digitalWrite(IN1, HIGH); // set LM298 channel one motor direction
digitalWrite(IN2, LOW);
int FWD = map(fbVl, 1025, 2048, 0, 1024); // map the channel value number to a number between 0-1024
// for writing Pwm to pin enA
Serial.print("FWD :");
Serial.println(FWD);
analogWrite(enA, FWD); // write pwm
}
if (fb == 3 && cmd[3] == ' ' && fbVl < mid) { // backwards motor direction
digitalWrite(IN1, LOW); // set pins for reverse direction
digitalWrite(IN2, HIGH);
int BKW = map(fbVl, 1024, 0, 0, 1024); //map value
Serial.print("BKW :");
Serial.println(BKW);
analogWrite(enA, BKW); //write PWM
}
Serial.print ("fb Number : ");
Serial.println (fb);
Serial.print ("fbVl : ");
Serial.println (fbVl);
}
//******************************************************************************************
void exeServo() { // exeCmd function when called from the loop Reads the channel number and value and sends PWM signals
lastCmdTime = millis();
int ch = cmd[2] - '0' ; // Channel Number
int chVl = 0; // Channel Value temporarily store it in this and then move to Array chVal[] which is already
// declared at the top
int i = 4;
while ( isdigit( cmd[i] ) ) { // if the 4th character in the Array is a Number
//get the number and Calculate all the digits in to a single 4 digit number
chVl = (chVl * 10) + (cmd[i] - '0');
chVal[ch] = chVl;
i++;
}
if (ch >= 0 && ch <= 2 && cmd[3] == ' ') { //if channel value is between 0 and 9 send PWM Signals using Channel Value
if (!servoCh[ch].attached()) {
servoCh[ch].attach(chPin[ch], usMin, usMax);
}
servoCh[ch].writeMicroseconds(chVal[ch]);
}
Serial.print ("channel Number : ");
Serial.println (ch);
Serial.print ("chVl : ");
Serial.println (chVl);
}
//*********************************************************************************************
void exeReply() {
port.beginPacket(port.remoteIP(), localPort); // Send "Alive 1" back to the App to light up the "led" in the App GUI
// Alive is the "id" for "LED" and "1" is the On command /n" will be ignored
port.write("alive 1\n");
port.endPacket();
aliveSentTime = millis();
Serial.println("alive sent");
}
Labels:
android,
arduino,
code,
controller,
diy,
esp8266internetrobot,
h-bridge,
internet,
ios,
lm298,
micro-controller,
motor-driver,
programming,
relays,
roboremo,
robot,
servo,
sketch,
udp,
wifi
D.I.Y. Make RCA/AV Cable for Raspberry pi (using earphones/headphones audio lead)
Make RCA cable for Raspberry pi
I used an old cell phone's hands-free earphones kit and a female RCA connectors cable to make an AV (audio/video) Cable for the Raspberry Pi.
First, I tried to use a "ready-made" AV cable that I had for a long time and it came with another cell phone (Nokia N95 8GB music edition) but it didn't work at first because the Raspberry pi and that cellphone have different pin-out in the Audio Jack.
So, when I plugged it in the Raspberry Pi 3 and in the TV ,I just got weird noises and no Video . After thinking about it for sometime,I tested it with a multimeter by putting it in the "continuity mode" and in that mode if you touch both of the leads of the multimeter together it shows the number "0" and if there is no connection between the two leads it shows the alphabet "l" which means out-of-limit or range. It actually measures the resistance between it's two leads.So, if there is no connection between the two points i.e. the audio jack's metal pin and the corresponding wires the resistance will be infinite or too high for the meter to measure.
So, if you connect one lead of the multimeter (black or red doesn't matter in this case) to one of the four metal contacts of the Audio lead and the other lead of the multimeter to the RCA connector's outer metal part (Ground) or the center part (which is for the Signal) you can see which part of the Audio lead is connected to which part of the RCA connector.
In my case what was happening was that the Raspberry Pi's Video signal was going to the Ground of the Rca Cable and because ground is common for all the signals (Audio Left,Audio Right ,Video) all the three RCA connectors (red,white,yellow) had Video signal in their outer metal part of the connector and the "Actual Ground" was only on the Signal part in the center of the Yellow connector because of the different pin-out.
However, I made it to work also, just to test the Video output of the Raspberry pi by using a single Male RCA connector with it's wire stripped and by wrapping it on both the outer part of the yellow connector (of that cell phones AV cable) to get the Video Signal and the center part to get the Ground and then it worked but it was too messy.
So,then i felt the need to make a proper AV cable for the pi because I also fixed a cheap LCD display and that display was part of a car's Headrest and meant to be used with the DVD player it came along with(the chinese car DVD player with built-in lcd came with two head rests with LCDs in them ) and it has two analog video inputs so it can work with the Rpi too.
How i made the AV cable can be seen in the picture below.
![]() |
Raspberry Pi Audio Jack/RCA Connections Pin-out |
![]() |
Cell phone hands-free earphones with button and a Mic and four connector lead |
![]() |
Cellphone Earphones with Button and Mic for Calls |
![]() |
Female RCA connectors Cable |
![]() |
Female RCA Connectors Separated from the "other" lead |
![]() |
Separate all the wires and test with a multimeter (on continuity mode) because sometimes the wires are insulated and they have to be "burned" to remove the insulation |
![]() |
Test all the wires before proceeding any further just to be sure because it will become difficult to troubleshoot later if there is any problem with the connections |
![]() |
Join the related wires together |
![]() |
Solder them together and Test them Again |
![]() |
Tape the wires separately and then together to make it all neat |
Then I used Male-to-Male RCA cable to connect this to the TV.
You can also use Male to Male RCA cable then cut it,strip it and join with the audio lead the same way and then it will directly connect to the TV giving the same results .
I did it this way because I also had the useless female connectors .
![]() |
Car Head-rest Rear LCD for DVD player Front View |
![]() |
Back Cover Removed View of LCD and it's control board |
![]() |
Main IC on the control board of LCD |
![]() |
Back View of LCD control Board and Connectors |
Control motors,Leds,Relays or Motor Driver like lm298 using ESP8266 NodeMcu WiFi UDP with RoboRemo App
//**************************************************** // Android/fruitPhone Controlled WiFi Car //**************************************************** // ESP 8266 NodeMcu V1.0 PWM Servo Control Via WiFi UDP // Using Free Android or iOS App "RoboRemo" //****************************************************
// for Controlling LM298 module with 3 pins (one channel) //I have uploaded another sketch after this one see this link with LM298 pins included
//****************************************************
//*************************************************************** // PLEASE VISIT //**************************************************************** // My Blog : https://amkDiyProjects.BlogSpot.com // My youtube Channel: https://youtube.com/CrazyGuyOfficial //**************************************************************** //************************************************************ // Libraries Required for this to work //************************************************************ #include <ESP8266WiFi.h> #include <WiFiUdp.h> #include <Servo.h> //************************************************************ //************************************************************ // Settings for the WIFI: //************************************************************ const char* ssid = "mywifi"; // Set WiFi Name of WiFi Router/AP/HotSpot AND Esp8266 will connect TO it const char* password = "12345678"; // Set PassWord For WiFi unsigned int localPort = 9876; // Set port number // if it's not working first ensure the following things // to use it in Local network i.e. in the same wifi "client Isolation" should be turned off in the Wifi Router's settings // otherwise even if both the phone and the esp8266 are connected to the wifi they will not be able to "talk to each-other" // to use it from the Internet the port should be forwarded in the WiFi router's settings //************************************************************ // Settings for Servo using Servo library //************************************************************ const int chCount = 4; // 4 channels,total number of channels is 4 and 4 GPIOs will be used Servo servoCh[chCount]; int chPin[] = {5, 4, 14, 12}; // ESP8266 12E NODE MCU DevKit V1.0 pins: GPIO 5, 4, 14, 12 // on my NODE MCU board they are marked D1 D2 D5 D6 respectively // IN THE App first channel "ID" is Ch 0 = 5 ch 1 = 4 ch 2 = 14 ch 3 = 12 int chVal[] = {1600, 1600, 1600, 1600}; // default value in micro-seconds for PWM signals (middle) int usMin = 700; // min pulse micro seconds int usMax = 2600; // max pulse micro seconds //************************************************************ char cmd[40]; // Make a character array/C string to store the Contents Read from the received UDP Packet // Cmd is the name of the UDP packet Buffer in which the command which is received is stored unsigned long lastCmdTime = 60000; unsigned long aliveSentTime = 0; //************************************************************ WiFiUDP port; //************************************************************ // SETUP BEGINS //************************************************************ void setup() { delay(1000); Serial.begin(115200); Serial.println("Connecting to "); Serial.println(ssid); WiFi.mode(WIFI_STA); //Set Esp8266 in Station mode //it can work without this line but necessary for preventing Ap mode (happened in my case ) WiFi.begin(ssid, password); // Connect to WiFi network while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.println("trying to connect"); delay(500); // IF UNABLE TO CONNECT OR IF IT'S TAKING TOO LONG //first CHECK the SSID,PASSWORD in the SKETCH it should be your WIFI name/ssid and PASSWORD //second every-time after uploading a sketch reset esp8266 once or disconnect from power and connect again //and in the second case to view the serial data again //select the device port in Arduino IDE again and turn off/on Serial monitor } Serial.println(""); Serial.println("WiFi connected"); port.begin(localPort); Serial.print("Use this Ip and Port in RoboRemoApp to connect: "); //Print the IP address and port number Serial.print(WiFi.localIP()); Serial.print(":"); Serial.print(localPort); } void loop() { if (millis() - lastCmdTime > 500) { // All PWM values will Return to Default Values 500 milli seconds after the time of Last Received Command // So all PWM signals will return to default values if there is No New Command for (int i = 1; i <= 3; ) { // set i to 0,1,2 or 3 (if connected to servo and want it to stay at the last commanded position) // and rest of the pins PWM signals will return to default values if there is No New Command // Comment out these two lines if you just want to turn the Pwm signals off immediately // and Uncomment if you also want the servo to return to mid but then servo.detach below should be commented // because servo.detach turns the pins off immediately and does'nt give the servo enough time to return to mid // servoCh[i].attach(chPin[i]); // servoCh[i].writeMicroseconds(1600 ); servoCh[i].detach(); // Turns OFF the Pins // comment it out if want the servo to Return to it's mid Position Quickly // because this loop runs over and over again quickly and the servos need some time to //physically move and PWM should be ON during that period // because this line turns off the pin before moving to i++ and changing the pin number i++; } } int packetSize = port.parsePacket(); // Declaring an int for getting Packet Size if (packetSize > 0) { // if Packet Size is more than zero or if there is some command received then port.read(cmd, 40); // Read the Received UDP Packet //and Put the Contents,the channel number and value in the Cmd (array/C string) // Serial.println(cmd); // Print the recieved cmd if (cmd[0] == 'c' && cmd[1] == 'h') { // if the command starts with the caracter c and the second character is h exeCmd(); // Execute the execmd function which is at the end of the loop } if (millis() - aliveSentTime > 1000) { // an "alive" signal is sent periodically to the phone to know the connection state // in the RoboRemo app from "edit UI" option add an "led" or a "text log box" set the ID // to "alive" or can be changed but for the text box if left empty the received text will be shown exeReply(); // Execute exeReply function At the end of the loop } } } void exeCmd() { // exeCmd function when called from the loop Reads the channel number and value and sends PWM signals lastCmdTime = millis(); int ch = cmd[2] - '0' ; // Channel Number int chVl = 0; // Channel Value temporarily store it in this and then move to Array chVal[] which is already declared at the top int i = 4; while ( isdigit( cmd[i] ) ) { // if the 4th character in the Array is a Number //get the number and Calculate all the digits in to a single 4 digit number chVl = (chVl * 10) + (cmd[i] - '0'); chVal[ch] = chVl; i++; } if (ch >= 0 && ch <= 9 && cmd[3] == ' ') { //if channel value is between 0 and 9 send PWM Signals using Channel Value if (!servoCh[ch].attached()) { servoCh[ch].attach(chPin[ch], usMin, usMax); } servoCh[ch].writeMicroseconds(chVal[ch]); } Serial.print ("channel Number : "); Serial.println (ch); Serial.print ("channel Value : "); Serial.println (chVal[ch]); } void exeReply() { port.beginPacket(port.remoteIP(),localPort); // Send "Alive 1" back to the App to light up the "led" in the App GUI // Alive is the "id" for "LED" and "1" is the On command /n" will be ignored port.write("alive 1\n"); port.endPacket(); aliveSentTime = millis(); Serial.print("alive sent"); }
Labels:
android,
arduino,
automation,
code,
controller,
humidity,
internet,
ios,
lights,
lm298,
motion sensor,
motor driver,
programming,
relays,
roboremo,
servo,
sketch,
temperature,
udp,
wifi
Arduino Nano micro-controller Grow-Box / Green-House Controller 2017[OUT-DATED] Sketch / Code Compiled / Tested with Arduino IDE 1.6.9
/*
************** UPDATED ON FEB 2017 *************
***
THIS SKETCH IS OUT DATED . FOR LATEST SKETCH GO TO THE FOLLOWING LINK
https://amkdiyprojects.blogspot.com/2017/09/pre_25.html
***
***MAKING A MODULAR SYSTEM FOR D.I.Y. GREENHOUSE
*****i WILL improve it as i learn more :)
//**********************//**********************//**********************
//**********************//**********************//**********************//**********************//**********************//**********************
// Arduino Nano Grow-box / Green-House Controller v 3.0 :)
//**********************//**********************//**********************//**********************//**********************//**********************
// ***Made by Ali khan from Pakistan :)
//**********************//**********************//**********************
// **PARTS required (for this sketch to work as it is )
//**********************//**********************//**********************
1.Arduino Nano
2.A thermistor (i used A 10K WATERPROOF ONE)
3.A resistor (matching the value of the thermistor's "nominal resistance at 25 DEGREES C"
for example: 5k resistor for 5k thermistor)
4.OLED display ssd1306 (mine is ssd1306 but got it working by using sh1106 constructor
also got rid of the "white line problem")
5. DHT 22 + Pull up Resistor 5K ohm or close 4.7K
6.RELAY MODULE LOW LEVEL TRIGGER TYPE (5 Relays required in total for all the pins
can be separate 4 CAN WORK TOO )
7. DS3231 RTC MODULE (RESISTOR from charging circuit REMOVED and charging DISABLED
WITH CR2032(NON-rechargeable)Cell
8. An LED with appropriate RESISTOR for using it as a STATUS LED
9. Power Supply (two if complete isolation is required)
*/
//**********************//**********************//**********************
//TEMPERATURE and HUMIDITY "CONTROL PARAMETERS"
//**********************//**********************//**********************
//Default Temperature and Humidity Settings
int Tmax = 29 ; // Set temperature Maximum point at which "Cooler" will turn ON
int setT = 25 ; // Set temperature point at which "heater" and "cooler" will turn OFF
int Tmin = 19 ; // Set temperature Minimum point at which Heater will turn ON
int setHmx = 80 ; // set humidity max at which "bigfan" will turn ON
int setHnr = 65 ; // Set humidity normal at which "bigfan" and "spray" will turn OFF
int setHlw = 55 ; // Set humidity low at which "spray will turn ON
// Separate Temperature and Humidity Settings for Day and Night time can be done by Alarms function belowwww
//**********************//**********************//**********************
// Light Timer ON/OFF Time Settings
//**********************//**********************//**********************
const int OnTime = 14 ; // Hour when Light will turn ON (24 hr format NO zeros before single digits)
const int OffTime = 8 ; // Hour when Light will turn OFF (24 hr format NO zeros before single digits)
// SET RTC'S TIME USING DS1307 EXAMPLE SKETCH FROM ABOVE FILE > EXAMPLE > DS1307 > SETTIME
// THEN UPLOAD THIS SKETCH
//*****************************************************************************************************************
bool LightSts = 0 ; // DON'T CHANGE MANUALLY THESE ARE FOR STATUS UPDATES IN SERIAL MONITOR
bool CoolerSts = 0 ;
bool HeaterSts = 0 ;
bool BigFanSts = 0 ;
bool SpraySts = 0 ;
//**********************//**********************//**********************
// PINS AND CONNECTIONS
//**********************//**********************//**********************
// Five pins used in total for five relays
// usually a 4 Relay board is available so it can be used as only one of the pins for Heater/Cooler are required
// and they can be swapped according to the outdoor temperature in different seasons
// LOW-level Relay board will trigger the relay when the trigger pin is LOW/grounded
// so when something has to be turned ON the trigger pin will become LOW otherwise it will stay HIGH (as.a.mf.)
// if possible use two separate power supplies for relay board and arduino by removing JDVCC-VCC jumper
const byte Bigfan = 4 ; // Bigfan turns on at high humidity
const byte cooler = 5 ; // Cooler turn on at high temp (T1 from DHT)
const byte spray = 6 ; // Spray turns on at low humidity
const byte lightone = 7 ; // Main Lights(for plants)
const byte heater = 8 ; // Heater turns ON at low temp (T1 from DHT)
const byte lighttwo = 3 ; // pin for "status LED' inicating the loop is running when oled is turned OFF...
//i turn it off by removing two jumper wires manually
//blinks every ten second (change ten second timer)
// ******** THERMISTOR AND DHT PINS BELOW *******
// DS3231 RTC "SDA to A4", "SCL to A5" "Vcc to 5V arduino pin Gnd to Gnd"
//**********************//**********************//*********************
//THERMISTOR PIN and SETTINGS
//**********************//**********************//**********************
#define THERMISTORPIN A0 // which analog pin to connect to thermistor and the resistor "joint"
#define THERMISTORNOMINAL 10000 // resistance at 25 degrees C
#define TEMPERATURENOMINAL 25 // temp. for nominal resistance (almost always 25 C)
#define NUMSAMPLES 5 // how many samples to take and average,takes longer gets 'smooth'
#define BCOEFFICIENT 3500 // The beta coefficient of the thermistor (usually 3000-4000)
#define SERIESRESISTOR 9700 // the value of the 'other' resistor should be close to the thermistors nominal value
int samples[NUMSAMPLES];
//**********************//**********************//**********************
// INCLUDE LIBRARIES
//**********************//**********************//**********************
#include "DHT.h" //use older versions i haven't tried it with the new one
#include <U8glib.h> // OLED
#include <Wire.h> // I2C
#include <Time.h> // Time Manipulation
#include <DS1307RTC.h> // DS1307 RTC
#include <TimeAlarms.h> // time alarm library //Change Number of alarms "dtNBR_ALARMS to 24 "
//"BY EDITING TIMEALARM.H FILE IN LIBRARIES FOLDER.
//increasing this number increases size of the sketch too
//or remove alarms from the code below to match the max number defined in the library
#define DS1307_ID 0x68 //Address of the RTC
//******************************************************** D H T 22 and pin ***************************************************************************
#define DHTPIN A1 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE, 6);
//**********************//**********************//**********************
// MAKING CHARACTER ARRAYS or C strings
//**********************//**********************//**********************
char timebuf[10]; // array for Time
char str[10]; // for Display
//char datebuf[10]; // Date //un comment for using/displaying date with time
//int year2digit; // 2 digit year // necessary for Date Specific Alarms
// for example triggering a water pump relay for watering the plants
// i didn't use it as my setup currently doesn't need date
//**********************//**********************//**********************
// OLED CONSTRUCTOR
//**********************//**********************//**********************
U8GLIB_SH1106_128X64 u8g(13, 11, 10, 9); // SPI SCK/clk to D13, MOSI = D11, CS = D10, DC = D9
// OLED "constructor" and pins info.
//check out example sketch section for U8glib it has all the info
//**********************//**********************//**********************//**********************//**********************//**********************
// SETUP BEGINS
//**********************//**********************//**********************//**********************//**********************//**********************
void setup() {
pinMode(Bigfan, OUTPUT); // set output relay pins // add more if you have more relays or pins connected to something
pinMode(cooler, OUTPUT);
pinMode(heater, OUTPUT);
pinMode(spray, OUTPUT);
pinMode(lightone,OUTPUT);
pinMode(lighttwo,OUTPUT);
digitalWrite(Bigfan, HIGH); // When using "LOW level trigger" type Relay module, turning a pin "HIGH" will
digitalWrite(cooler, HIGH); // turn the relay "OFF" and turning the pin "LOW" turns the relay "ON"
digitalWrite(heater, HIGH); // THIS WILL PREVENT STARTUP RELAY TRIGGERING PROBLEM
digitalWrite(spray, HIGH);
digitalWrite(lightone,HIGH);
analogReference(EXTERNAL); // AREF connected to 3.3 ON BOARD for accuracy of thermistor
//(go to adafruit using a thermistor tutorial )
u8g.firstPage(); // //START SCREEN "Picture loop" for OLED
do {
u8g.setFont(u8g_font_unifont);
u8g.drawFrame(10, 12, 108, 31);
u8g.drawFrame(0, 0, 128, 64);
u8g.drawStr(15, 25, "Grow Box 3.0");
u8g.drawStr( 16, 40, "Controller");
u8g.drawStr(30, 56, "Made by:AMK");
}
while ( u8g.nextPage() );
//**********************//**********************//***********************//**********************
//Check to see if the RTC is present.if yes then Set the ARDUINO's INTERNAL clock accordingly
//**********************//**********************//***********************//**********************
// when using timer library the Arduino's "internal clock " is used for getting "current time"
// Arduino's internal clock is NOT so accurate and gets off time so we use time from RTC (which IS
// accurate at least for our use) and we sync Arduino's internal Clock with the time from RTC and we
// have to do this periodically (at-least once in every 24 hrs )so our tasks can be completed according
// to the correct time we can put the sync command in the Loop and Alarm Functions too
Wire.beginTransmission(DS1307_ID);
Wire.write((uint8_t)0x00);
if (Wire.endTransmission() == 0) //Did the RTC respond?
{
setSyncProvider(RTC.get); //Yes it did, get the time from the RTC
Serial.begin(9600); // for initializing serial monitor
Serial.println("TIME SYNCHRONIZED");
}
Serial.println("AMK GROW BOX Controller! V3.0 "); //ONLY ONCE AT START UP in serial monitor only
Serial.println("AmkDiyProjects.Blogspot.com"); //ONLY ONCE AT START UP in serial monitor only
Serial.println("Subscribe to My Channel "); //ONLY ONCE AT START UP in serial monitor only
Serial.println("Youtube.com/CrazyGuyOfficial "); //ONLY ONCE AT START UP in serial monitor only
//***********************//**********************//***********************//**********************
// TIMER ALARM THAT RUNS OVER AND OVER AFTER SECONDS
//***********************//**********************//***********************//**********************
Alarm.timerRepeat(10, Repeats); // timer for every 10 seconds blinking LIGHT TWO (status LED) it blinks only when
// loop is running normally and (below in the sketch ) if DHT sensor has problems
//the loop stops and light two led lights up constantly indicating sensor problem
}
//**********************//**********************//**********************
// SETUP END
//**********************//**********************//**********************
//***********************//**********************//***********************//**********************
//************// Function Called When Repeating Timer alarm triggers //*******************
//***********************//**********************//***********************//**********************
void Repeats() {
Serial.println("*****>>10 second timer<<*****");
digitalWrite(lighttwo, HIGH); // it is also used to indicate Dht read failed
//and lights up continuously below in dht part
Alarm.delay(30);
digitalWrite(lighttwo, LOW);
digitalClockDisplay(); // Update the Clock Display IN SERAL MONITOR
// this calls the function digitalClockDisplay at the end
if (LightSts ==1) {
Serial.println ("< Lights ON >");
}
else {
Serial.println ("< Lights OFF >");
}
if (CoolerSts ==1) {
Serial.println ("< Cooler ON >");
}
else {
Serial.println ("< Cooler OFF >");
}
if (HeaterSts ==1) {
Serial.println ("< Heater ON >");
}
else {
Serial.println ("< Heater OFF >");
}
if (BigFanSts ==1) {
Serial.println ("< BigFan ON >");
}
else {
Serial.println ("< Bigfan OFF >");
}
if (SpraySts ==1) {
Serial.println ("< Spray ON >");
}
else {
Serial.println ("< Spray OFF >");
}
}
//***********************//**********************//***********************
//**********************//**********************//**********************
// LOOP BEGINS
//**********************//**********************//**********************
void loop() {
if (hour() == 0 && minute() == 0 && second() == 0) //If it is 00:00:00 MIDNIGHT UPDATE the Arduino's INTERNAL Clock
{
setSyncProvider(RTC.get); //It's time, sync the Arduino's INTERNAL Clock to the RTC
}
//***********************//**********************//***********************//**********************
// LET THERE BE LIGHT
//**************************************************************************************************
// This will make sure that the light one (for plants) stays ON after reset or power down/up cycle
// because Alarms will trigger on a given time and will turn the pin HIGH but if after the alarm is
// triggered AND there is a reset the pin will turn off until next alarm that turns it ON again
// which can interrupt photo-period for plants So, this line makes sure that LIGHTS turn ON immediately
// after reset which happens DURING the LIGHT period for plants
//**********************************************************
// Turn Lights On/Off
//**********************************************************
if (OffTime > OnTime) { // Same Day //GETS THE JOB DONE :)
if (hour() >= OnTime && hour () <= OffTime - 1) {
// if current hour is equal or greater than ON time
// AND equal to or less than OFF time minus 1 then turn the
// lights ON (by turning pins LOW because of using LOW level Relays)
// Minus 1 from OFF time because we are not using Minutes here
// For Example turn off time is "16" (4 PM) the hour number will be "16" from
// 16:00 till 16:59 (4:00 till 4:59)
digitalWrite(lightone, LOW);
LightSts = 1 ;
}
else {
digitalWrite(lightone, HIGH);
LightSts = 0 ;
}
}
//**********************************************************
if (OffTime < OnTime) { // Different Day
if (hour() >= OnTime || hour () <= OffTime - 1) {
// if current hour is equal or greater than ON time
// OR equal to or less than OFF time minus 1 then turn the
// lights ON (by turning pins LOW because of using LOW level Relays)
// Minus 1 from OFF time because we are not using Minutes here
// For Example turn off time is "16" (4 PM) the hour number will be "16" from
// 16:00 till 16:59 (4:00 till 4:59)
// Minutes,Seconds even day,date,year can be used by adding code
digitalWrite(lightone, LOW);
LightSts = 1;
}
else {
digitalWrite(lightone, HIGH);
LightSts = 0 ;
}
}
//********************************************************************************************************************************************
// *******************************************************************************************************************************************
// DAILY TIMED ALARMS THAT TRIGGER ON SPECIFIED TIMES
// these alarms will trigger once and will do "stuff" mentioned in the alarm functions at the end of the loop
// *******************************************************************************************************************************************
Alarm.alarmRepeat(3, 0, 0, ONAlarm); // daily Alarm 1 for example // for triggering an alarm on ""03:00:00"" in the morning
Alarm.alarmRepeat(4, 0, 0, ONAlarm); // daily Alarm 2 or for example // for triggering an alarm on ""04:00:00"" in the morning
Alarm.alarmRepeat(5, 0, 0, ON2Alarm); // daily Alarm 3
Alarm.alarmRepeat(6, 0, 0, ONAlarm); // daily Alarm 4
Alarm.alarmRepeat(7, 0, 0, ONAlarm); // daily Alarm 5
Alarm.alarmRepeat(8, 0, 0, ON2Alarm); // daily Alarm 6
Alarm.alarmRepeat(9, 0, 0, ONAlarm); // daily Alarm 7
Alarm.alarmRepeat(10, 0, 0, ONAlarm); // daily Alarm 8
Alarm.alarmRepeat(11, 0, 0, ON2Alarm); // daily Alarm 9
Alarm.alarmRepeat(12, 0, 0, ONAlarm); // daily Alarm 10
Alarm.alarmRepeat(13, 0, 0, ONAlarm); // daily Alarm 11
Alarm.alarmRepeat(14, 0, 0, ON2Alarm); // daily Alarm 12
Alarm.alarmRepeat(15, 0, 0, ONAlarm); // daily Alarm 13
Alarm.alarmRepeat(16, 0, 0, ONAlarm); // daily Alarm 14
Alarm.alarmRepeat(17, 0, 0, ON2Alarm); // daily Alarm 15
Alarm.alarmRepeat(18, 0, 0, ONAlarm); // daily Alarm 16
Alarm.alarmRepeat(19, 0, 0, ONAlarm); // daily Alarm 17
Alarm.alarmRepeat(20, 0, 0, ON2Alarm); // daily Alarm 18
Alarm.alarmRepeat(21, 0, 0, OFFAlarm); // daily Alarm 19
Alarm.alarmRepeat(22,0, 0, OFFAlarm); // daily Alarm 20
Alarm.alarmRepeat(23, 0, 0, OFF2Alarm); // daily Alarm 21
Alarm.alarmRepeat(0, 0, 0, OFFAlarm); // daily Alarm 22
Alarm.alarmRepeat(1, 0, 0, OFFAlarm); // daily Alarm 23
Alarm.alarmRepeat(2, 0, 0, OFF2Alarm); // daily Alarm 24
//***********************//**********************//***********************//**********************
// DHT 22****** TEMPERATURE HUMIDITY CALCULATIONS
//***********************//**********************//***********************//**********************
float h = dht.readHumidity(); // READ HUMIDITY
float t = dht.readTemperature();// Read temperature as Celsius
// Check if any reads failed and exit early (to try again)
if (isnan(h) || isnan(t) ) {
Alarm.delay(1000);
Serial.println("Failed to read from DHT sensor!");
Serial.println("Wait for 2 secs if it doesn't start check circuit");
digitalWrite (lighttwo,HIGH);
return;
}
/*Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("T1: ");
Serial.print(t);
Serial.print(" *C ");
*/
//***************************************************************************************************************
// THERMISTOR CALCULATIONS
//***************************************************************************************************************
uint8_t i;
float average;
for (i = 0; i < NUMSAMPLES; i++) { // take "N" number of samples in (milivolts) in a row, with a slight delay
samples[i] = analogRead(THERMISTORPIN);
Alarm.delay(10);
}
average = 0;
for (i = 0; i < NUMSAMPLES; i++) { // average all the samples out
average += samples[i];
}
average /= NUMSAMPLES;
average = 1023 / average - 1; // convert the value to resistance
average = SERIESRESISTOR / average;
//Serial.print("Thermistor resistance ");
//Serial.println(average);
float steinhart; // Calculate temperature from that resistance value
steinhart = average / THERMISTORNOMINAL; // (R/Ro)
steinhart = log(steinhart); // ln(R/Ro)
steinhart /= BCOEFFICIENT; // 1/B * ln(R/Ro)
steinhart += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
steinhart = 1.0 / steinhart; // Invert
steinhart -= 273.15; // convert to C
/*Serial.print("T2 "); // FOR SERIAL MONITOR
Serial.print(steinhart);
Serial.println(" *C");
*/
//***********************//**********************//***********************//**********************
// CONTROL PART turning things ON and OFF according to Temperature(from DHT) and Humidity (THE GOOD STUFF) "ifs"
//***********************//**********************//***********************//**********************
if (t >= Tmax) // TURN COOLER ON IF TEMPERATURE IS EQUAL TO OR EXCEEDS "Tmax" (HEATER remains OFF)
{
digitalWrite(cooler, LOW);
CoolerSts = 1 ;
}
if (t <= setT ) // Turn OFF the COOLER when TEMP GETS DOWN TO "setT" OR GOES BELOW
{ digitalWrite(cooler, HIGH);
CoolerSts = 0 ;
}
if (t <= Tmin) // TURN HEATER "ON" WHEN TEMPERATURE GETS TO "Tmin" OR BELOW (cooler remains OFF)
{
digitalWrite(heater, LOW);
HeaterSts = 1 ;
}
if (t >= setT ) // TURN OFF HEATER WHEN TEMP GETS TO "setT" (and REMAINS LOWER THAN "Tmax")
{ digitalWrite (heater, HIGH);
HeaterSts = 0 ;
}
//***********************//**********************//***********************//**********************
//************************************ Control for HUMIDITY ******************************
//***********************//**********************//***********************//**********************
if (h>=setHmx)
{
digitalWrite(Bigfan,LOW); // Turn fan on when humidity is high
BigFanSts = 1 ;
}
if (h<=setHnr )
{
digitalWrite(Bigfan,HIGH);
BigFanSts=0;
}
if (h<=setHlw)
{
digitalWrite(spray,LOW); // Turn Spray on when humidity is low
SpraySts= 1 ;
}
if (h>=setHnr)
{
digitalWrite(spray,HIGH); // Turn Spray off when humidity is normal or high
SpraySts = 0 ;
}
//***********************//**********************
// OLED PART
//DISPLAY ON THE OLED
//***********************//**********************
tmElements_t tm; //formatting time and date before displaying
if (RTC.read(tm)) {
sprintf(timebuf, "%02d:%02d", tm.Hour, tm.Minute); // format time
u8g.firstPage(); // PICTURE LOOP FOR OLED it's is a doer :)
do {
u8g.setFont(u8g_font_helvB08); // set font for oled display
if (t >= Tmax) //conditions for showing temperature status in the first line (high ,upper range ,normal range,low )
{
u8g.drawFrame(0, 0, 128, 20);
u8g.drawStr( 73, 14, "*HI TEMP*");
}
if (t <= Tmax && t > setT)
{ u8g.drawFrame(0, 0, 128, 20);
u8g.drawStr( 80, 14, "*^^U^^*");
}
if
(t <= setT && t > Tmin)
{ u8g.drawFrame(0, 0, 128, 20);
u8g.drawStr( 80, 14, "> N <");
}
if
(t <= Tmin)
{ u8g.drawFrame(0, 0, 128, 20);
u8g.drawStr( 73, 14, "*LO TEMP*");
}
if (h>=setHmx)
{ u8g.drawFrame(0, 0, 128, 20);
u8g.drawStr( 32, 14, "HMx");
}
if (h>setHnr && h< setHmx)
{ u8g.drawFrame(0, 0, 128, 20);
u8g.drawStr( 32, 14, "Hur");
}
if (h>setHlw && h<=setHnr)
{ u8g.drawFrame(0, 0, 128, 20);
u8g.drawStr( 32, 14, "Hn");
}
if (h<=setHlw)
{ u8g.drawFrame(0, 0, 128, 20);
u8g.drawStr( 32, 14, "HL");
}
//************// Display Time on OLED//**************//
u8g.drawFrame(0, 0, 128, 20); // Draw frame
u8g.setPrintPos(3, 14); // set position for displaying time
u8g.print(timebuf); //display time
//******// Display CURRENT Temperature1&2,humidity , Set Tmax ,Set Tnor and Set Tmin on OLED//*********************
u8g.drawStr(0, 34, "T1:"); // first digit is screen coordinate for X-axis and second for Y-axis
// (it starts on left bottom corner of the text which is to be shown on the oled)
// T1 for temperature from DHT22 and T2 is from Thermistor
u8g.drawStr( 26, 34, dtostrf(t, 5, 2, str));
u8g.drawStr( 56, 34, "\260C");
u8g.drawStr( 70, 34, "T2:");
u8g.drawStr( 88, 34, dtostrf(steinhart, 5, 2, str)); //stienhart is the final Celsius reading
u8g.drawStr( 118, 34, "\260C");
u8g.drawStr( 70, 44, "H:");
u8g.drawStr( 88, 44, dtostrf(h, 5, 2, str));
u8g.drawStr( 119, 44, "%");
u8g.drawStr( 0, 44, "Mx:");
u8g.drawStr( 26, 44, dtostrf(Tmax, 5, 2, str));
u8g.drawStr( 56, 44, "\260C");
u8g.drawStr( 0, 54, "Nr :");
u8g.drawStr( 26, 54, dtostrf(setT, 5, 2, str));
u8g.drawStr( 56, 54, "\260C");
u8g.drawStr( 0, 64, "Mn:");
u8g.drawStr( 26, 64, dtostrf(Tmin, 5, 2, str));
u8g.drawStr( 56, 64, "\260C");
Alarm.delay(500);
} while ( u8g.nextPage() );
}
}
//**********************//**********************//**********************
// LOOP END
//**********************//**********************//**********************
//**********************//**********************//**********************//**********************
//Functions called when daily time specific alarms (above in the loop) triggers:
//***********************************************//**********************//**********************
void ONAlarm() {
/* Tmax = 29; // set day time temperatures
setT = 25;
Tmin = 19;
*/
}
void ON2Alarm() {
setSyncProvider(RTC.get); //It's time, sync the Arduino's INTERNAL Clock to the RTC
}
void OFFAlarm() {
/* Tmax = 26; // set night time temperatures
setT = 23;
Tmin = 19;
*/
}
void OFF2Alarm() {
setSyncProvider(RTC.get); //It's time, sync the Arduino's INTERNAL Clock to the RTC
}
//**********************//**********************//**********************//**********************
//Function for digital clock display (in the SERIAL MONITOR )
//**********************//**********************//**********************//**********************
void digitalClockDisplay() { // digital clock display of the time 24hr format
Serial.print(hour());
printDigits(minute());
printDigits(second());
Serial.println("");
Serial.println(dayStr(weekday()));
Serial.print(monthStr(month()));
Serial.print(" ");
Serial.print(day());
Serial.print(" ");
Serial.println(year());
}
void printDigits(int digits) {
Serial.print(":");
if (digits < 10)
Serial.print('0');
Serial.print(digits);
}
//***********************************************//**********************//**********************
// Un comment the function below and comment the above only one can be used in the code or change names
// 12hrs display function
/*void digitalClockDisplay() //// digital clock display of the time 12hr format
{
Serial.print(hourFormat12());
printDigits(minute());
printDigits(second());
Serial.println("");
Serial.println(dayStr(weekday()));
Serial.print(monthStr(month()));
Serial.print(" ");
Serial.print(day());
Serial.print(" ");
Serial.println(year());
//Alarm.delay(1000);
}
void printDigits(int digits)
{
Serial.print(":");
if (digits < 10) {
Serial.print('0');
}
Serial.print(digits);
}
*/
//That's all folks taaaaan tantan taan .....taetan taetan taetan tantaaaaaaannnnn
Subscribe to:
Posts (Atom)