Monday, December 12, 2016

arduino HC-SR04 anti bounching

HC-SR04

unsigned long delay1,delay2;
if (jarak<=30){

if (millis()-delay1>=2000){
digitalWrite(relay,LOW);
}
}
else { delay1=millis();}
if (jaraK>=200){
if (millis()-delay2>=2000){
digitalWrite(relay,HIGH);
}
}
else { delay2=millis();}

Monday, November 28, 2016

NRF24L01 for remote relay

NRF24L01 for remote relay


//receiver

#include <SPI.h>                       // SPI Arayüzünü dahil ettik.
//#include "nRF24L01.h"
#include "RF24.h"                      // RF24 kütüpanelerini dahil ettik.
#include <Wire.h>
#include <DS3231.h>


DS3231  rtc(SDA, SCL);
// Init a Time-data structure
Time  t;
uint32_t targetTime = 0;
uint8_t hh = 0, mm = 0, ss = 0, dd = 0, bb = 0; //variable Unsignet int 0-255
int yy = 0; //variable integer
byte data[1];                          // Göndereceğimiz data değişkenini oluşturduk.
boolean var;                           // Bit şeklinde var değişkeninini oluşturduk.
const uint64_t pipe = 0xF0F0F0F0E1LL;
RF24 radio(9, 10);                     // Modülün CE pinini 9.pin CS pinini de 10.pine bağlayacağımızı belirttik.

int r1 = 0, r2 = 0, r3 = 0;

void setup() {
  Serial.begin(57600);
  pinMode(3, OUTPUT); digitalWrite(3, HIGH);//kolam renang
  pinMode(5, OUTPUT); digitalWrite(5, HIGH);//kolam naga
  pinMode(7, OUTPUT); digitalWrite(7, HIGH); //lampu naga
  radio.begin();                        
  radio.openReadingPipe(1, pipe);      
  radio.startListening();
  rtc.begin();
}

void loop() {

  // NRF remote

  if (radio.available()) {
    bool var = false;
    while (!var) {
      var = radio.read(&data, 1);
    }//while

    if (data[0] == 1 && r1 == 0) {
      digitalWrite(3, LOW);
     // Serial.println("RELAY 3 LOW");
      r1 = 1; data[0] = 0;
    }
    if (data[0] == 1 && r1 == 1 ) {
      digitalWrite(3, HIGH);
      //Serial.println("RELAY 3 HIGH ");
      r1 = 0; data[0] = 0;
    }

    if (data[0] == 2 && r2 == 0) {
      digitalWrite(5, LOW);
      //Serial.println("RELAY 5 LOW");
      r2 = 1; data[0] = 0;
    }
    if (data[0] == 2 && r2 == 1 ) {
      digitalWrite(5, HIGH);
      //Serial.println("RELAY 5 HIGH ");
      r2 = 0; data[0] = 0;
    }

    if (data[0] == 3 && r3 == 0) {
      digitalWrite(7, LOW);
      //Serial.println("RELAY 7 LOW");
      r3 = 1; data[0] = 0;
    }
    if (data[0] == 3 && r3 == 1 ) {
      digitalWrite(7, HIGH);
      //Serial.println("RELAY 7 HIGH ");
      r3 = 0 ; data[0] = 0;
    }
  }//if

  t = rtc.getTime();  // gate all data time & date from RTC
  hh = t.hour, DEC; //pengambilan data jam
  mm = t.min, DEC; //pengambilan data menit
  ss = t.sec, DEC; //pengambilan data detik
  //Serial.print (hh); Serial.print (F(" : "));
  //Serial.print (mm); Serial.print (F(" : "));
  //Serial.println (ss);

  //jam 9 pagi
  if (hh == 10 && mm == 0 && ss == 0) {
    digitalWrite(3, LOW);//kolam renang
    digitalWrite(5, LOW);//kolam naga
    digitalWrite(7, HIGH);//lampu naga //relay 3
  }
  if (hh == 15 &&  mm == 0 && ss == 0) {
    digitalWrite(3, HIGH);//kolam renang
    digitalWrite(5, HIGH);//kolam naga
    digitalWrite(7, HIGH);//lampu naga
  }
delay(1000);
}



// transmitter
#include  <SPI.h>
//#include "nRF24L01.h"
#include  "RF24.h"
#include <PinChangeInterrupt.h>
#include <avr/sleep.h>


