Send Mirf values with ethercard - arduino

I have project where I'm getting data over nRF24L01 and using Mirf to that. Now I'm working for Hub which need to send data to my webservice. For ethernet my choice was ENC28j60 with ethercard library.
Question : How I can wait data from Mirf and just send data forward with Ethercard browseUrl? I can send data without Mirf but there's some loop which I'm not understand.
My code :
#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>
#include <EtherCard.h>
// Set network settings
static byte mymac[] = { 0x74, 0x69, 0x69, 0x2D, 0x30, 0x31 };
byte Ethernet::buffer[700];
static uint32_t timer;
// My webservice
const char website[] PROGMEM = "my.webservice.com";
// Mirf variables
int tmpVal1;
// Local components
const int Yellow = 6;
const int Blue = 5;
void setup() {
Serial.begin(57600);
// Setup leds
pinMode(Yellow, OUTPUT);
digitalWrite(Yellow, LOW);
pinMode(Blue, OUTPUT);
digitalWrite(Blue, LOW);
setupMirf();
setupEthernet();
}
void loop() {
// Waiting to get date from Mirf
while (!Mirf.dataReady()) {
//ether.packetLoop(ether.packetReceive());
}
Mirf.getData((byte *)&tmpVal1);
Serial.print(tmpVal1);
Serial.println(F(" C"));
// Receive responses
ether.packetLoop(ether.packetReceive());
if (millis() > timer) {
timer = millis() + 5000;
//Serial.println();
Serial.println("Sending data to webservice : ");
ether.browseUrl(PSTR("/sendingdata.asmx/sendingdata?"), "Device=100&DeviceValue=80", website, my_callback);
}
//ShowLedNotification();
}
// called when the client request is complete
static void my_callback (byte status, word off, word len) {
Serial.println(">>>");
Ethernet::buffer[off+300] = 0;
Serial.print((const char*) Ethernet::buffer + off);
Serial.println("...");
digitalWrite(Blue,HIGH);
delay(200);
digitalWrite(Blue,LOW);
}
void ShowLedNotification() {
if (tmpVal1 > 0 ) {
digitalWrite(Yellow, HIGH);
delay(1000);
digitalWrite(Yellow, LOW);
}
else
{
digitalWrite(Blue, HIGH);
delay(1000);
digitalWrite(Blue, LOW);
}
}
long readVcc() {
long result;
// Read 1.1V reference against AVcc
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate AVcc in mV
return result;
}
//Setting up network and getting DHCP IP
void setupEthernet() {
Serial.println(F("Setting up network and DHCP"));
Serial.print(F("MAC: "));
for (byte i = 0; i < 6; ++i) {
Serial.print(mymac[i], HEX);
if (i < 5)
Serial.print(':');
}
Serial.println();
if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
Serial.println(F("Failed to access Ethernet controller"));
Serial.println(F("Setting up DHCP"));
if (!ether.dhcpSetup())
Serial.println(F("DHCP failed"));
ether.printIp("My IP: ", ether.myip);
ether.printIp("Netmask: ", ether.netmask);
ether.printIp("GW IP: ", ether.gwip);
ether.printIp("DNS IP: ", ether.dnsip);
// Check network connection
if (!ether.dnsLookup(website))
Serial.println("DNS failed");
ether.printIp("SRV: ", ether.hisip);
}
void setupMirf() {
//Initialize nRF24
Serial.println(F("Initializing Mirf"));
Mirf.spi = &MirfHardwareSpi;
Mirf.init();
Mirf.setRADDR((byte *)"serv1");
Mirf.payload = sizeof(tmpVal1);
// we use channel 90 as it is outside of WLAN bands
// or channels used by wireless surveillance cameras
Mirf.channel = 90;
Mirf.config();
}

Did get that work. Now using if clause not while Mirf.dataReady()
void loop() {
if (Mirf.dataReady()) {
Mirf.getData((byte *)&tmpVal1);
Serial.print(tmpVal1);
Serial.println(F(" C"));
ShowLedNotification();
// Send data to webservice
if (millis() > timer) {
timer = millis() + 5000;
Serial.println("Sending data to webservice");
String myVarsStr = "Device=";
myVarsStr += myDeviceID;
myVarsStr += "&DeviceValue=";
myVarsStr += tmpVal1;
char myVarsCh[40];
myVarsStr.toCharArray(myVarsCh, 40);
ether.browseUrl(PSTR("/receivedata.asmx/ReceiveData?"), myVarsCh, website, my_callback);
}
}
else
{
word pos = ether.packetReceive();
word len = ether.packetLoop(pos);
delay(200);
}
}

