I have been trying to send a simple message using an arduino microcontroller and a gsm shield but it keeps getting an error 0.
Here is the code:
int8_t answer;
int onModulePin= 2;
char aux_string[20];
char phone_number[]="*********";
void setup(){
pinMode(onModulePin, OUTPUT);
Serial.begin(115200);
Serial.println("Starting...");
power_on();
delay(3000);
// sets the PIN code
sendATcommand("AT+CPIN=****", "OK", 2000);
delay(3000);
Serial.println("Connecting to the network...");
while( (sendATcommand("AT+CREG?", "+CREG: 0,1", 500) || sendATcommand("AT+CREG?", "+CREG: 0,5", 500)) == 0 );
Serial.print("Setting SMS mode...");
sendATcommand("AT+CMGF=1", "OK", 1000); // sets the SMS mode to text
Serial.println("Sending SMS");
sprintf(aux_string,"AT+CMGS=\"%s\"", phone_number);
answer = sendATcommand(aux_string, ">", 2000); // send the SMS number
if (answer == 1)
{
Serial.println("Test-Arduino-Hello World");
Serial.write(0x1A);
answer = sendATcommand("", "OK", 20000);
if (answer == 1)
{
Serial.print("Sent ");
}
else
{
Serial.print("error ");
}
}
else
{
Serial.print("error ");
Serial.println(answer, DEC);
}
}
void loop(){
}
void power_on(){
uint8_t answer=0;
// checks if the module is started
answer = sendATcommand("AT", "OK", 2000);
if (answer == 0)
{
// power on pulse
digitalWrite(onModulePin,HIGH);
delay(3000);
digitalWrite(onModulePin,LOW);
// waits for an answer from the module
while(answer == 0){ // Send AT every two seconds and wait for the answer
answer = sendATcommand("AT", "OK", 2000);
}
}
}
int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout){
uint8_t x=0, answer=0;
char response[100];
unsigned long previous;
memset(response, '\0', 100); // Initialice the string
delay(100);
while( Serial.available() > 0) Serial.read(); // Clean the input buffer
Serial.println(ATcommand); // Send the AT command
x = 0;
previous = millis();
// this loop waits for the answer
do{
if(Serial.available() != 0){ // if there are data in the UART input buffer, reads it and checks for the asnwer
response[x] = Serial.read();
x++;
if (strstr(response, expected_answer) != NULL) // check if the desired answer is in the response of the module
{
answer = 1;
}
}
}while((answer == 0) && ((millis() - previous) < timeout)); // Waits for the asnwer with time out
return answer;
}
char phone_number[]="*********";
In the above code, replace ********* with 9xxxxyyyyy (Sim Number/ Mobile Number)
char phone_number[]="*********";
Then start the Serial Monitor with the mentioned baud rate (115200 as in the above code)
Related
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/
I'm after some desperately needed help please.
My setup consists of two arduinos (EtherTens) and a Raspberry Pi (running Mosquitto MQTT broker and Home Assistant). On one Arduino I have a security sensor shield with two PIRs attached and publishing states to the broker (this works 100% how it should).
On my other arduino, I have a couple of relay 8 driver shields (they use I2C) connected to two 8 channel relay boards (total of 16 relays connected).
I have toggle switches connected to switch a few lights in the house for hardware activation plus I have it setup to be activated through Home Assistant with MQTT topics.
The issues I've come across is random relay activation from turning other lights on in the house. I think there's some line interference somewhere and am hoping that a software debounce might solve the issue but I am lost in the code (I already have 10k pulldown resistors on my toggle switch setup).
The other issue is the the Arduino running the relay shields is really (and I mean really) slow to subscribe to the broker...I'm talking anywhere up to 10 seconds at times.
Would anyone be able to suggest the best way to fix my code please?
// This subscribes to MQTT IOT get the PIR sensor states //
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <Wire.h>
#define SHIELD_1_I2C_ADDRESS 0x20 // 0x20 is the address with all jumpers removed
#define SHIELD_2_I2C_ADDRESS 0x21 // 0x21 is the address with a jumper on position A0
#define MAC_I2C_ADDRESS 0x50 // Microchip 24AA125E48 I2C ROM address
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 2, 110);
IPAddress server(192, 168, 2, 149);
byte shield1BankA = 0; // Current status of all outputs on first shield, one bit per output
byte shield2BankA = 0; // Current status of all outputs on second shield, one bit per output
const int buttonPin2 = 2;
const int buttonPin3 = 3;
const int buttonPin4 = 4;
const int buttonPin5 = 5;
const int buttonPin6 = 6;
int buttonState2;
int buttonState3;
int buttonState4;
int buttonState5;
int buttonState6;
int lastButtonState2 = LOW;
int lastButtonState3 = LOW;
int lastButtonState4 = LOW;
int lastButtonState5 = LOW;
int lastButtonState6 = LOW;
unsigned long lastDebounceTime2 = 0;
unsigned long lastDebounceTime3 = 0;
unsigned long lastDebounceTime4 = 0;
unsigned long lastDebounceTime5 = 0;
unsigned long lastDebounceTime6 = 0;
unsigned long debounceDelay2 = 50;
unsigned long debounceDelay3 = 50;
unsigned long debounceDelay4 = 50;
unsigned long debounceDelay5 = 50;
unsigned long debounceDelay6 = 50;
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the Hallway Light
if (strcmp(topic, "left/hallwaylight") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(1);
client.publish("left/hallwaylight/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(1);
delay(500);
client.publish("left/hallwaylight/state", "0");
}
}
// Switch on the Workshop Light - Sensor 2
if (strcmp(topic, "left/workshoplight") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(2);
client.publish("left/workshoplight/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(2);
delay(500);
client.publish("left/workshoplight/state", "0");
}
}
/*
// Switch on the #############
if (strcmp(topic, "left/sensor2") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(2);
client.publish("left/workshoplight/state", "1");
Serial.println("Workshop Light On");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(2);
delay(500);
client.publish("left/workshoplight/*&^*&^&*", "0");
}
}
// Switch on the ####################
if (strcmp(topic, "left/sensor2") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(2);
client.publish("left/workshoplight/state", "1");
Serial.println("Workshop Light On");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(2);
delay(500);
client.publish("left/workshoplight/khebfjseghf", "0");
}
} */
// Switch on the Fountain
if (strcmp(topic, "left/fountain") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(8);
client.publish("left/fountain/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(8);
delay(500);
client.publish("left/fountain/state", "0");
}
}
// Switch on the Entrance Lights
if (strcmp(topic, "left/entrancelights") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(7);
client.publish("left/entrancelights/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(7);
delay(500);
client.publish("left/entrancelights/state", "0");
}
}
// Switch on the Foyer Lights
if (strcmp(topic, "left/foyerlights") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(6);
client.publish("left/foyerlights/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(6);
delay(500);
client.publish("left/foyerlights/state", "0");
}
}
// Switch on the Driveway Lights - Sensor 1
if (strcmp(topic, "left/drivewaylights") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(9);
client.publish("left/drivewaylights/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(9);
delay(500);
client.publish("left/drivewaylights/state", "0");
}
}
// Switch on the Spa Light
if (strcmp(topic, "left/spalight") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(10);
client.publish("left/spalight/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(10);
delay(500);
client.publish("left/spalight/state", "0");
}
}
// Switch on the Pool Light
if (strcmp(topic, "left/poollight") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(11);
client.publish("left/poollight/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(11);
delay(500);
client.publish("left/poollight/state", "0");
}
}
// Switch on the Tree Light
if (strcmp(topic, "left/treelight") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(12);
client.publish("left/treelight/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(12);
delay(500);
client.publish("left/treelight/state", "0");
}
}
// Switch on the Fountains
if (strcmp(topic, "left/fountains") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(13);
client.publish("left/fountains/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(13);
delay(500);
client.publish("left/fountains/state", "0");
}
}
// Switch on the Spa
if (strcmp(topic, "left/spa") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(16);
client.publish("left/spa/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(16);
delay(500);
client.publish("left/spa/state", "0");
}
}
}
void setup()
{
Wire.begin(); // Wake up I2C bus
Serial.begin(38400);
Ethernet.begin(mac, ip);
// Note - the default maximum packet size is 128 bytes. If the
// combined length of clientId, username and password exceed this,
// you will need to increase the value of MQTT_MAX_PACKET_SIZE in
// PubSubClient.h
/* Set up the Relay8 shields */
initialiseShield(SHIELD_1_I2C_ADDRESS);
sendRawValueToLatch1(0); // If we don't do this, channel 6 turns on! I don't know why
initialiseShield(SHIELD_2_I2C_ADDRESS);
sendRawValueToLatch2(0); // If we don't do this, channel 6 turns on! I don't know why
pinMode(buttonPin2, INPUT);
pinMode(buttonPin3, INPUT);
pinMode(buttonPin4, INPUT);
pinMode(buttonPin5, INPUT);
pinMode(buttonPin6, INPUT);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
int reading2 = digitalRead(buttonPin2);
int reading3 = digitalRead(buttonPin3);
int reading4 = digitalRead(buttonPin4);
int reading5 = digitalRead(buttonPin5);
int reading6 = digitalRead(buttonPin6);
if (reading2 != lastButtonState2) {
lastDebounceTime2 = millis();
}
if ((millis() - lastDebounceTime2) > debounceDelay2) {
if (reading2 != buttonState2) {
buttonState2 = reading2;
if ((buttonPin2 == HIGH) && What to put here????) {
toggleLatchChannel(1);
client.publish("left/hallwaylight/state", "1");
}
/*if (digitalRead(2) == HIGH) //Digital pin for Hall Light
{
toggleLatchChannel(1);
delay(1000);
}*/
}
}
lastButtonState2 = reading2;
if (digitalRead(3) == HIGH) //Digital pin for Fountain
{
toggleLatchChannel(6);
delay(1000);
}
if (digitalRead(4) == HIGH) //Digital pin for Entrance Lights
{
toggleLatchChannel(7);
delay(1000);
}
if (digitalRead(5) == HIGH) //Digital pin for Foyer Lights
{
toggleLatchChannel(8);
delay(1000);
}
if (digitalRead(6) == HIGH) //Digital pin for Driveway Lights - to be removed
{
toggleLatchChannel(9);
delay(1000);
}
client.loop();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("leftArduinoClient")) {
Serial.println("connected");
client.subscribe("left/#");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void initialiseShield(int shieldAddress)
{
// Set addressing style
Wire.beginTransmission(shieldAddress);
Wire.write(0x12);
Wire.write(0x20); // use table 1.4 addressing
Wire.endTransmission();
// Set I/O bank A to outputs
Wire.beginTransmission(shieldAddress);
Wire.write(0x00); // IODIRA register
Wire.write(0x00); // Set all of bank A to outputs
Wire.endTransmission();
}
void toggleLatchChannel(byte channelId)
{
if ( channelId >= 1 && channelId <= 8 )
{
byte shieldOutput = channelId;
byte channelMask = 1 << (shieldOutput - 1);
shield1BankA = shield1BankA ^ channelMask;
sendRawValueToLatch1(shield1BankA);
}
else if ( channelId >= 9 && channelId <= 16 )
{
byte shieldOutput = channelId - 8;
byte channelMask = 1 << (shieldOutput - 1);
shield2BankA = shield2BankA ^ channelMask;
sendRawValueToLatch2(shield2BankA);
}
}
void setLatchChannelOn (byte channelId)
{
if ( channelId >= 1 && channelId <= 8 )
{
byte shieldOutput = channelId;
byte channelMask = 1 << (shieldOutput - 1);
shield1BankA = shield1BankA | channelMask;
sendRawValueToLatch1(shield1BankA);
}
else if ( channelId >= 9 && channelId <= 16 )
{
byte shieldOutput = channelId - 8;
byte channelMask = 1 << (shieldOutput - 1);
shield2BankA = shield2BankA | channelMask;
sendRawValueToLatch2(shield2BankA);
}
}
void setLatchChannelOff (byte channelId)
{
if ( channelId >= 1 && channelId <= 8 )
{
byte shieldOutput = channelId;
byte channelMask = 255 - ( 1 << (shieldOutput - 1));
shield1BankA = shield1BankA & channelMask;
sendRawValueToLatch1(shield1BankA);
}
else if ( channelId >= 9 && channelId <= 16 )
{
byte shieldOutput = channelId - 8;
byte channelMask = 255 - ( 1 << (shieldOutput - 1));
shield2BankA = shield2BankA & channelMask;
sendRawValueToLatch2(shield2BankA);
}
}
void sendRawValueToLatch1(byte rawValue)
{
Wire.beginTransmission(SHIELD_1_I2C_ADDRESS);
Wire.write(0x12); // Select GPIOA
Wire.write(rawValue); // Send value to bank A
shield1BankA = rawValue;
Wire.endTransmission();
}
void sendRawValueToLatch2(byte rawValue)
{
Wire.beginTransmission(SHIELD_2_I2C_ADDRESS);
Wire.write(0x12); // Select GPIOA
Wire.write(rawValue); // Send value to bank A
shield2BankA = rawValue;
Wire.endTransmission();
}
/** Required to read the MAC address ROM */
byte readRegister(byte r)
{
unsigned char v;
Wire.beginTransmission(MAC_I2C_ADDRESS);
Wire.write(r); // Register to read
Wire.endTransmission();
Wire.requestFrom(MAC_I2C_ADDRESS, 1); // Read a byte
while (!Wire.available())
{
// Wait
}
v = Wire.read();
return v;
}
Subscribing to the broker may take long because of the delay in this function:
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("leftArduinoClient")) {
Serial.println("connected");
client.subscribe("left/#");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
If you fail to connect on the first attempt, the program will wait for 5 seconds. Have you checked with serial monitor if this is the case? You should see two "failed..." messages.
As for relays: debouncing is only for hardware switches - when you press a button there is a short period when electrcal contacts in it bounce back and forth connecting and disconnecting several times. When you connect a switch to a microcontroller, it will read several transitions of digital pin connected to a button. Debouncing is a way to ignore these short pulses.
That being said, there is no need to debounce a signal that comes from another microcontroller, or a PC - there are no mechanical parts that can oscillate generating "fake" pulses. Try to write a short test program that will just activate all relays in a sequence, one at a time, without reading any external inputs. That way you will know, if the problem comes from a bug in your code, or is it a hardware problem.
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...
I have a serial application that runs from a nano into a current loop driver.
Now if I connect the Tx straight to the Rx the led is set to HIGH but if I link the Tx/Rx to the current loop board the LED isnt set at all. I have even added a serial to usb monitor to confirm that the current loop board is returning the same hex as is being passed. Any suggestions?
int timeout = 0;
void setup() {
// put your setup code here, to run once:
pinMode(13, OUTPUT);
Serial.begin(4800,SERIAL_8E1);
//Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
//delay(10000);
byte inByte1 = 0xF1;
byte inByte2 = 0x10;
byte inByte3 = 0xB0;
//if(timeout == 0)
//{
Serial.write(inByte1);
Serial.write(inByte2);
Serial.write(inByte3);
//}
//timeout = timeout+1;
//if(timeout == 50)
//{
// timeout=0;
//}
//delay(80);
byte inByte4 = 0xE1;
//Serial.println(Serial.available());
while (!Serial.available()) {
//timeout =0;
//byte inChar = Serial.read();
//Serial.println(inChar);
//digitalWrite(13, HIGH);
//if(inChar == inByte4)
//{
// digitalWrite(13, HIGH);
//}
Serial.write(inByte1);
Serial.write(inByte2);
Serial.write(inByte3);
delay(80);
}
while (Serial.available()) {
//timeout =0;
//byte inChar = Serial.read();
//Serial.println(inChar);
digitalWrite(13, HIGH);
//if(inChar == inByte4)
//{
// digitalWrite(13, HIGH);
//}
}
}
String ReadResult(Stream &serial)
{
int serialState = 0;
String content = "";
char character;
long interval = 10000;
//unsigned int timeout = 0;
unsigned long currentMillis = millis();
long previousMillis = millis();
while ( !serial.available() && serialState != 1) {
currentMillis = millis();
if(currentMillis - previousMillis > interval){
serialState = 1;
}
}
//timeout = 0;
//while (serial.available()) {
// character = serial.read();
// content += character;
//}
return content;
};
The driver that I was feeding to was not returning thecorrect voltage
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);
}
}