volatile byte flag = 0;
void handler() {
    flag = 1;
    //Serial.println("wake up");
    //delay(100);
    detachPinChangeInterrupt(3);
    detachPinChangeInterrupt(5);
    detachPinChangeInterrupt(7);
}

byte data[1];
const uint64_t pipe = 0xF0F0F0F0E1LL;
RF24 radio(9, 10);                    // Modülün CE pinini 9.pin CS pinini de 10.pine bağlayacağımızı belirttik.
unsigned long nowTime;
unsigned long start1;

unsigned long previousMillis = 0;
unsigned long startSleep;

int kirim = 0,btn3,btn5,btn7;
int sleepStatus = 0;             // variable to store a request for sleep
int count = 0;                   // counter
void wakeUpNow()   {}

void setup() {
  Serial.begin(57600);
  pinMode(3, INPUT_PULLUP);
  pinMode(5, INPUT_PULLUP);
  pinMode(7, INPUT_PULLUP);
  pinMode(13, INPUT);
  digitalWrite(13, LOW);
  attachPCINT(digitalPinToPCINT(3), handler, CHANGE);
  attachPCINT(digitalPinToPCINT(5), handler, CHANGE);
  attachPCINT(digitalPinToPCINT(7), handler, CHANGE);
  radio.begin();
  radio.setRetries(15,15);
  radio.openWritingPipe(pipe);
  radio.startListening();
}
void sleepNow(){
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_enable();
      attachPCINT(digitalPinToPCINT(3), handler, CHANGE);
  attachPCINT(digitalPinToPCINT(5), handler, CHANGE);
  attachPCINT(digitalPinToPCINT(7), handler, CHANGE);
    sleep_mode();
    sleep_disable();
    detachPinChangeInterrupt(3);
    detachPinChangeInterrupt(5);
    detachPinChangeInterrupt(7);
}

void loop() {
//Serial.println("bgn");
  btn3 = digitalRead(3);
  btn5 = digitalRead(5);
  btn7 = digitalRead(7);

  if(flag == 1){
      if (btn3==0) {
        data[0] = 1;
        Serial.println("RELAY 3 ");
      }
      else if (btn5==0) {
        data[0] = 2;
        Serial.println("RELAY 5 ");
      }
      else if (btn7==0) {
        data[0] = 3;
        Serial.println("RELAY 7 ");
      }
 
    radio.stopListening();
    radio.write( &data, sizeof(unsigned long) );
    radio.startListening();
    delay(1000);
    data[0]=9;
    flag = 0;
  }//flag
  startSleep = millis();
  if(startSleep - previousMillis >= 3000) {
    previousMillis = startSleep;
    Serial.println("sleep");
    sleepNow();
  }
}//end loop



Monday, November 7, 2016

nodemcu cloudmqtt servo

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Servo.h>
#include<EEPROM.h>

long lastReconnectAttempt = 0;
int servoPin = D4;
bool statusBall;
const char *statusBall2;
bool statusBall3;
int addressEpp = 0;
Servo servo;
const char *statusServo;
const char *ssid =  "ssid";   // cannot be longer than 32 characters!
const char *pass =  "pass";   //

//Prepare Mqtt connection data
const char *MQTTBroker = "cloudmqtt.com";
const char *MQTTuser = "";
const char *MQTTpassword = "";
//const char *Topic = "/kranstatus";
//const char *Topicid = "/kran";
uint16_t port = 12728;


void cekMem(){
    statusBall=EEPROM.read(1);
 // Serial.println(" memory ");
 // Serial.println(statusBall);
  if(statusBall == 1){
    statusBall2 = "on";
    servoOn();
  }
  if(statusBall == 0){
    statusBall2 ="off";
    servoOff();
  }
 // Serial.println("memory part");
   //Serial.println(statusBall2);
}

void servoOn(){
    servo.attach(servoPin);
    servo.write(86);
    delay(800);
    servo.detach();
   // Serial.println("servo on");
    statusBall2 = "on";
    EEPROM.write(1, 1);
}
void servoOff(){
    servo.attach(servoPin);
    servo.write(250);
    delay(800);
    servo.detach();
    //Serial.println("servo off");
    statusBall2 = "off";
    EEPROM.write(1, 0);
}

//PubSubClient mqtt(MQTTBroker,port);
WiFiClient wclient;
PubSubClient client(wclient, MQTTBroker, port);