Related

ESP12F, cant get a relay to work with data from dht11

i've been trying to build a system that detects in one room of the house the temperature using an esp8266 and a dht11 sensor, this esp sends the data to a webserver while the ESP12F grabs this data and should turn the relay on when a certain value is reached, however i can't get the relay to work, as soon as i upload the code, the led on the module turns but not at its full power, i tried with another code to see if it was just a faulty relay, but it works perfectly with the same connections. The code from the client side of the system is below:
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
#include "WiFiClient.h"
#include "ESP8266WiFiMulti.h"
ESP8266WiFiMulti WiFiMulti;
const char* ssid = "*******";
const char* password = "********";
//Your IP address or domain name with URL path
const char* serverNameTemp = "http://192.168.1.188/temperature";
const char* serverNameHumi = "http://192.168.1.188/humidity";
const char* serverNamePres = "http://192.168.1.188/pressure";
#include "Wire.h"
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
String temperature;
String humidity;
String pressure;
const int relay = 5;
float temp_int = temperature.toFloat();
unsigned long previousMillis = 0;
const long interval = 2000;
void setup() {
Serial.begin(115200);
Serial.println();
pinMode(relay,OUTPUT);
digitalWrite(relay,LOW);
// Address 0x3C for 128x64, you might need to change this value (use an I2C scanner)
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.clearDisplay();
display.setTextColor(WHITE);
int int_temp = temperature.toFloat();
WiFi.mode(WIFI_STA);
WiFiMulti.addAP(ssid, password);
while((WiFiMulti.run() == WL_CONNECTED)) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected to WiFi");
}
void loop() {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval) {
// Check WiFi connection status
if ((WiFiMulti.run() == WL_CONNECTED)) {
int int_temp = temperature.toFloat();
temperature = httpGETRequest(serverNameTemp);
humidity = httpGETRequest(serverNameHumi);
pressure = httpGETRequest(serverNamePres);
if(int_temp < 26){
digitalWrite(relay,LOW);
}
else if (int_temp > 26){
digitalWrite(relay,HIGH);
}
Serial.println("Temperature: " + temperature + " *C - Humidity: " + humidity + " % - Pressure: " + pressure + " hPa");
Serial.println(int_temp);
Serial.println(temperature.toFloat());
display.clearDisplay();
// display temperature
display.setTextSize(2);
display.setCursor(0,0);
display.print("T: ");
display.print(temperature);
display.print(" ");
display.setTextSize(1);
display.cp437(true);
display.write(248);
display.setTextSize(2);
display.print("C");
// display humidity
display.setTextSize(2);
display.setCursor(0, 25);
display.print("H: ");
display.print(humidity);
display.print(" %");
// display pressure
display.setTextSize(2);
display.setCursor(0, 50);
display.print("P:");
display.print(pressure);
display.setTextSize(1);
display.setCursor(110, 56);
display.print("hPa");
display.display();
// save the last HTTP GET Request
previousMillis = currentMillis;
}
else {
Serial.println("WiFi Disconnected");
}
}
}
String httpGETRequest(const char* serverName) {
WiFiClient client;
HTTPClient http;
// Your IP address with path or Domain name with URL path
http.begin(client, serverName);
// Send HTTP POST request
int httpResponseCode = http.GET();
String payload = "--";
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
return payload;
}

Error using thingspeak talk back to control arduino led

