In the if (user == "A") code part {- It works, but if I put - if (user == '') <- here is invisible, but it's an asterisk {- It won't, it goes through this if, and follows the code, I'm using a matrix keyboard in arduino ... I already gave a serial.print to see, the "", responds on the keyboard but it won't.
void NovoUser() {
lcd.clear();
delay(10);
lcd.setCursor(1, 0);
lcd.print("***Novo Usuario***");
String usuario = ler(1, "Digite seu usuario:", 1, false);
bool existente = usuarioExistente(usuario);
if (usuario == "A") {
Serial.print(usuario);
lcd.clear();
lcd.setCursor(0, 1);
lcd.print("Usuario invalido");
delay(1000);
NovoUser();
} else {
if (!existente) { /*existe*/
lcd.clear();
lcd.setCursor(0, 1);
lcd.print("Usuario existente");
delay(1000);
existente = false;
return NovoUser();
} else {
lcd.clear();
String senha = ler(1, "Digite sua senha:", 4, false);
if (incluiUsuario(usuario, senha)) {
lcd.clear();
lcd.setCursor(0, 1);
lcd.print("Usuario incluido");
delay(1500);
Menu();
} else {
lcd.setCursor(0, 4);
lcd.print("erro");
delay(2000);
}
}
}
}
Related
I have an arduino anti-theft sistem.
The problem is the function void disarm()
//define Variables
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <RTClib.h>
//LCD
#define I2C_ADDR 0x27
#define LCD_COLUMNS 20
#define LCD_LINES 4
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
RTC_DS1307 rtc;
// Definire PINI
const int ledPin4 = 4;
const int ledPin5 = 5;
int lastButtonstate = LOW;
int lastState;
int button = 3;
// PIR
int pir = 2; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int val = 0;
//Senzor dist
#define trigerPin 9
#define echoPin 10
long duration, distance;
// Arm/Disarm
bool isArmed = false;
//tastatura si parola
char password[5] ="1234"; //create a password
int pozisyon = 0; //keypad position
const byte rows = 4; //number of the keypad's rows and columns
const byte cols = 4;
char keyMap [rows] [cols] = { //define the cymbols on the buttons of the keypad
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins [rows] = {14, 15, 16, 17}; //pins of the keypad
byte colPins [cols] = {18, 19, 20, 21};
Keypad myKeypad = Keypad( makeKeymap(keyMap), rowPins, colPins, rows, cols);
void setup() {
Serial.begin(9600);
rtc.begin();
pinMode(trigerPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(pir, INPUT);
//Setup for LEDs
pinMode(ledPin4, OUTPUT);
pinMode(ledPin5, OUTPUT);
// Pin Mode Buton
lastState = digitalRead(button);
//Setup for LCD
lcd.init();
lcd.backlight();
lcd.setCursor(5,0);
lcd.print(" Sistem ");
lcd.setCursor(2,1);
lcd.print(" anti-efractie ");
delay(1000);
lcd.clear();
}
void loop() {
int currState = digitalRead(button);
if(currState != lastState && currState == HIGH) {
if(!isArmed) {
arm();
}
else if(isArmed) {
disarm();
}
}
lastState = currState;
pirsenzor();
distsenzor();
delay(100);
}
//=================================FUNCTII & SENZORI=================================
void arm() {
if(!isArmed) {
// Armare si cerere parola
lcd.clear();
lcd.print("Armare sistem");
delay(1000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Introduceti codul:");
delay(50);
int attempts = 0;
do {
char whichKey = myKeypad.getKey();
if (whichKey != NO_KEY) {
lcd.setCursor(pozisyon, 1);
lcd.print("*");
password[pozisyon] = whichKey;
pozisyon++;
}
if (pozisyon == 4) {
// Verificare parola corecta
if(strcmp(password, "1234") == 0) {
digitalWrite(ledPin5, HIGH);
delay(300);
digitalWrite(ledPin5, LOW);
delay(300);
digitalWrite(ledPin5, HIGH);
delay(300);
digitalWrite(ledPin5, LOW);
delay(300);
digitalWrite(ledPin5, HIGH);
delay(300);
digitalWrite(ledPin5, LOW);
lcd.clear();
lcd.setCursor(5, 0);
lcd.print("Sistem armat");
delay(3000);
lcd.clear();
isArmed = true;
break;
}
else {
// Verificare parola incorecta
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Parola Incorecta!");
delay(1000);
lcd.clear();
pozisyon = 0;
attempts++;
if(attempts == 1)
{
lcd.clear();
break;
}
continue;
}
}
} while (!isArmed);
}
}
void disarm() {
if(isArmed) {
// Dezarmare si cerere parola
lcd.clear();
lcd.print("Dezarmare sistem");
Serial.println("Sunt aici");
delay(1000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Introduceti codul:");
delay(50);
int attempts = 0;
do {
char whichKey = myKeypad.getKey();
if (whichKey != NO_KEY) {
lcd.setCursor(pozisyon, 1);
lcd.print("*");
password[pozisyon] = whichKey;
pozisyon++;
}
if (pozisyon == 4) {
// Verificare parola corecta
if(strcmp(password, "1234") == 0) {
Serial.println("Am trecut de asta");
digitalWrite(ledPin4, HIGH);
delay(300);
digitalWrite(ledPin4, LOW);
delay(300);
digitalWrite(ledPin4, HIGH);
delay(300);
digitalWrite(ledPin4, LOW);
delay(300);
digitalWrite(ledPin4, HIGH);
delay(300);
digitalWrite(ledPin4, LOW);
lcd.clear();
lcd.setCursor(5, 0);
lcd.print("Sistem dezarmat");
Serial.println("Am facut asta");
delay(3000);
isArmed = false;
lcd.clear();
break;
}
else {
// Verificare parola incorecta
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Parola Incorecta!");
delay(1000);
lcd.clear();
pozisyon = 0;
attempts++;
if(attempts == 3)
{
lcd.clear();
break;
}
}
}
} while (isArmed);
}
}
// Senzor PIR
void pirsenzor() {
distsenzor();
val = digitalRead(pir); // read input value
if (val == HIGH && !isArmed && distance <= 250) {
digitalWrite(ledPin4, HIGH);
delay(300);
digitalWrite(ledPin4, LOW);
delay(300);
digitalWrite(ledPin4, HIGH);
delay(300);
digitalWrite(ledPin4, LOW); // turn LED ON
if (pirState == LOW) {
lcd.setCursor(0, 0);
lcd.print("Motion detected at");
lcd.setCursor(0, 1);
lcd.print(distance);
lcd.print(" m ");
pirState = HIGH;
}
} else {
digitalWrite(ledPin4, LOW); // turn LED OFF
if (pirState == HIGH) {
lcd.clear();
pirState = LOW;
}
}
}
//Senzor distanta
void distsenzor() {
digitalWrite(trigerPin, LOW); // ensure trigger is low
delayMicroseconds(2);
digitalWrite(trigerPin, HIGH); // send a 10us high to trigger
delayMicroseconds(10);
digitalWrite(trigerPin, LOW);
duration = pulseIn(echoPin, HIGH); //Measure the duration of the echo pulse
distance = (duration / 2) / 29.1; //Calculate the distance using the speed of sound
if (distance >= 400 || distance <= 2) { //Check if the distance is out of range
}
}
Everything is good I push the button to arm the system, the system ask to introduce the password everything is ok but when disarm function is called the function bypass password verification step.
A mention I have a pushbutton with a double function (arm/disarm system).
Sorry for my bad english :).
a suggestion or a solution please.
When you arm the system with
isArmed = true;
you should also reset
pozisyon = 0;
because pozisyon == 4 is used as an indicator that a password has been entered
This is my code:
#include <Keypad.h>
#include <LiquidCrystal.h>
#include <Ethernet.h>
#include <SPI.h>
bool hands = false;
bool result = true;
char Key;
unsigned int Number=0;
String weight;
String path;
bool alreadyConnected = false; // whether or not the client was connected previously
int cnt=0;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 1, 2 }; // ip in lan
byte gateway[] = { 192, 168, 1, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
LiquidCrystal lcd(35, 34, 33, 32, 31, 30);
EthernetServer server(9639); //server port
EthernetClient client;
char keys[4][4] = {
{'1', '2', '3','A'},
{'4', '5', '6','B'},
{'7', '8', '9','C'},
{'*', '0', '#','D'},
};
byte rowpins[4] = {22, 23, 24, 25};
byte colpins[4] = {26, 27, 28, 29};
Keypad mykeypad = Keypad(makeKeymap(keys), rowpins, colpins, 4, 4);
String readString;
void setup()
{
lcd.begin(20, 4);
Ethernet.begin(mac, ip, gateway, subnet);
if (Ethernet.linkStatus() == LinkOFF) {
lcd.setCursor(0, 0);
lcd.print(" :Error: ");
lcd.setCursor(0, 1);
lcd.print("Ethernet Cable");
lcd.setCursor(0, 2);
lcd.print("Not Connected!");
Serial.println("Ethernet cable is not connected.");
while(true);
}
Serial.begin(19200);
Serial1.begin(19200);
EthernetClient client = server.available();
lcd.setCursor(0, 1);
lcd.print(" Connecting... ");
delay(5000);
if (client.connect(gateway, 9639))
{
client.print("A");
Serial.println("Connecting MilkyWeigh Server...");
}
else
{ lcd.clear();
lcd.setCursor(0, 1);
lcd.print("1.Check LAN Cable");
lcd.setCursor(0, 2);
lcd.print(" --Reset MilkoSol-- ");
while (true);
}
server.begin();
while (true) {
client = server.available(); // wait for a new client:
if (client)
{
while (client.connected())
{
if (client.available())
{
char b = client.read();
if (b == 'B')
{
lcd.setCursor(0, 2);
lcd.print(" Connected! ");
Serial.println("Successfully Connected!");
delay(1500);
hands = true;
b = "";
} //if B comes, handshaking done
} // if client available
} //while client connected
} //if (client)
if (hands == true)
{
lcd.clear();
client.stop();
break;
}
} //while true
lcd.setCursor(0, 0);
lcd.print ("Input Code: ");
lcd.print (Number);
} // void setup
void loop()
{
while (Key == NO_KEY){
Key = mykeypad.getKey();
}
DetectButtons();
if (Key == '4')
{
SaveToServer();
delay(200);
SaveToServer();
}
if (Key == '#')
{
if (Number > 0)
{
GetName();
}
Getweight();
}
Key=NO_KEY;
}
void Getweight(){
while (Serial1.available()>0)
{
weight = Serial1.readStringUntil('\r');
Serial1.flush();
}
Serial.print(weight);
}
void SaveToServer()
{
if (client.connect(gateway, 9639))
{
client.print('#'+String(Number)+','+weight);
//client.stop();
}
else
{ lcd.clear();
lcd.setCursor(0, 2);
lcd.print(" Save Error ");
Serial.println("Try again!");
Number=0;
readString="";
// weight="";
alreadyConnected=false;
return 0;
}
server.begin();
EthernetClient client = server.available(); // Listening for client (i.e. server) response
if (client)
{
if (!alreadyConnected)
{
// clear out the input buffer:
client.flush();
alreadyConnected = true;
}
while (client.connected())
{
if (client.available())
{
if (client.available()>0)
{
char z = client.read();
if (z == 'K')
{
Serial.print("Success: Data Saved!");
lcd.clear();
lcd.setCursor(6, 2);
lcd.print("Success!");
delay(1500);
Number=0;
weight="";
readString="";
DisplayResult();
}
client.flush();
client.stop();
}
}
}
} // if client
}// SaveToServer
void GetName()
{
if (client.connect(gateway, 9639))
{
client.print(Number);
//client.stop();
}
else
{ lcd.clear();
lcd.setCursor(0, 2);
lcd.print(" Connection Failed! ");
Serial.println("Connection Failed!");
Number=0;
readString="";
// weight="";
alreadyConnected=false;
return 0;
}
server.begin();
EthernetClient client = server.available(); // Listening for client (i.e. server) response
if (client)
{
if (!alreadyConnected)
{
// clear out the input buffer:
client.flush();
alreadyConnected = true;
}
while (client.connected())
{
if (client.available())
{
readString="";
while (client.available()>0)
{
//client.readStringUntil('?');
readString = client.readStringUntil('?');
client.flush();
client.stop();
}
}
}
if (readString == "err")
{
lcd.clear();
lcd.setCursor(0, 2);
lcd.print("Not found,Try again!");
Serial.println("Not found,Try again!");
delay(1500);
Number=0;
readString="";
hands = true;
DisplayResult();
}
else
{
lcd.clear();
DisplayResult();
Serial.println(readString);
hands = true;
}
} // if client
}// GetName
void DetectButtons()
{
// path = path + "DetectButtons";
//Serial.println(path);
if (Key == '*') //If cancel Button is pressed
{
Serial.println ("Button Cancel");
Number = 0;
weight = "";
readString="";
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Input Code: ");
lcd.setCursor(0, 1);
lcd.print(" ");
lcd.setCursor(0, 2);
lcd.print(" ");
lcd.setCursor(0, 3);
lcd.print(" ");
}
if (Key == '1') //If Button 1 is pressed
{ Serial.println ("Button 1");
if (Number == 0)
Number = 1;
else
Number = (Number * 10) + 1; //Pressed twice
}
/*
if (Key == '4') //If Button 4 is pressed
{ Serial.println ("Button 4");
if (Number == 0)
Number = 4;
else
Number = (Number * 10) + 4; //Pressed twice
}
*/
if (Key == '7') //If Button 7 is pressed
{ Serial.println ("Button 7");
if (Number == 0)
Number = 7;
else
Number = (Number * 10) + 7; //Pressed twice
}
if (Key == '0')
{ Serial.println ("Button 0"); //Button 0 is Pressed
if (Number == 0)
Number = 0;
else
Number = (Number * 10) + 0; //Pressed twice
}
if (Key == '2') //Button 2 is Pressed
{ Serial.println ("Button 2");
if (Number == 0)
Number = 2;
else
Number = (Number * 10) + 2; //Pressed twice
}
if (Key == '5')
{ Serial.println ("Button 5");
if (Number == 0)
Number = 5;
else
Number = (Number * 10) + 5; //Pressed twice
}
if (Key == '8')
{ Serial.println ("Button 8");
if (Number == 0)
Number = 8;
else
Number = (Number * 10) + 8; //Pressed twice
}
if (Key == '3')
{ Serial.println ("Button 3");
if (Number == 0)
Number = 3;
else
Number = (Number * 10) + 3; //Pressed twice
}
if (Key == '6')
{ Serial.println ("Button 6");
if (Number == 0)
Number = 6;
else
Number = (Number * 10) + 6; //Pressed twice
}
if (Key == '9')
{ Serial.println ("Button 9");
if (Number == 0)
Number = 9;
else
Number = (Number * 10) + 9; //Pressed twice
}
DisplayResult();
} // end of detect buttons function
void DisplayResult()
{
lcd.clear();
lcd.setCursor(0, 0);
lcd.print ("Input Code: ");
lcd.print (Number);
lcd.setCursor(0, 1);
lcd.print (readString);
lcd.setCursor(0, 2);
lcd.print ("Weight :");
lcd.print (weight);
lcd.setCursor(0, 3);
lcd.print ("*=Cncl,#=Wght,A=Save");
}
The problem is when '#' key is pressed first time with input_code =111, client.read somehow miss or skip the response (name) from server and shows blank. But when i press '#' key second time with input_code = 222, it shows previous response (name) from server.
The EthernetClient can be used to connect to remote server as in WebClient example or it is used by the EthernetServer as a peer for remote client as in ChatServer example.
If you use both, use different names. Now your client 'client' is global and clients returned from server are local but with the same name. And you can make the global client variable local too.
The variable alreadyConnected is used with local client and with server's client.
You don't stop the local client.
You have redundant while/if (client.available()) to test the request (server's client).
Why while (client.available() > 0) around readStringUntil('?')?
EthernetServer should by started with begin only once in setup().
So as of right now when I arm the system and move my hand in front of the PIR sensor it says system triggered how do i get it to take a password from the user to deactivate the system. Also when the system is deactive it should say on the screen "Not Active"
#include <LiquidCrystal.h>
#include <Password.h>
#include <Keypad.h>
//Password
Password password = Password("1234");
LiquidCrystal lcd(0, 1, 10, 11, 12, 13);
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = { // Define the Keymap
{
'1','2','3','A' }
,
{
'4','5','6','B' }
,
{
'7','8','9','C' }
,
{
'*','0','#','D' }
};
byte rowPins[ROWS] = {9,8,7,6};
byte colPins[COLS] = {5,4,3,2};
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS);
int armed = 0;
const int pir1 = A4;
int sensorHit = 0;
int alarmStatus = 0;
int alarmActive = 0;
int zone = 0;
void setup() {
// put your setup code here, to run once:
lcd.begin(16,2);
pinMode(pir1, INPUT);
mainScreen();
keypad.addEventListener(keypadEvent);
}
void loop() {
// put your main code here, to run repeatedly:
keypad.getKey();
if(alarmActive == 1){
if(digitalRead(pir1) == HIGH){
zone = 0;
alarmTriggered();
}
}
}
void keypadEvent(KeypadEvent eKey){
switch (keypad.getState()){
case PRESSED:
lcd.print(eKey);
switch (eKey){
case '#': checkPassword(); break;
default:
password.append(eKey);
}
}
}
void alarmTriggered(){
password.reset();
alarmStatus = 1;
lcd.clear();
lcd.setCursor(0,0);
lcd.print("SYSTEM TRIGGERED");
lcd.print(0,1);
if(zone == 0){
lcd.print(" FRONT DOOR OPEN ");
}
}
void checkPassword(){
if (password.evaluate()){ //if code is correct:
lcd.clear(); //clear LCD
lcd.print("VALID PASSWORD"); //print message
password.reset(); //resets password after correct entry
delay(1500); //wait...
lcd.clear(); //clear
if (alarmStatus==0 && alarmActive == 0){ //if system is off (ie: disarmed)
lcd.print("ARMED!"); //display message
alarmActive=1; //system armed
alarmStatus=1;
delay(2000); //wait
lcd.clear(); //clear
lcd.setCursor(0, 0); //return to top left of LCD
lcd.print("Code to disarm:"); //back to where we began
}
else{
lcd.print("DISARMED!"); //display message
alarmActive=0; //system unarmed
alarmStatus=0;
delay(2000); //wait
lcd.clear(); //clear
lcd.setCursor(0, 0); //return to top left of LCD
lcd.print("Code to arm:"); //back to where we began
}
}
else{ //if password is incorrect:
lcd.clear();
lcd.print("INVALID PASSWORD");
password.reset(); //resets password after INCORRECT entry
delay(2000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Retry Code:");
}
}
void mainScreen(){
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Enter Pin:");
}
You need an input device for entering the password. A simple example can be 10 switches where each switch represent 1 so our password has to be between 0 to 10. You add the switches values together and compare with your set password. The rest should be easy for you.
I am getting this deprecated conversion error when I compile/verify or upload my codes to the Arduino board.
#define SENSOR 3
#define BUZZER 4
#define RELAY 5
#define MOTOR 6
char phonenumber[] = "+639278832517";
//char phonenumber[] = "+639166390471";
uint8_t vibrationData = 0;
uint8_t isArmed = 1;
float latitude, longitude, speed_kph, heading, altitude;
long randNumber;
void setup() {
Serial.begin(115200);
pinMode(RELAY, OUTPUT);
pinMode(MOTOR, OUTPUT);
pinMode(BUZZER, OUTPUT);
digitalWrite(RELAY, HIGH);
digitalWrite(MOTOR, HIGH);
digitalWrite(BUZZER, HIGH);
randomSeed(analogRead(A0));
attachInterrupt(digitalPinToInterrupt(SENSOR), vibrationISR, RISING);
setupFona();
disarm();
Serial.println("Setup done!");
latitude = 14.7042209;
longitude = 121.0369513;
deleteMessages();
}
void vibrationISR() {
if(!isArmed) return;
if(vibrationData == 2) return;
vibrationData = 1;
}
void loop() {
if(isArmed) {
if(vibrationData > 0) {
vibrationData = 2;
digitalWrite(BUZZER, LOW);
Serial.println("Vibration Detected");
if(sendSMS(phonenumber, "Vibration sensor triggered")) {
Serial.println("Send notification success!");
} else {
Serial.println("Send notification failed");
}
delay(1000);
digitalWrite(BUZZER, HIGH);
vibrationData = 0;
}
}
String response = readSMS(phonenumber);
if(response.equals("!#disarm")) {
disarm();
} else if(response.equals("!#arm")) {
arm();
} else if(response.equals("!#on")) {
motorOn();
} else if(response.equals("!#off")) {
motorOff();
} else if(response.equals("!#gps")) {
sendGPS();
}
}
void sendGPS() {
if(getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude)) {
Serial.println("Got GPS fix");
} else {
randNumber = random(300);
if (randNumber % 2 == 0) {
latitude += 0.0001;
longitude += 0.0001;
} else {
latitude -= 0.0001;
longitude -= 0.0001;
}
Serial.println("Cannot get GPS fix");
Serial.print(latitude, 6); Serial.print(","); Serial.println(longitude, 6);
}
String message = "!#location:" + String(latitude, 6) + "," + String(longitude, 6);
Serial.println(message);
int messageLen = message.length();
char messageArray[messageLen + 1];
message.toCharArray(messageArray, messageLen + 1);
if(sendSMS(phonenumber, messageArray)) {
Serial.println("Send GPS success!");
} else {
Serial.println("Send GPS failed");
}
}
void arm() {
Serial.println("Arm");
isArmed = 1;
digitalWrite(RELAY, HIGH);
digitalWrite(MOTOR, HIGH);
if(sendSMS(phonenumber, "System is armed")) {
Serial.println("Send Arm notification success!");
} else {
Serial.println("Send Arm notification failed");
}
}
void disarm() {
Serial.println("Disarm");
isArmed = 0;
digitalWrite(RELAY, LOW);
if(sendSMS(phonenumber, "System is disamred")) {
Serial.println("Send Disarm notification success!");
} else {
Serial.println("Send Disarm notification failed");
}
}
void motorOn() {
Serial.println("Motor On");
digitalWrite(MOTOR, LOW);
if(sendSMS(phonenumber, "Motor is now on")) {
Serial.println("Send Motor On notification success!");
} else {
Serial.println("Send Motor On notification failed");
}
}
void motorOff() {
Serial.println("Motor Off");
digitalWrite(MOTOR, HIGH);
if(sendSMS(phonenumber, "Motor is now off")) {
Serial.println("Send Motor Off notification success!");
} else {
Serial.println("Send Motor Off notification failed");
}
}
Error logs:
E:\smart-motorcycle\smart-motorcycle.ino:145:47: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
if(sendSMS(phonenumber, "Motor is now off")) {
^
This codes has been tested before but after importing the project from another laptop this errors appeared.
Your sendSMS probably looks like this
void sendSMS(char *phonenumber, char *message);
This should be const char * when you are passing string literals.
void sendSMS(const char *phonenumber, const char *message);
note that you don't get a warning on the phone number as the array is not a pointer to const memory.
char phonenumber[] = "+639278832517";
Situation: I have a webpage that has two buttons on it. One sends to the PubNub channel a JSON string of {"lightRight":"1"} and one sends {"lightRight":"0"}, regardless of what I do in the Arduino Sketch I cannot make it into the "on" portion of the void light function.
I know from the serial output of the arduino that I am receiving communication from the web page. If I flip my boolean values to off then I am able to get the "LED HIGH" output but then no longer can I get the "led low".
The code I am trying to adapt can be found here.
https://gist.github.com/ianjennings/ada8fb1a91a486a0c73e
It is very possible I have hacked out to much code from the examples that is why I am including it, but running the stock code I cannot seem to get this to work.
I am not a developer, so I am very sorry if I do not call things as their proper terms. I will learn from correction.
#include <PubNub.h>
#include <SPI.h>
#include <EthernetV2_0.h>
#include <string.h>
#include <Servo.h>
byte mac[] = { MAC was here };
byte gateway[] = { Gate was here };
byte subnet[] = { Sub was here };
IPAddress ip(IP was here);
char pubkey[] = "Key was here";
char subkey[] = "Key was here";
char channel[] = "Channel was here";
int lightRight = 5;
int lightRoom = 6;
int lightGarage = 7;
int i;
EthernetClient *client;
#define W5200_CS 3
#define SDCARD_CS 4
void setup()
{
pinMode(SDCARD_CS,OUTPUT);
digitalWrite(SDCARD_CS,HIGH);
Serial.begin(9600);
Serial.println("Serial set up");
while (!Ethernet.begin(mac)) {
Serial.println("Ethernet setup error");
blink(1000, 999999);
delay(1000);
}
Serial.println("Ethernet set up");
PubNub.begin(pubkey, subkey);
Serial.println("PubNub set up");
pinMode(lightRight, OUTPUT);
pinMode(lightRoom, OUTPUT);
pinMode(lightGarage, OUTPUT);
// blink(100, 5);
reset();
}
//void flash(int ledPin)
//{
// for (int i = 0; i < 3; i++) {
// Serial.println("flash");
// digitalWrite(ledPin, HIGH);
// delay(100);
// digitalWrite(ledPin, LOW);
// delay(100);
// }
//}
void loop()
{
Ethernet.maintain();
PubSubClient *client;
Serial.println("waiting for a message (subscribe)");
client = PubNub.subscribe(channel);
if (!client) {
Serial.println("subscription error");
return;
}
String messages[10];
boolean inside_command = false;
int num_commands = 0;
String message = "";
char c;
while (client->wait_for_data()) {
c = client->read();
if(inside_command && c != '"') {
messages[num_commands] += c;
}
if(c == '"') {
if(inside_command) {
num_commands = num_commands + 1;
inside_command = false;
} else {
inside_command = true;
}
}
message += c;
}
client->stop();
for (i = 0; i < num_commands; i++){
int colonIndex = messages[i].indexOf(':');
String subject = messages[i].substring(0, colonIndex);
String valueString = messages[i].substring(colonIndex + 1, messages[i].length());
boolean value = false;
if(valueString == "1") {
value = true;
}
if(subject == "lightRight") {
light(lightRight, value);
}
if(subject == "lightRoom") {
light(lightRoom, value);
}
if(subject == "lightGarage") {
light(lightGarage, value);
}
if(subject == "blink") {
blink(100, valueString.toInt());
}
Serial.println(subject);
Serial.println(value);
}
Serial.print(message);
Serial.println();
delay(2000);
}
void light(int ledPin, boolean on) {
if(on) {
digitalWrite(ledPin, HIGH);
Serial.println("LED HIGH");
} else {
digitalWrite(ledPin, LOW);
Serial.println("led low");
}
}
void reset() {
Serial.println("Void reset");
light(lightRight, false);
light(lightRoom, false);
light(lightGarage, false);
}
void on() {
Serial.println("Void on");
light(lightRight, true);
light(lightRoom, true);
light(lightGarage, true);
}
void off() {
Serial.println("Void off");
light(lightRight, false);
light(lightRoom, false);
light(lightGarage, false);
}
void blink(int delayn, int count) {
for (int j=0; j <= count; j++){
on();
delay(delayn);
off();
delay(delayn);
}
}
That example expects the PubNub publish to be "lightRight:1" and not {"lightRight": "1"}.