void callback(const MQTT::Publish& pub){
  //Serial.println(pub.payload_string());
    if(pub.payload_string()=="on" && statusBall2 == "off" ){
    servoOn();
    //Serial.println("call back on");
  }
  if(pub.payload_string()=="off" && statusBall2 == "on"){
    servoOff();
    //Serial.println("call back off");
  }
}
void WIFI_Connect()
{
  WiFi.disconnect(1);
  Serial.println("Booting Sketch...");
  delay(2000);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, pass);
    int Attempt = 0;
    while (WiFi.status() == 6) {
    delay(100);
    Attempt++;
      if (Attempt == 300) {
        ESP.restart();
      }
    }
 
  client.set_callback(callback);  //Set Callback function

  if (client.connect(MQTT::Connect("kran").set_auth(MQTTuser,MQTTpassword))){
    client.publish("kranstatus", statusBall2);  //publish
    client.subscribe("kranstatus");    //subscribe
  }
   // Serial.print("Wifi connect");
    //Serial.println(WiFi.status());
}
void setup()
{
  statusBall=EEPROM.read(1);
  //Serial.print(" memory --");
  //Serial.println(statusBall);
  if(statusBall == 1){
    statusBall2 = "on";
    servoOn();
  }
  if(statusBall == 0){
    statusBall2 ="off";
    servoOff();
  }
  //Serial.print("memory status");
   //Serial.println(statusBall2);
  //Serial.begin(9600);

  WIFI_Connect();
  //client.set_callback(callback);  //Set Callback function

  //if (client.connect(MQTT::Connect("kran").set_auth(MQTTuser,MQTTpassword))){
  //  client.publish("kranstatus", statusBall2);  //publish
  //  client.subscribe("kranstatus");    //subscribe
  //}

}


void loop()
{

      //delay(1000);
      //client.subscribe("kranstatus");
      //client.publish("kranstatus", statusBall2);  //publish
    //Serial.print("status loop ");
    //Serial.println(WiFi.status());
    delay(2000);
    if (WiFi.status() == 6)
    {
      //Serial.println("putus koneksi");
      WIFI_Connect();
    }
    else
    {
      if(!client.subscribe("kranstatus")){
        WIFI_Connect();
      }
      if(!client.publish("kranstatus", statusBall2)){
        WIFI_Connect();
      }

      //delay(1000);
      //client.subscribe("kranstatus");
      //client.publish("kranstatus", statusBall2);  //publish
    }

client.loop();

 
}

Wednesday, October 26, 2016

Nodemcu 12E with servo mg995

#include <ESP8266WiFi.h>
#include <Servo.h>
const char* ssid = "";
const char* password = "";

//int ledPin = 13; // GPIO13
int val = 0;     // variable for reading the pin status
int servoPin = D4;
Servo servo;
int flag = 1;
int tranPin = 14; //Transister base pin

WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  delay(10);
  pinMode(tranPin, OUTPUT);

  Serial.begin(9600);

  servo.attach(servoPin);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  // Match the request

  int value = LOW;
  if (request.indexOf("/LED=ON") != -1)  {
    /*
    if(flag ==0){
      digitalWrite(tranPin, HIGH); //turn on servo power
      servo.write(60);
      delay(800);
      digitalWrite(tranPin, LOW); //turn on servo power
      flag = 1;
    }
    */
    servo.attach(servoPin);
    servo.write(60);
    delay(800);
    servo.detach();
    value = HIGH;
  }
  if (request.indexOf("/LED=OFF") != -1)  {
    /*
    if(flag == 1){
      digitalWrite(tranPin, HIGH); //turn on servo power
      servo.write(150);
      delay(800);
      digitalWrite(tranPin, LOW); //turn on servo power
      flag = 0;
    }
    */
    servo.attach(servoPin);
    servo.write(150);
    delay(800);
    servo.detach();
    value = LOW;
  }

// Set ledPin according to the request
//digitalWrite(ledPin, value);

  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");

  client.print("Valve is now: ");

  if(value == HIGH) {
    client.print("ON");
  } else {
    client.print("OFF");
  }
  client.println("<br><br>");
  client.println("<a href=\"/LED=ON\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/LED=OFF\"\"><button>Turn Off </button></a><br />");
  client.println("</html>");

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");

}

Thursday, August 18, 2016

NRF24L01

// http://www.bajdi.com
// Sending a struct with the nRF24L01 module
// Data to be sent is the reading of 2 analog pins
// Data received is the analog reading of 2 pins on the other Arduino 