The error I'm facing is about using talkback function of thingspeak to control my Arduino LED. it cannot execute the talkback command to off the led. The error is in my void get talkback. Please help me
#include "ThingSpeak.h"
#include <Ethernet.h>
#define redLED 8
byte mac[] = {0x90, 0xA2, 0xDA, 0x10, 0x40, 0x4F};
const String channelsAPIKey = "";
const String talkBackAPIKey = "";
const String talkBackID = "";
const String talkCommandID = "";
const unsigned int getTalkBackInterval = 10 * 1000;
const unsigned int updateChannelsInterval = 15 * 1000;
String talkBackCommand;
long lastConnectionTimeChannels = 0;
boolean lastConnectedChannels = false;
int failedCounterChannels = 0;
long lastConnectionTimeTalkBack = 0;
boolean lastConnectedTalkBack = false;
int failedCounterTalkBack = 0;
char charIn;
// Arduino Ethernet Client is initialized
EthernetClient client;
void setup()
{
Ethernet.init(10); // Most Arduino Ethernet hardware
Serial.begin(9600); //Initialize serial
// start the Ethernet connection:
pinMode(redLED, OUTPUT);
digitalWrite(redLED, HIGH);
}
void loop()
{
getTalkBack();
}
void getTalkBack()
{
String tsData;
tsData = talkBackID + "/commands/execute?api_key=" + talkBackAPIKey;
if ((!client.connected() && (millis() - lastConnectionTimeTalkBack > getTalkBackInterval)))
{
if (client.connect("api.thingspeak.com", 80))
{
client.println("GET /talkbacks/" + tsData + " HTTP/1.0");
client.println();
lastConnectionTimeTalkBack = millis();
if (client.connected())
{
Serial.println("---------------------------------------");
Serial.println("GET TalkBack command");
Serial.println();
Serial.println("Connecting to ThingSpeak");
Serial.println();
Serial.println();
Serial.println("Server response");
Serial.println();
failedCounterTalkBack = 0;
while (client.connected() && !client.available()) delay(2000); //waits for data
while (client.connected() || client.available())
{
charIn = client.read();
talkBackCommand += charIn;
Serial.print(charIn);
if (talkBackCommand == "LED_ON")
{
digitalWrite(redLED, HIGH);
}
if (talkBackCommand == "LED_OFF")
{
digitalWrite(redLED, LOW);
}
}
if (talkBackCommand = talkBackCommand.substring(talkBackCommand.indexOf("_CMD_") + 5));
{
Serial.println();
Serial.println();
Serial.println("Disconnected");
Serial.println();
Serial.println("--------");
Serial.println();
Serial.println("talkback command was");
Serial.println();
Serial.println("--------");
Serial.println();
Serial.println(talkBackCommand);
Serial.println("--------");
Serial.println();
}
}
else
{
failedCounterTalkBack++;
Serial.println("Connection to ThingSpeak failed (" + String(failedCounterTalkBack, DEC) + ")");
Serial.println();
lastConnectionTimeChannels = millis();
}
}
}
if (failedCounterTalkBack > 3 )
{
startEthernet();
}
client.stop();
Serial.flush();
}
The below is a image from my serial monitor. It shows that I can capture the command but couldn't execute it.
Looks like you are reading and appending all the received bytes to talkBackCommand. So, talkBackCommand is "HTTP/1.1 200 OK Date...." and if (talkBackCommand == "LED_ON") would never be true.
I think you wanted to see if the received data contain your commands LED_ON or LED_OFF. You can do something like this:
if (talkBackCommand.indexOf("LED_ON") != -1)
indexOf() locates a String in a String and returns index or -1 if not found.
See more info about indexOf() here: https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/indexof/

integrating the AdafruitFona GSM shield with tiny gps library