#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"

RF24 radio(1,2);  // make sure this corresponds to the pins you are using
const uint64_t pipes[2] = { 
  0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };

const int led = 0;

typedef struct{
  int A;
  int B;
  float C;
  float D;
}
A_t;

typedef struct{
  int W;
  int X;
  float Y;
  float Z;
}
B_t;

A_t duino1;  
B_t duino2; 

void setup()
{
  Serial.begin(57600);
  pinMode(led, OUTPUT);
  radio.begin();
  radio.openWritingPipe(pipes[0]);
  radio.openReadingPipe(1,pipes[1]);
}

void loop(void)
{
  // we need data to sent...
  duino2.W = analogRead(A0);
  duino2.X = analogRead(A1);
  duino2.Y = analogRead(A0)/102.3;
  duino2.Z = analogRead(A1)/102.3;
  // end of analog reading

  // radio stuff
  radio.stopListening();
  bool ok = radio.write( &duino2, sizeof(duino2) );
  radio.startListening();

  unsigned long started_waiting_at = millis();
  bool timeout = false;
  while ( ! radio.available() && ! timeout )
    if (millis() - started_waiting_at > 250 )
      timeout = true;

  if ( timeout )
  {
    Serial.println("Failed, response timed out.");
    digitalWrite(led, HIGH);
  }
  else
  {
    radio.read( &duino1, sizeof(duino1) );
    digitalWrite(led, LOW);
  }
  // end of radio stuff

  // serial print received data
  Serial.print("duino1.A = ");
  Serial.println(duino1.A);
  Serial.print("duino1.B = ");
  Serial.println(duino1.B);
  Serial.print("duino1.C = ");
  Serial.println(duino1.C);
  Serial.print("duino1.D = ");
  Serial.println(duino1.D);
  // end of serial printing
}


============================================================


// http://www.bajdi.com
// Sending a struct with the nRF24L01 module
// Data to be sent is the reading of 2 analog pins
// Data received is the analog reading of 2 pins on the other Arduino 

#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"

typedef struct{
  int A;
  int B;
  float C;
  float D;
}
A_t;

typedef struct{
  int W;
  int X;
  float Y;
  float Z;
}
B_t;

A_t duino1;  
B_t duino2;

RF24 radio(8,9);   // make sure this corresponds to the pins you are using
const uint64_t pipes[2] = { 
  0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };

void setup()
{
  Serial.begin(57600);
  radio.begin();
  radio.openWritingPipe(pipes[1]);
  radio.openReadingPipe(1,pipes[0]);
  radio.startListening();
}

void loop(void)
{ 
  // we need data to sent...
  duino1.A = analogRead(A0);
  duino1.B = analogRead(A1);
  duino1.C = analogRead(A0)/102.3;
  duino1.D = analogRead(A1)/102.3;
  // end of analog reading

  // radio stuff
  if ( radio.available() )
  {
    bool done = false;
    while (!done)
    {
      done = radio.read( &duino2, sizeof(duino2) );
    }
    radio.stopListening();
    radio.write( &duino1, sizeof(duino1) );
    radio.startListening();
  }
  // end of radio stuff

  // serial print received data 
  Serial.print("duino2.W = ");
  Serial.println(duino2.W);
  Serial.print("duino2.X = ");
  Serial.println(duino2.X);
  Serial.print("duino2.Y = ");
  Serial.println(duino2.Y);
  Serial.print("duino2.Z = ");
  Serial.println(duino2.Z);
  // end of serial printing
}

Sunday, August 14, 2016

Simple NRF24L01 wireless remote

Code for Receiver
#include <"spi .h">
#include "nRF24L01.h"
#include "RF24.h"
int msg[1];
RF24 radio(9,10);
const uint64_t pipe = 0xE8E8F0F0E1LL;
int LED1 = 3;
void setup(void){
 Serial.begin(9600);
 radio.begin();
 radio.openReadingPipe(1,pipe);
 radio.startListening();
 pinMode(LED1, OUTPUT);
}
void loop(void){
 if (radio.available()){
   bool done = false;  
   while (!done){
     done = radio.read(msg, 1);    
     Serial.println(msg[0]);
     if (msg[0] == 111){
        delay(10);
        digitalWrite(LED1, HIGH);
     }
     else {digitalWrite(LED1, LOW);}
     delay(10);
}
}
 else{Serial.println("No radio available");}}
============================================
code for transmitter




#include  <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
int msg[1];
RF24 radio(9,10);
const uint64_t pipe = 0xE8E8F0F0E1LL;
int SW1 = 7;
void setup(void){
 Serial.begin(9600);
 radio.begin();
 radio.openWritingPipe(pipe);
}
 void loop(void){
 if (digitalRead(SW1) == HIGH){
 msg[0] = 111;
 radio.write(msg, 1);}}

NRF24L01 multi receiver

hardware: 0.1 uf capacitors recommended The connections are laid out in detail in the first link on the prior page. Basically, the pins in the lower right corners of the diagrams above must be connected to the corresponding Arduino pins. VCC must be 3.3V and CE and CSN from the NRF24L01+ connect to pins 7 and 8, respectively, on the Arduino. The IRQ pin is unnecessary in this application. Soldering a 0.1 uf capacitor between the VCC and ground pins of the NRF24L01+ is a good idea.
 
This example is a frivolous game in which the PRX generates a random number and the nodes try to guess the number. Its real purpose is to demonstrate the network in action.
While I think Codebender is fantastic, Please copy the code out of Codebender because the RF24.h library in Codebender appears to be an older version.
First, the code for the PRX primary receiver (hub)
=======================================================
// An example demonstrating the multiceiver capability of the NRF24L01+
// in a star network with one PRX hub and up to six PTX nodes

//This sketch is a modification from a video on the ForceTronics YouTube Channel,
//which code was leveraged from http://maniacbug.github.io/RF24/starping_8pde-example.html
//This sketch is free to the public to use and modify at your own risk

#include <SPI.h> //Call SPI library so you can communicate with the nRF24L01+
#include <nRF24L01.h> //nRF2401 libarary found at https://github.com/tmrh20/RF24/
#include <RF24.h> //nRF2401 libarary found at https://github.com/tmrh20/RF24/

const int pinCE = 7; //This pin is used to set the nRF24 to standby (0) or active mode (1)
const int pinCSN = 8; //This pin is used to tell the nRF24 whether the SPI communication is a command or message to send out
RF24 radio(pinCE, pinCSN); // Declare object from nRF24 library (Create your wireless SPI)

//Create up to 6 pipe addresses P0 - P5;  the "LL" is for LongLong type
const uint64_t rAddress[] = {0x7878787878LL, 0xB3B4B5B6F1LL, 0xB3B4B5B6CDLL, 0xB3B4B5B6A3LL, 0xB3B4B5B60FLL, 0xB3B4B5B605LL };

byte daNumber = 0; //The number that the transmitters are trying to guess

void setup()  
{
  randomSeed(analogRead(0)); //create unique seed value for random number generation
  daNumber = (byte)random(11); //Create random number that transmitters have to guess
  Serial.begin(115200);  //start serial to communication
  Serial.print("The number they are trying to guess is: ");
  Serial.println(daNumber); //print the number that they have to guess
  Serial.println();
  radio.begin();  //Start the nRF24 module

  radio.setPALevel(RF24_PA_LOW);  // "short range setting" - increase if you want more range AND have a good power supply
  radio.setChannel(108);          // the higher channels tend to be more "open"

  // Open up to six pipes for PRX to receive data
  radio.openReadingPipe(0,rAddress[0]);
  radio.openReadingPipe(1,rAddress[1]);
  radio.openReadingPipe(2,rAddress[2]);
  radio.openReadingPipe(3,rAddress[3]);
  radio.openReadingPipe(4,rAddress[4]);
  radio.openReadingPipe(5,rAddress[5]);
 
  radio.startListening();                 // Start listening for messages
}

void loop()
{  
    byte pipeNum = 0; //variable to hold which reading pipe sent data
    byte gotByte = 0; //used to store payload from transmit module
   
    while(radio.available(&pipeNum)){ //Check if received data
     radio.read( &gotByte, 1 ); //read one byte of data and store it in gotByte variable
     Serial.print("Received guess from transmitter: ");
     Serial.println(pipeNum + 1); //print which pipe or transmitter this is from
     Serial.print("They guess number: ");
     Serial.println(gotByte); //print payload or the number the transmitter guessed
     if(gotByte != daNumber) { //if true they guessed wrong
      Serial.println("Fail!! Try again.");
     }
     else { //if this is true they guessed right
      if(sendCorrectNumber(pipeNum)) Serial.println("Correct! You're done."); //if true we successfully responded
      else Serial.println("Write failed"); //if true we failed responding
     }
     Serial.println();
    }

   delay(200);  
}

 //This function turns the receiver into a transmitter briefly to tell one of the nRF24s