i need help in integrating the two libraries so that i can send the GPS data via GSM . Information regarding the use of two special Serial is needed and also a help with the code is needed .
The below segmnet containts the code for the GPS shield this has to be used to generate the location and this data has to be sent via gsm to a mobile number.
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
It requires the use of SoftwareSerial, and assumes that you have a
4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
static const int RXPin = 4, TXPin = 3;//was 4 and 3;
static const uint32_t GPSBaud = 9600;
// The TinyGPS++ object
TinyGPSPlus gps;
// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);
void setup()
{
Serial.begin(115200);
ss.begin(GPSBaud);
Serial.println(F("GPS GSM tracking system"));
Serial.println(F("Sabdadon Presents"));
Serial.print(F("Search and Rescue")); Serial.println(TinyGPSPlus::libraryVersion());
Serial.println(F("Sabarish"));
Serial.println();
}
void loop()
{
// This sketch displays information every time a new sentence is correctly encoded.
while (ss.available() > 0)
if (gps.encode(ss.read()))
displayInfo();
if (millis() > 500000 && gps.charsProcessed() < 10)
{
Serial.println(F("No GPS detected: check wiring."));
while(true);
}
}
void displayInfo()
{
delay(10000);
Serial.print(F("Location: "));
if (gps.location.isValid())
{
Serial.print(gps.location.lat(), 5);
Serial.print(F(","));
Serial.print(gps.location.lng(), 5);
// latitude=gps.location.lat();
//longitude=gps.location.lng();
//if(latitude && longitude)
}
else
{
Serial.print(F("INVALID"));
}
Serial.print(F(" Date/Time: "));
if (gps.date.isValid())
{
Serial.print(gps.date.month());
Serial.print(F("/"));
Serial.print(gps.date.day());
Serial.print(F("/"));
Serial.print(gps.date.year());
}
else
{
Serial.print(F("INVALID"));
}
Serial.print(F(" "));
if (gps.time.isValid())
{
if (gps.time.hour() < 10) Serial.print(F("0"));
Serial.print(gps.time.hour());
Serial.print(F(":"));
if (gps.time.minute() < 10) Serial.print(F("0"));
Serial.print(gps.time.minute());
Serial.print(F(":"));
if (gps.time.second() < 10) Serial.print(F("0"));
Serial.print(gps.time.second());
Serial.print(F("."));
if (gps.time.centisecond() < 10) Serial.print(F("0"));
Serial.print(gps.time.centisecond());
}
else
{
ss.read();
Serial.print(F("INVALID"));
}
Serial.println();
}
FOR GSM
#include "Adafruit_FONA.h"
#define FONA_RX 2//2
#define FONA_TX 3//3
#define FONA_RST 4//4
char replybuffer[255];
#include <SoftwareSerial.h>
#include <AltSoftSerial.h>
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);
uint8_t type;
void setup()
{
while (!Serial);
Serial.begin(115200);
Serial.println(F("FONA basic test"));
Serial.println(F("Initializing....(May take 3 seconds)"));
fonaSerial->begin(4800);
if (! fona.begin(*fonaSerial)) {
Serial.println(F("Couldn't find FONA"));
while (1);
}
type = fona.type();
Serial.println(F("FONA is OK"));
Serial.print(F("Found "));
switch (type) {
case FONA800L:
Serial.println(F("FONA 800L")); break;
case FONA800H:
Serial.println(F("FONA 800H")); break;
case FONA808_V1:
Serial.println(F("FONA 808 (v1)")); break;
case FONA808_V2:
Serial.println(F("FONA 808 (v2)")); break;
case FONA3G_A:
Serial.println(F("FONA 3G (American)")); break;
case FONA3G_E:
Serial.println(F("FONA 3G (European)")); break;
default:
Serial.println(F("???")); break;
}
// Print module IMEI number.
char imei[15] = {0}; // MUST use a 16 character buffer for IMEI!
uint8_t imeiLen = fona.getIMEI(imei);
if (imeiLen > 0) {
Serial.print("Module IMEI: "); Serial.println(imei);
}
}
void loop()
{ Serial.print(F("FONA> "));
while (! Serial.available() ) {
if (fona.available()) {
Serial.write(fona.read());
}
}
// send an SMS!
char sendto[21], message[141];
flushSerial();
Serial.print(F("Send to #"));
readline(sendto, 20);
Serial.println(sendto);
Serial.print(F("Type out one-line message (140 char): "));
readline(message, 140);
Serial.println(message);
if (!fona.sendSMS(sendto, message)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("Sent!"));
}
}
void flushSerial() {
while (Serial.available())
Serial.read();
}
char readBlocking() {
while (!Serial.available());
return Serial.read();
}
uint16_t readnumber() {
uint16_t x = 0;
char c;
while (! isdigit(c = readBlocking())) {
//Serial.print(c);
}
Serial.print(c);
x = c - '0';
while (isdigit(c = readBlocking())) {
Serial.print(c);
x *= 10;
x += c - '0';
}
return x;
}
uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout) {
uint16_t buffidx = 0;
boolean timeoutvalid = true;
if (timeout == 0) timeoutvalid = false;
while (true) {
if (buffidx > maxbuff) {
//Serial.println(F("SPACE"));
break;
}
while (Serial.available()) {
char c = Serial.read();
//Serial.print(c, HEX); Serial.print("#"); Serial.println(c);
if (c == '\r') continue;
if (c == 0xA) {
if (buffidx == 0) // the first 0x0A is ignored
continue;
timeout = 0; // the second 0x0A is the end of the line
timeoutvalid = true;
break;
}
buff[buffidx] = c;
buffidx++;
}
if (timeoutvalid && timeout == 0) {
//Serial.println(F("TIMEOUT"));
break;
}
delay(1);
}
buff[buffidx] = 0; // null term
return buffidx;
}
Here is a step-by-step to mix your GPS input device and your GSM output device.
Remainder for Arduino principles:
The void setup() function is performed one time after startup.
The void loop() function is performed periodically after the
setup().
Step1 - declaration of GPS device and Serial link
// GPS and Serial link
static const int RXPin = 4, TXPin = 3;//was 4 and 3;
static const uint32_t GPSBaud = 9600;
// The TinyGPS++ object
TinyGPSPlus DeviceGPS;
// The serial connection to the GPS device
SoftwareSerial SerialGPS(RXPin, TXPin);
Step2 - declaration of GSM/FONA device and Serial link
Including the SendTo SMS number !!!
#define FONA_RX 2//2
#define FONA_TX 3//3
#define FONA_RST 4//4
// The serial connection to the GSM device
SoftwareSerial SerialFONA = SoftwareSerial(FONA_TX, FONA_RX);
// The FONA/GSM Cellular Module device
Adafruit_FONA DeviceFONA = Adafruit_FONA(FONA_RST);
// The destination SMS number
static const char *sSendTo = "<NUMBER>";
Step3 - setup() function for (Console, GPS and GSM)
It is possible to add some extra Init.
// only execute once
void setup()
{
// Wait and Init Console
while (!Serial); // Serial over USB
Serial.begin(115200);
// Init GPS link
SerialGPS.begin(GPSBaud);
Serial.print(F("TinyGPSPlus ver: "));
Serial.println(TinyGPSPlus::libraryVersion());
// Init GSM link
SerialFONA.begin(4800);
if (! DeviceFONA.begin(SerialFONA)) {
Serial.println(F("Couldn't find FONA"));
while (1); // Stop working
}
// Add some extra Init
}
Step4 - loop() function to wait GPS location and send SMS
It is possible to use String() to create the SMS based on the
acquired DeviceGPS.location.lng() and DeviceGPS.location.lat().
// executed periodicaly
void loop()
{
// check until GPS message
while (SerialGPS.available() > 0) {
// get for a complete GPS message
DeviceGPS.encode(SerialGPS.read());
}
// flush GSM serial link
while (SerialFONA.available() > 0) {
if (DeviceFONA.available()) {
DeviceFONA.flush();
}
}
// send an SMS!
char sendto[21], message[141];
// Wait for location (lng, lat, alt) is OK
if (DeviceGPS.location.isValid()) {
// ==> create SMS with longitude & latitude
}
}