//in the network that it guessed the right number. Returns true if write to module was
//successful
bool sendCorrectNumber(byte xMitter) {
    bool worked; //variable to track if write was successful
    radio.stopListening(); //Stop listening, start receiving data.
    radio.openWritingPipe(rAddress[xMitter]); //Open writing pipe to the nRF24 that guessed the right number
      // note that this is the same pipe address that was just used for receiving
    if(!radio.write(&daNumber, 1))  worked = false; //write the correct number to the nRF24 module, and check that it was received
    else worked = true; //it was received
    radio.startListening(); //Switch back to a receiver
    return worked;  //return whether write was successful
}

=========================================================
And now the code for the PTX primary transmitters (nodes)

// An example demonstrating the multiceiver capability of the NRF24L01+
// in a star network with one PRX hub and up to six PTX nodes

//This sketch is a modification from a video on the ForceTronics YouTube Channel,

//which code was leveraged from http://maniacbug.github.io/RF24/starping_8pde-example.html

//This sketch is free to the public to use and modify at your own risk


#include <SPI.h> //Call SPI library so you can communicate with the nRF24L01+

#include <nRF24L01.h> //nRF2401 libarary found at https://github.com/tmrh20/RF24/

#include <RF24.h> //nRF2401 libarary found at https://github.com/tmrh20/RF24/

const int pinCE = 7; //This pin is used to set the nRF24 to standby (0) or active mode (1)

const int pinCSN = 8; //This pin is used to tell the nRF24 whether the SPI communication is a command or message to send out


RF24 radio(pinCE, pinCSN); // Create your nRF24 object or wireless SPI connection

#define WHICH_NODE 2     // must be a number from 1 - 6 identifying the PTX node

const uint64_t wAddress[] = {0x7878787878LL, 0xB3B4B5B6F1LL, 0xB3B4B5B6CDLL, 0xB3B4B5B6A3LL, 0xB3B4B5B60FLL, 0xB3B4B5B605LL};

const uint64_t PTXpipe = wAddress[ WHICH_NODE - 1 ];   // Pulls the address from the above array for this node's pipe

byte counter = 1; //used to count the packets sent

bool done = false; //used to know when to stop sending packets


void setup()

{

  Serial.begin(115200);   //start serial to communicate process

  randomSeed(analogRead(0)); //create unique seed value for random number generation

  radio.begin();            //Start the nRF24 module

  radio.setPALevel(RF24_PA_LOW);  // "short range setting" - increase if you want more range AND have a good power supply
  radio.setChannel(108);          // the higher channels tend to be more "open"

  radio.openReadingPipe(0,PTXpipe);  //open reading or receive pipe

  radio.stopListening(); //go into transmit mode

}

void loop()

{

   if(!done) { //true once you guess the right number

     byte randNumber = (byte)random(11); //generate random guess between 0 and 10

     radio.openWritingPipe(PTXpipe);        //open writing or transmit pipe

     if (!radio.write( &randNumber, 1 )){  //if the write fails let the user know over serial monitor

         Serial.println("Guess delivery failed");    

     }

     else { //if the write was successful

          Serial.print("Success sending guess: ");

          Serial.println(randNumber);

     

        radio.startListening(); //switch to receive mode to see if the guess was right

        unsigned long startTimer = millis(); //start timer, we will wait 200ms

        bool timeout = false;

        while ( !radio.available() && !timeout ) { //run while no receive data and not timed out

          if (millis() - startTimer > 200 ) timeout = true; //timed out

        }

   

        if (timeout) Serial.println("Last guess was wrong, try again"); //no data to receive guess must have been wrong

        else  { //we received something so guess must have been right

          byte daNumber; //variable to store received value

          radio.read( &daNumber,1); //read value

          if(daNumber == randNumber) { //make sure it equals value we just sent, if so we are done

            Serial.println("You guessed right so you are done");

            done = true; //signal to loop that we are done guessing

          }

          else Serial.println("Something went wrong, keep guessing"); //this should never be true, but just in case

        }

        radio.stopListening(); //go back to transmit mode

     }

   }

    delay(1000);
}
=========================================
The #define WHICH_NODE statement needs to be altered for each node. Otherwise, the code is the same.
When running, I suggest powering the PRX first and starting the serial monitor for it. Otherwise you might miss the action!
ENJOY! And please do comment on any way in which this Instructable might be improved.

Saturday, June 25, 2016

How to disable internal Arduino ATMEGA pullups on SDA and SCL with I2C bus

just edit libraries/wire/utility/twi.c and comment out the following:
// activate internal pullups for twi.
  digitalWrite(SDA, 1);
  digitalWrite(SCL, 1);


Doing this in the sketch seems to be equivalent:
pinMode(SDA, INPUT);
pinMode(SCL, INPUT);
Even doing this immediately after Wire.begin() potentially still sends 5V glitches on SDA/SCL.

(tested with arduino-1.6.0 on a NANO)

Thursday, May 5, 2016

humidity sensor

#define DHTPIN 2  
#define RELAYPIN 4
#define DHTTYPE DHT11   // DHT 21 (AM2301)
#define next 9
#define INC 7
#define set_mode 5

/* ----- C Program for Arduino based Alarm Clock ---- */
#include <Wire.h>
#include<EEPROM.h>

#include <LiquidCrystal_I2C.h>
#include "DHT.h"
DHT dht(DHTPIN, DHTTYPE);

LiquidCrystal_I2C lcd(0x27, 16, 2);

unsigned long previousMillis = 0;
const long interval = 5000;

int HMIN,HMAX,h,t;
int add = 11;
  int st=0; //var for void match
  int sb=0;//var for void match
void setup()
{
 cekMem();
 //Serial.begin(9600);
 Wire.begin();
 dht.begin();
 lcd.init();
 lcd.backlight();

 pinMode(INC, INPUT);
 pinMode(next, INPUT);
 pinMode(set_mode, INPUT);
 pinMode(RELAYPIN, OUTPUT);
 digitalWrite(next, HIGH);
 digitalWrite(set_mode, HIGH);
 digitalWrite(INC, HIGH);

   lcd.setCursor(0,0);
   lcd.print("Sensor Starting..");
    delay(2000);

}

void loop()
{
  //unsigned long currentMillis = millis();
  h = dht.readHumidity();
  t = dht.readTemperature();
  if (isnan(t) || isnan(h)) {
    lcd.setCursor(1,0);
    lcd.print("Error");
    lcd.setCursor(0,1);
    lcd.print("Check Sensor cable");
  }
  else {
    lcd.clear();
    lcd.print("Now: T:");
    lcd.print(t);
    lcd.print(" H: ");
    lcd.print(h);
    lcd.setCursor(0, 1);
    lcd.print("H Min/max: ");
    lcd.print(HMIN);
    lcd.print("/");
    lcd.print(HMAX);
    delay(1000);
  }
  if(digitalRead(set_mode)==0){
    lcd.clear();
    lcd.setCursor(1,0);
    setHmin();

    lcd.clear();
    lcd.setCursor(1,0);
    lcd.print("Setting Humidity");
    lcd.setCursor(0,1);
    lcd.print("tersimpan");
    delay(2000);  
  }
  match();
}//loop
void setHmin(){
     lcd.setCursor(1,0);
     lcd.clear();
     lcd.print("SET H MIN");
     lcd.setCursor(0,1);
     lcd.print(HMIN);
     int temp=1,hmin1=0,hmax1=0;
     while(temp==1){
        if(digitalRead(INC)==0){
          HMIN++;
           lcd.setCursor(0,1);
           lcd.print(HMIN);
            if(HMIN==99){
               HMIN=65;
           }//if(HMIN==99){
          //while(digitalRead(INC)==0);
        }//if(digitalRead(INC)==0){
         delay(1000);
        if(digitalRead(next)==0){
          hmin1=HMIN;
          EEPROM.write(add++,hmin1);
          lcd.clear();
          lcd.setCursor(1,0);
          lcd.print("H MIN SAVED at: ");
          lcd.setCursor(0,1);
          lcd.print(HMIN);
          delay(3000);
          while(digitalRead(next)==0);
          temp=2;
        }//if(digitalRead(next)==0)
      }//while temp==1
    while(temp==2){
      //setting HMAX
      lcd.clear();
      lcd.setCursor(1,0);    
      lcd.print("Set H MAX");
     lcd.setCursor(0,1);
     lcd.print(HMAX);    
      if(digitalRead(INC)==0){
        HMAX++;
        lcd.setCursor(0,1);
        lcd.print(HMAX);      
        if(HMAX==99){
          HMAX=65;
        }//if(HMAX==99){
        //while(digitalRead(next)==0);//?
      }

        delay(1000);
      if(digitalRead(next)==0){
       hmax1=HMAX;
       EEPROM.write(add++, hmax1);
       lcd.clear();
       lcd.setCursor(1,0);
       lcd.print("H MAX Saved at: ");
       lcd.setCursor(0,1);
       lcd.print(HMAX);
       temp=0;
       while(digitalRead(next)==0);
       }//if(digitalRead(next)==0){
     }//if(digitalRead(INC)==0){
     delay(1000);


//}//while temp=2
}//setHmin()
void cekMem(){
    int tem[17];
  for(int i=11;i<17;i++)
  {
    tem[i]=EEPROM.read(i);
  }
  HMIN= tem[11];
  HMAX =tem[12];
  if(HMIN >= 100) { HMIN = 65;}
    else if(HMIN <= 65) {HMIN = 60; }
  if(HMAX >=100){ HMAX=65;}
    else if (HMAX <= 65) {HMAX = 60; }
}