PIC16F628A to Arduino RF Communication Fails (433MHz)

I have pic16f628a and Arduino UNO...
I use MikroC for PIC...
I use 433 mhz transmitter and receiver.
My purpose is reading datas from Arduino UNO which I send from PIC16F628A; but I couldn't success it...
The circuit of PIC16F628A (Transmitter):
The circuit of Transmitter
I connected first pin of receiver to +5V of Arduino;
second pin of receiver to 12.pin of Arduino,
last pin of receiver to GND pin of Arduino.
Transmitter(PIC16F628A):
char pre[15]={'U','U','U','U','U',255,255,255,255,255,0,0,0,0,0}; //start bytes...
char ileri[3]={'f','r','w'};
char geri[3]={'b','c','k'};
char dur[3]={'d', 'u', 'r'};
char i=0,j=0;
void kurulum()
{
CMCON= 7;
TRISB= 2;
UART1_Init(2400);
delay_ms(100);
}
void main()
{
kurulum();
while(1)
{
for(i=0;i<15;i++)
{
UART1_Write(pre[i]);
}
for(j=0;j<10;j++)
{
for(i=0;i<3;i++)
{
while(!UART1_Tx_Idle());
UART1_Write(ileri[i]);
}
}
//*************************************************************
for(i=0;i<15;i++)
{
UART1_Write(pre[i]);
}
for(j=0;j<10;j++)
{
for(i=0;i<3;i++)
{
while(!UART1_Tx_Idle());
UART1_Write(geri[i]);
}
}
for(i=0;i<15;i++)
{
UART1_Write(pre[i]);
}
for(j=0;j<10;j++)
{
for(i=0;i<3;i++)
{
while(!UART1_Tx_Idle());
UART1_Write(dur[i]);
}
}
}
}
Receiver (Arduino):
// receiver.pde
//
// Simple example of how to use VirtualWire to receive messages
// Implements a simplex (one-way) receiver with an Rx-B1 module
//
// See VirtualWire.h for detailed API docs
// Author: Mike McCauley (mikem#airspayce.com)
// Copyright (C) 2008 Mike McCauley
// $Id: receiver.pde,v 1.3 2009/03/30 00:07:24 mikem Exp $
#include <VirtualWire.h>
const int led_pin = 13;
const int receive_pin = 12;
void setup()
{
delay(1000);
Serial.begin(9600); // Debugging only
Serial.println("setup");
// Initialise the IO and ISR
vw_set_rx_pin(receive_pin);
//vw_set_ptt_inverted(true); // Required for DR3100
vw_setup(2400); // Bits per sec
vw_rx_start(); // Start the receiver PLL running
pinMode(led_pin, OUTPUT);
}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen)) // Non-blocking
{
int i;
digitalWrite(led_pin, HIGH); // Flash a light to show received good message
// Message with a good checksum received, dump it.
Serial.print("Got: ");
for (i = 0; i < buflen; i++)
{
Serial.print(buf[i], HEX);
Serial.print(' ');
}
Serial.println();
digitalWrite(led_pin, LOW);
}
}
I tried this code; but it didn't work...
There is another code;
void setup() {
Serial.begin(2400);
}
void loop() {
if (Serial.available() > 0){
Serial.println(Serial.read());
}
}
Before trying it; I connected data pin of receiver to RX pin of Arduino...
I usually got '0' byte.i
It didn't work as I desired...
SOLVED
The tests I have done so far were already taking the true datas but I was viewing them as numbers...
That's why I couldn't understand that It was working well.
Let's have a look at codes;
Transmitter:
The same as transmitter code at question message
Arduino (Receiver):
char x, msg[6];
int i= 0;
void setup() {
Serial.begin(2400);
}
void loop() {
if (Serial.available() > 0){
msg[i] = Serial.read();
if (msg[0]=='f' || msg[0] == 'b' || msg[0] == 'd'){
i++;
}
if (i==3){
Serial.println(msg);
i = 0;
msg[0]=0;
}
}
}
msg[0]=='f' || msg[0] == 'b' || msg[0] == 'd'
The purpose of comparison above is catching "frw", "bck" or "dur" messages which I sent transmitter...
The data pin of the receiver should be connected RX pin of the Arduino...