void match(){
    /if (currentMillis - previousMillis >= interval) {
   
    //}
    if((HMIN >= h) && (st==0) ){
      digitalWrite(RELAYPIN, HIGH);
      st=1;
      sb=0;
    }
    if((HMAX <= h) && (sb==0)){
      digitalWrite(RELAYPIN, LOW);
      sb=1;
      st=0;
    }
}//void match

Sunday, April 3, 2016

ARDUINO TWO PIR WITH MILIS

int calibrationTime = 5;      

//the time when the sensor outputs a low impulse
long unsigned int lowIn;        

//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;

boolean lockLow = true;
boolean takeLowTime;

int pirPin = 3;    //the digital pin connected to the PIR sensor's output
int pirPin2 = 4;    //the digital pin connected to the PIR sensor's output
int ledPin = 13;


/////////////////////////////
//SETUP
void setup(){
  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  pinMode(pirPin2, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(pirPin, LOW);

  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
    for(int i = 0; i < calibrationTime; i++){
      Serial.print(".");
      delay(1000);
      }
    Serial.println(" done");
    Serial.println("SENSOR ACTIVE");
    delay(50);
  }

////////////////////////////
//LOOP
void loop(){

     if((digitalRead(pirPin) ||digitalRead(pirPin2))  == HIGH){
       digitalWrite(ledPin, HIGH);   //the led visualizes the sensors output pin state
       if(lockLow){
         //makes sure we wait for a transition to LOW before any further output is made:
         lockLow = false;          
         Serial.println("---");
         Serial.print("motion detected at ");
         Serial.print(millis()/1000);
         Serial.println(" sec");
         delay(50);
         }        
         takeLowTime = true;
       }

     if((digitalRead(pirPin) ||digitalRead(pirPin2))  == LOW){      
       digitalWrite(ledPin, LOW);  //the led visualizes the sensors output pin state

       if(takeLowTime){
        lowIn = millis();          //save the time of the transition from high to LOW
        takeLowTime = false;       //make sure this is only done at the start of a LOW phase
        }
       //if the sensor is low for more than the given pause,
       //we assume that no more motion is going to happen
       if(!lockLow && millis() - lowIn > pause){
           //makes sure this block of code is only executed again after
           //a new motion sequence has been detected
           lockLow = true;                      
           Serial.print("motion ended at ");      //output
           Serial.print((millis() - pause)/1000);
           Serial.println(" sec");
           delay(50);
           }
       }
  }

Sunday, March 20, 2016

arduino RF-Receiver Code

/* Example for receiving http://code.google.com/p/rc-switch/ If you want to visualize a telegram copy the raw data and paste it into http://test.sui.li/oszi/ */ #include RCSwitch mySwitch = RCSwitch(); int a=0; int relay = 5; void setup() { Serial.begin(9600); mySwitch.enableReceive(0); // Receiver on inerrupt 0 => that is pin #2 } void loop() { if (mySwitch.available()) { a = mySwitch.getReceivedValue(); if(a == 17715){ //Serial.println("Relay ON"); digitalWrite(ledPin, HIGH); } if(a == 17724){ //Serial.println("Relay OFF"); digitalWrite(ledPin, LOW); } mySwitch.resetAvailable(); } }