Openhab doesn't change the status of switch from manual overide

I have just made an account because of this particular problem I'm having with OpenHAB. I was following a tutorial from this https://openhardwarecoza.wordpress.com/2015/03/29/openhab-mqtt-arduino-and-esp8266-part-3-hardware-arduino-with-ethernet-shield/ site but since the reply there didn't help me. I decided to go to this site.
I have successfully installed OpenHAB and use it. When I turn the switch off and on from both the HTTP page and android device, It works just fine. But when I tried to manual override using a push button on an Arduino. It didn't update the state of the switch in both of them. I'm using windows with OpenHAB version 1.71
The Openhab server notices that there is an update of the state from the push button, but the button in the HTTP page and android device didn't change at all.
I have tested the connection using MQTTlens and it works just fine.
Below is my code
items configuration
Group All
Switch mqttsw1 "Switch 1" (all) {mqtt=">[mymosquitto:/arduino/l1/com:command:off:0],>[mymosquitto:/arduino/l1/com:command:on:1],<[mymosquitto:/arduino/l1/state:state:default]"}
Switch mqttsw2 "Switch 2" (all) {mqtt=">[mymosquitto:/arduino/l2/com:command:off:0],>[mymosquitto:/arduino/l2/com:command:on:1],<[mymosquitto:/arduino/l2/state:state:default]"}
Number temp "Temperature [%.1f °C]" <temperature> {mqtt="<[mymosquitto:/arduino/temp/state:state:default]"}
Number hum "Humidity [%.1f &#37]" <temperature> {mqtt="<[mymosquitto:/arduino/hum/state:state:default]"}
Sitemap configuration
sitemap dolphin label="Main Menu"
{
Frame label="Switch" {
Switch item=mqttsw1 label="Switch 1"
Switch item=mqttsw2 label="Switch 2"
}
Frame label="Weather" {
Text item=temp
Text item=hum
}
The Arduino Code
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <DHT.h>
const int butt1 = 3;// the pin that the pushbutton is attached to
const int butt2 = 2;
const int ledPin1 = 5;
const int ledPin2 = 4;
int ledState1 = HIGH;
int buttonState1;
int lastButtonState1 = LOW;
int ledState2 = HIGH;
int buttonState2;
int lastButtonState2 = LOW;
long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 60000; // READING INTERVAL
int t = 0; // TEMPERATURE VAR
int h = 0; // HUMIDITY VAR
#define DHTPIN 24 // SENSOR PIN
#define DHTTYPE DHT11 // SENSOR TYPE - THE ADAFRUIT LIBRARY OFFERS SUPPORT FOR MORE MODELS
DHT dht(DHTPIN, DHTTYPE);
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xEF };
IPAddress ip(192, 168, 1, 103);
IPAddress server(192, 168, 1, 100);
void callback(char* topic, byte* payload, unsigned int length);
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println();
Serial.println("Callback");
Serial.print("Topic = ");
Serial.println(topic);
Serial.print("Payload = ");
for (int i=0;i<length;i++){
Serial.print((char)payload[i]);
}
Serial.println();
if (strcmp(topic,"/esp1/l1/com")==0) {
if (payload[0] == '0')
{
digitalWrite(ledPin1, LOW);
delay(100);
client.publish("/esp1/l1/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(ledPin1, HIGH);
delay(100);
client.publish("/esp1/l1/state","1");
}
}
if (strcmp(topic,"/esp1/l2/com")==0) {
if (payload[0] == '0')
{
digitalWrite(ledPin2, LOW);
delay(100);
client.publish("/esp1/l2/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(ledPin2, HIGH);
delay(100);
client.publish("/esp1/l2/state","1");
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("arduinoClient")) {
Serial.println("connected");
client.subscribe("/esp1/#");
client.publish("conn","Connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void push1() {
int reading1 = digitalRead(butt1);
buttonState1 = reading1;
if (buttonState1 == HIGH) {
ledState1 = !ledState1;
if (ledState1 < 1)
{
digitalWrite(ledPin1, LOW);
delay(100);
client.publish("/esp1/l1/com","0");
client.publish("/esp1/l1/state","0");
}
else
{
digitalWrite(ledPin1, HIGH);
delay(100);
client.publish("/esp1/l1/com","1");
client.publish("/esp1/l1/state","1");
}
}
}
void push2() {
int reading2 = digitalRead(butt2);
buttonState2 = reading2;
if (buttonState2 == HIGH) {
ledState2 = !ledState2;
if (ledState2 < 1)
{
digitalWrite(ledPin2, LOW);
delay(100);
client.publish("/esp1/l2/com","0");
client.publish("/esp1/l2/state","0");
}
else
{
digitalWrite(ledPin2, HIGH);
delay(100);
client.publish("/esp1/l2/com","1");
client.publish("/esp1/l2/state","1");
}
}
}
void temp() {
h = (int)dht.readHumidity();
t = (int)dht.readTemperature();
char temp[2];
char hum[3];
sprintf(hum, "%d", h);
sprintf(temp, "%d", t);
client.publish("/esp1/temp/state", temp);
client.publish("/esp1/hum/state", hum);
}
void setup() {
// put your setup code here, to run once:
pinMode(butt1, INPUT);
pinMode(butt2, INPUT);
// initialize the LED as an output:
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
Serial.begin(9600);
Ethernet.begin(mac, ip);
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
pinMode(26, OUTPUT); // sets the digital pin as output
pinMode(22, OUTPUT); // sets the digital pin as output
digitalWrite(26, HIGH); // sets +5v for the sensor
digitalWrite(22, LOW); // sets gnd for the sensor
h = (int)dht.readHumidity();
t = (int) dht.readTemperature();
if (client.connect("arduinoClient")) {
client.publish("conn","Connected");
client.subscribe("/esp1/#");
}
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()) {
reconnect();
}
currentMillis = millis();
if (currentMillis - previousMillis > interval) { // READ ONLY ONCE PER INTERVAL
previousMillis = currentMillis;
temp();
}
int reading1 = digitalRead(butt1);
int reading2 = digitalRead(butt2);
if (reading1 != buttonState1) {
push1();
}
if (reading2 != buttonState2){
push2();
}
client.loop();
}
If there are anybody who can help me I would be very grateful. Thank you for your attention !
Best Regards,
Aldi
If I remember correctly you should post back a status of ON or OFF instead of 1 or 0.
Could you change your arduino code to publish back ON and OFF and test that?
e.g.
client.publish("/esp1/l1/state","ON");

Resources