text:
How to use #define in a library I'm trying to write?
I have written simple code to enable toggling of serial.print debug data.
  #define DEBUG
  #ifdef  DEBUG
    #define DEBUG3(x,y,z) Serial.print(x);Serial.print(" ");Serial.print(y);
     Serial.print(" "); Serial.println (z)
    #define DEBUG2(y,z) Serial.print(y);Serial.print(" ");Serial.println
     (z)
    #define DEBUG(z) Serial.println(z)
    #define DEBUGln  Serial.println("");
  #else
    #define DEBUG3(x,y,z)
    #define DEBUG2(x,y)
    #define DEBUG(x)
    #define DEBUGln
  #endif

Then I can just call DEBUG3("words",value,"words"); anywhere in the sketch and it will automatically print out the text, int, strings, etc with a single space between and automatically go to next line etc etc.
Just define the correct number of fields to print and separate using commas.
If I want to turn off debug then I just comment out #define DEBUG at the top.
Now the issue is I don't want to copy in this code every time I want to use it, so it makes sense to make it a library so that I can just call something like:
#include <SERIAL_DEBUG.h>
#define DEBUG     (or //#define DEBUG) //to enable or disable

The reason being that sometimes I might want to print up to 10 things on a single line (not very often but it could happen).
This is my first library attempt and I'm having a hard time finding any information on how I would go about setting up the .h and .cpp files for this type of #define DEBUG(x) Serial.println(x) and the #define DEBUG (from sketch) parts.

I wouldn't use DEBUG if I was you, some compilers define it.  You might want to look at printf which may solve you needs.

Have you tried copying someone elses library and renaming the folders and files as appropriate.  You might have an issue because the source file has no substance, so the compiler won't actually generate an object it can link against.  You could stick a dummy function in there if this becomes an issue.  In this case another solution would be to just define a header file and store it in a central location and do a 'include "..\DebugFile.h"` - dirty but effective.

yea i have been tossing up what exact command to call it. i want something simple and DEBUG() was working sofar but i might change it.. easy enough..
no substance yes good thinking ill keep it in mind.
so you mean just a .h and not do much if anything with .cpp?
because that would be oh so much less to think about

You need to put your code inside bracket to make it a single statement. Otherwise, if (something) DEBUG3(x,y,z); will not give you what you want.

Anything in a header file that is included with #include is literally pasted into the file at the point of the #include.
So anything in your sketch you want to place into a header file you can just place it in a header file and include that file at the same location where the original code was.
So you can have a header file debug.h:
  #ifdef  DEBUG
    #define DEBUG3(x,y,z) Serial.print(x);Serial.print(" ");Serial.print(y);
     Serial.print(" "); Serial.println (z)
    #define DEBUG2(y,z) Serial.print(y);Serial.print(" ");Serial.println
     (z)
    #define DEBUG(z) Serial.println(z)
    #define DEBUGln  Serial.println("");
  #else
    #define DEBUG3(x,y,z)
    #define DEBUG2(x,y)
    #define DEBUG(x)
    #define DEBUGln
  #endif

And include that in your sketch at the right location:
#define DEBUG
#include "debug.h"

Note that the #define DEBUG must come before the #include. Remember: the #include is replaced by the content of the included file, so after preprocessing you end up with exactly what you had before in your sketch:
  #define DEBUG
  #ifdef  DEBUG
    #define DEBUG3(x,y,z) Serial.print(x);Serial.print(" ");Serial.print(y);
     Serial.print(" "); Serial.println (z)
    #define DEBUG2(y,z) Serial.print(y);Serial.print(" ");Serial.println
     (z)
    #define DEBUG(z) Serial.println(z)
    #define DEBUGln  Serial.println("");
  #else
    #define DEBUG3(x,y,z)
    #define DEBUG2(x,y)
    #define DEBUG(x)
    #define DEBUGln
  #endif

The file can be in the same location as the sketch (in which case you should use #include "debug.h" or in a library folder (Arduino/libraries/debug/debug.h) in which case you should include it with #include <debug.h>. In the Arduino IDE it actually makes little or no difference which type of #include you use, but it does serve as a visual reminder that this is either a header included with the sketch ("") or an external library or system header (<>).

thank you sir . this worked and solved the issue.. i was thinking it would be more complicated to do from all the content out there about libraries and not realzing what exactly a the #include and .h file actually do cheers

Not a direct answer to your question, but I would suggest a different
approach based on streaming output, as described in the Arduino
Playground: Adding Streaming (insertion-style) Output. In
a nutshell, you define the << operator for Serial (and any other
object that inherits from Print) in a way that allows you to write
things like:
Serial << "My name is " << name << " and I am " << age << " years old.";

Now you can define a Debug object which would be, depending on whether
you want debugging output or not:

an alias to Serial
a dummy object that just discards its input.

Example:
#define DEBUG_ON

// From https://playground.arduino.cc/Main/StreamingOutput
template<class T> inline Print& operator<<(Print &obj, T arg)
{ obj.print(arg); return obj; }

#ifdef DEBUG_ON
# define Debug Serial
#else
class DummyStream {
public:
    template<class T> DummyStream& operator<<(T arg)
    { (void) arg; return *this; }
} Debug;
#endif

void setup()
{
    const unsigned long BAUDRATE = 9600;
    Serial.begin(BAUDRATE);
    Debug << "Serial port open at " << BAUDRATE << " bps\r\n";
}

That's is an overly complicated solution for a OP that is struggling with using #define. OP approach does the thing in a simple and easily comprehensible way. I love you, Edgar, but C++ looks like the unwanted child of PHP raping JavaScript.

thanks both of you. Alterno i agree haha. i had a look at a few of the other ways to go about toggling serial debug lines @COMPILE TIME. all of which seem really long winded and overly complicated. {{{continue on next}}}

my approach seems to work a lot better than i had expected.  being simple to implement a long chain of serial data and with ZERO change in overhead compared to Serial.print  when DEBUG enabled(extra spaces aside..),  and also ZERO overhead (as if all Serial.print was // commented out..) when disabled. it literally turns it all on or completely eliminates it.             i discovered if i put all the #define DEBUG#(X) into an otherwise enpty sketch and #include <DIR\sketch.ino> that works  its not a proper library but i guess it'l do if i cant make the library work


text:
usart sketch uploaded using makefile gives unusual behaviour
This is a simple usart program in avr c which just transmits a character.
#include <avr/io.h>
#include <util/delay.h>
#define F_CPU 16000000UL
#define BAUD 9600
#define BAUD_PRESCALLER ((F_CPU / (BAUD * 16UL)) - 1)
void send_val(unsigned char);
int main() {

UBRR0H = (uint8_t)(BAUD_PRESCALLER>>8);
UBRR0L = (uint8_t)(BAUD_PRESCALLER);
UCSR0B = (1<<TXEN0);
unsigned char x = 'B';
while(1) {

    send_val(x);
    _delay_ms(1000);
}

return 0;
}

void send_val(unsigned char v) {
while(!(UCSR0A & (1<<UDRE0)));
UDR0 = v;

}

when I upload this code via the Arduino IDE, everything is fine and the code works as expected.The LED labeled "L" on the PCB is still.
but, when I upload the code using the following Makefile, the code uploads successfully but the outcome is unexpected. I see a weird character(see EDIT) and the LED "L" blinks a couple of times in that 1 sec delay.
CC=avr-gcc
OBJCOPY=avr-objcopy

CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
PORT=/dev/ttyACM0

led.hex: led.elf
    ${OBJCOPY} -O ihex -R .eeprom led.elf led.hex

led.elf: led.o
    ${CC} -o led.elf led.o

install: led.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:led.hex

I referred the Schematics and the led is connected to SCK but I don't understand why the makefile is causing it to trigger.
that blinking of LED is what I think is causing the issue. Does the IDE have some other specific flags while uploading the code or am I committing some silly mistake?
EDIT: I wrote a small program to see the values in the device node /dev/ttyACM0. the ASCII value of the weired character(looks like a question mark) is actually 255.
another issue I noticed is that when I touch the solder beneath the pin 13 (only pin 13) the led L goes off!
As led L is connected to pin 13 I thought this is some hardware issue with my board but then I uploaded the blink led example code, touched the solder and everything is fine.
what could be the actual issue? this is getting mysterious.

The LED issue is normal and has already been covered here. Short answer: it's powered by an op-amp with an input that is floating unless you pinMode(LED_BUILTIN, OUTPUT);.

The -mmcu=atmega328p compiler flag is needed not only for the compile
phase, but also for the link phase. Otherwise the linker will not know
which CRT (C run time) to link with your program, and it will link none.
The CRT is responsible for things like initializing the stack pointer,
clearing r1 (as required by the AVR calling convention) and calling
your main().
Edit: the following simplified Makefile should work if you have a
modern version of avrdude that understands ELF files:
CC     = avr-gcc
MCU    = atmega328p
CFLAGS = -Os -DF_CPU=16000000UL -mmcu=${MCU}
PORT   = /dev/ttyACM0

led.elf: led.c
    ${CC} ${CFLAGS} $< -o $@

install: led.elf
    avrdude -c arduino -p ${MCU} -P ${PORT} -b 115200 -U $<

Otherwise you can keep your rules for led.elf → led.hex → install.

can you show the exact line I need to add to the makefile. thanks.

using this makefile, the upload succeeded as usual but the issue is still not resolved. I have avrdude version 6.2

@YsK: delete led.elf before typing make, otherwise make will just re-upload the old faulty led.elf.

i noticed that the led still goes off when i touch the solder of pin 13. only for this program..when i try the sample blink program it works fine. is something wrong with my code?

oh sorry, i didn't notice the comment about floating node. thanks for the help

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Charlieplexing 30 LED sections with a max of 27 LEDs at the same time?
So basically, I'm trying to make a digital wall clock and using digital numbers, I have 7 sections of LED's per number, 4 numbers and one section for the colon in between them. A total of 30 sections. The colon will toggle every second so the the most possible simultaneously glowing sections is 27. That's because of the time 08:08.
Is there any way to make this work with an arduino? Possibly by Charlieplexing the arduino into 30 sections, using 6 pins. Or is there something out there that has 30 pins!?
The problem of course with charlieplexing, is that you need it to become rapid pulses. I'm sure I'm going to need some help with this, and also with laying out a schematic.
To be clear, this is how the led sections are going to be laid out. I also know I'm going to need an npn transistor for every single one of them. the biggest section uses 20 LEDs.

Thanks!

I would consider 74HC595N's. These are shift registers, which can control 8 'outputs' using less pins on your Arduino.
These are very cheap (buy them per 10) and you can daisy chain 4 of them, having 32 outputs, using only 5 pins of your Arduino. This would fit perfectly with your 30 sections.
Each of the 30 outputs can be used to control a transistors to control one LED sections.
See for an example for using shift registers with the Arduino: ShiftOut
Also you might need this: ULN2803 darlington drivers for each output (4 total).

Jij bent Nederlands of niet?

@Hendriks3D True (but it's better to write everything in English here).

Indeed.........

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
changing device signature in avrdude
I am trying to burn bootloaders to Atmega2560V and when I hit burn bootloaders it shows me this error

avrdude: Device signature = 0x1e9803
  avrdude: Expected signature for ATmega2560 is 1E 98 01

I know this device should have 0x1e9801, But I don't know why it's showing me this error.
I tried my luck by starting threads at AVRFREAKS but no joy.
One of my friend told to try changing the device signature in the avrdude from 0x1e9801 to 0x1e9803 for a temporary try.
How can I do that.? please please please anyone help.
Thanks

You should have, somewhere in your hard drive, a file named
avrdude.conf. My copy of the file has the following lines:
#------------------------------------------------------------
# ATmega2560
#------------------------------------------------------------

part
    id               = "m2560";
    desc             = "ATmega2560";
    signature        = 0x1e 0x98 0x01;
    ...

Try changing the line with signature. Alternatively, you could make a
new entry for your MCU like this:
#------------------------------------------------------------
# ATmega2560V
#------------------------------------------------------------
# Identical to  ATmega2560 but for the signature

part parent "m2560"
    id        = "m2560v";
    desc      = "ATmega2560V";
    signature = 0x1e 0x98 0x03;


text:
AT+CENG=2,0 What type is the returning LAC?
The AT+CENG=2,0 command is giving me this result:

+CENG: 0,"0794,48,00,510,10,53,7944,10,00,36e3,255"

My LAC is 36e3 but what is the type? (Int, Double, byte, string)?
I get this code to translate cell ID and LAC into lat long:
class GMM {
  public static byte[] PostData(int MCC, int MNC, int LAC, int CID) {
    /* The shortCID parameter follows heuristic experiences:
     * Sometimes UMTS CIDs are build up from the original GSM CID (lower 4 hex digits)
     * and the RNC-ID left shifted into the upper 4 digits.
    */
    byte[] pd = new byte[] {
      0x00, 0x0e,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00,
      0x00, 0x00,
      0x00, 0x00,
      0x1b,
      0x00, 0x00, 0x00, 0x00, // Offset 0x11
      0x00, 0x00, 0x00, 0x00, // Offset 0x15
      0x00, 0x00, 0x00, 0x00, // Offset 0x19
      0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, // Offset 0x1f
      0x00, 0x00, 0x00, 0x00, // Offset 0x23
      0x00, 0x00, 0x00, 0x00, // Offset 0x27
      0x00, 0x00, 0x00, 0x00, // Offset 0x2b
      0xff, 0xff, 0xff, 0xff,
      0x00, 0x00, 0x00, 0x00
    };
    Console.WriteLine(pd.Length);
    bool isUMTSCell = ((Int64)CID > 65535);
    if ((Int64)CID > 65536) /* GSM: 4 hex digits, UTMS: 6 hex digits */
      pd[0x1c] = 5;
    else
      pd[0x1c] = 3;
    pd[0x11] = (byte)((MNC >> 24) & 0xFF);
    pd[0x12] = (byte)((MNC >> 16) & 0xFF);
    pd[0x13] = (byte)((MNC >> 8) & 0xFF);
    pd[0x14] = (byte)((MNC >> 0) & 0xFF);
    pd[0x15] = (byte)((MCC >> 24) & 0xFF);
    pd[0x16] = (byte)((MCC >> 16) & 0xFF);
    pd[0x17] = (byte)((MCC >> 8) & 0xFF);
    pd[0x18] = (byte)((MCC >> 0) & 0xFF);
    pd[0x27] = (byte)((MNC >> 24) & 0xFF);
    pd[0x28] = (byte)((MNC >> 16) & 0xFF);
    pd[0x29] = (byte)((MNC >> 8) & 0xFF);
    pd[0x2a] = (byte)((MNC >> 0) & 0xFF);
    pd[0x2b] = (byte)((MCC >> 24) & 0xFF);
    pd[0x2c] = (byte)((MCC >> 16) & 0xFF);
    pd[0x2d] = (byte)((MCC >> 8) & 0xFF);
    pd[0x2e] = (byte)((MCC >> 0) & 0xFF);
    pd[0x1f] = (byte)((CID >> 24) & 0xFF);
    pd[0x20] = (byte)((CID >> 16) & 0xFF);
    pd[0x21] = (byte)((CID >> 8) & 0xFF);
    pd[0x22] = (byte)((CID >> 0) & 0xFF);
    pd[0x23] = (byte)((LAC >> 24) & 0xFF);
    pd[0x24] = (byte)((LAC >> 16) & 0xFF);
    pd[0x25] = (byte)((LAC >> 8) & 0xFF);
    pd[0x26] = (byte)((LAC >> 0) & 0xFF);
    return pd;
  }

  public static string[] GetLatLng() {
    string[] result = new string[2];
    try {
      String url = "http://www.google.com/glm/mmap";
      HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri(url));
      req.Method = "POST";
      int MCC = Convert.ToInt32(510); //actual data
      int MNC = Convert.ToInt32(10); //actual data
      int LAC = Convert.ToInt32(36e3); //actual data - gives error here
      int CID = Convert.ToInt32(7945); //actual data
      byte[] pd = PostData(MCC, MNC, LAC, CID);
      req.ContentLength = pd.Length;
      req.ContentType = "application/binary";
      Stream outputStream = req.GetRequestStream();
      outputStream.Write(pd, 0, pd.Length);
      outputStream.Close();
      HttpWebResponse res = (HttpWebResponse)req.GetResponse();
      byte[] ps = new byte[res.ContentLength];
      int totalBytesRead = 0;
      while (totalBytesRead < ps.Length) {
        totalBytesRead += res.GetResponseStream().Read(
        ps, totalBytesRead, ps.Length - totalBytesRead);
      }
      string r = System.Text.Encoding.UTF8.GetString(ps);
      Console.WriteLine(r);
      if (res.StatusCode == HttpStatusCode.OK) {
        short opcode1 = (short)(ps[0] << 8 | ps[1]);
        byte opcode2 = ps[2];
        int ret_code = (int)((ps[3] << 24) | (ps[4] << 16) | (ps[5] << 8) | (ps[6]));
        if (ret_code == 0) {
          double lat = ((double)((ps[7] << 24) | (ps[8] << 16) | (ps[9] << 8) | (ps[10]))) / 1000000;
          double lon = ((double)((ps[11] << 24) | (ps[12] << 16) | (ps[13] << 8) | (ps[14]))) / 1000000;
          result[0] = lat.ToString();
          result[1] = lon.ToString();
          return result;
        } else {
          return result;
        }
      } else return result;
    }
    catch (Exception ex) {
      result[0] = ex.Message;
      return result;
    }
  }
}

Related: Get Latitude Longitude From AT+CNETSCAN and AT+CENG=2,0. If you don't know what LAC is, why do you care what type it is?

36e3  looks like a 16-bit hexadecimal value to me. Or it could be engineering notation (36×10³ - unlikely though since it would normally be represented as 3.6e4). What it means though I don't know - the manual would tell you.

@Nick I know what LAC is, but somehow the code above always returns null. So I was wondering if I pass the value incorrectly to google. I pass 14051 as LAC and google gives me nothing, the returning value is null.

@Juraj - Do you think this question deserves an up-vote? It's closed. The "same" moderator who closed it, answered it, and got 20 rep for it. Personally, I think it's a great question, so +10 rep.

LAC is "Location Area Code" - the code assigned by the operator to a group of cells that operate as one single broadcast unit.
It is returned to you as a hexadecimal representation of an unsigned 16 bit integer.
To know where the LAC is physically located on the planet you need to look it up in a table. I believe only the operator can give you that information. OS providers like Apple and Google most likely also have access to that data through agreements with operators.


text:
Arduino writes only one time on SD card - Data log
I connected the SD card to Arduino as it's explained here. The problem is that the Arduino writes only once to the SD card and I don't understand the reason.
#include <SD.h>
#include <SPI.h>

int CS_PIN = 4;

File file;

void setup() {
  Serial.begin(9600);
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  Serial.print("Initializing SD card...");
  if (!SD.begin(CS_PIN)) {
    Serial.println("Card failed, or not present");
    return;
  }
  Serial.println("card initialized.");
}

void loop() {
  String dataString = "TEST";
  File dataFile = SD.open("datalog.txt");
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
    Serial.println(dataString);
  } else {
    Serial.println("error opening datalog.txt");
  }
  delay(1000);
}

The output on Serial Monitor:

Arduino write only one time on SD card error opening datalog.txt error
  opening datalog.txt error opening datalog.txt error opening
  datalog.txt error opening datalog.txt error opening datalog.txt error
  opening datalog.txt error opening datalog.txt error opening
  datalog.txt error opening datalog.txt error opening datalog.txt error
  opening datalog.txt error opening datalog.txt

I also tried to use:
SD.open("file.txt", O_RDWR | O_APPEND);
SD.open("file.txt", O_RDWR | O_CREAT);

As I saw Adding data to an SD card file, but it doesn't work.

don't you need a mode when opening?

open the file in setup. then write data in loop. after all data has been written, close the file

You are opening the file in read mode but should be opening it in write mode. Change File dataFile = SD.open("datalog.txt"); to File dataFile = SD.open("datalog.txt", FILE_WRITE);.
You can remove this line of code: digitalWrite(10, HIGH);.
The arduino.cc website is also an excellent source of information regarding the SD library.

File dataFile = SD.open("datalog.txt");

Repeatedly opening the same file is probably not a good practice, if you want to retain previously written contents.

For people having the same problem. I had the same problem where the SD Card would only run the if statement once and then not read it anymore. For some reason, after I ran the CardInfo, DumpFile, and ReadWrite example scripts in the SD Library (changing the title of the SD.open() command to the one that I was using), my code began to work and it started running the if statement each time. I would recommend trying this if you're experiencing the same problem.

Interestingly enough, I was having a problem opening a file on my SD Card using the SD Card Reader Sensor and my Elegoo Mega2560 and running the CardInfo example ( on the SD Library) solved it for me. The first time the CardInfo example gave an error, and then (just saying what I did) I popped my SD Card and put it back in and then ran the CardInfo example again and then it worked. So... If you guys are having any problems. Try using the CardInfo example from the SD Library and re-insert your SD Card.

this indicates problems with the CS pin

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Arduino UNO/Nano communication with SP1ML-868 module
Good evening, I'm trying to establish serial communication between an Arduino UNO/Nano (ATMega328P) and a SP1ML-868 RF radio module (http://www.st.com/en/wireless-connectivity/sp1ml.html). I can talk to the radio with an FTDI breakout board, connected directly to my PC, but I can't do it with the Arduino.
As the radio is 3.3V and the Arduino is 5V, I tried to use the logic level converter from Sparkfun in the RX/TX lines, but that didn't work as well.
Any idea as to what I might be doing wrong? Thanks!
EDIT
I was able to talk to the radio by uploading a blank sketch to my Arduino and using only the RX/TX pins and the FTDI chip on the board. When I configure the Serial port (i.e. Serial.begin), this no longer works, which leads me to believe the problem is in the ATmega USART configuration. For some weird reason, this only works when the Arduino RX is connected to the module RX, and TX with TX.
As requested, below is the simple serial echo code I'm using, and an image with the wiring. This assumes the normal RX->TX and vice-versa connection. The module is powered through wires underneath its breakout board (3.3v).

void setup(){
  Serial.begin(115200);
}
void loop(){
  while(Serial.available() > 0){
    Serial.print((char)Serial.read());
  }
}

Please edit your question to include a complete minimal sketch that demonstrates the problem. Please edit your question to explain how you have the module wired to the Arduino board.

@per1234 There, does that help?

Not an answer to my question per-se, but I was able to solve my problem.
As mentioned on my comment on the last answer, the SP1ML module's serial communication is handled through an ARM microcontroller. So I got my hands on an Arduino Due, which has an ARM Cortex M3 MCU, and uploaded a serial echo code similar to the one on my question, only now using Serial3 to talk to the module:

void setup(){
  Serial.begin(9600);    // Connected to PC
  Serial3.begin(115200); // Connected to SP1ML, Rx-Tx connection
}
void loop(){
  if (Serial.available() > 0){
    Serial3.write(Serial.read()); // Echo to SP1ML
  }
  if (Serial3.available() > 0){
    Serial.write(Serial3.read()); // Echo to serial monitor
  }
}

I tried the exact same code on an Arduino Mega (same pins, ATmega2560 MCU) and it didn't work.
Obviously the MCUs are very different, but I have no idea one works and the other doesn't. A wild guess would be that the word sizes are different. In the Atmega, the word size is 16-bits, and in the ARM, the word size is 32-bits.

For some weird reason, this only works when the Arduino RX is connected to the module RX, and TX with TX.

This works because in that configuration you are actually using your Arduino as a USB-serial adapter. When you make the RX-RX, TX-TX connection you cannot communicate between the ATmega328P on your Uno but you are also making a RX-TX, TX-RX connection with the ATmega16U2 chip on your Uno that is used as the USB-serial adapter on the board.
I feel that it's problematic to try to use Serial (pins 0 and 1) for communication both with the computer and the module. Instead I would recommend using the SoftwareSerial library for communication between the Uno and the module.
SoftwareSerial doesn't work reliably at 115200 so you should first use the current working wiring to configure the module to communicate at a lower baud rate. 9600 is quite safe but if communications speed is a bottleneck for your application you can probably use a higher baud rate.
Next, wire the module to any unused pins on your Uno other than 0 and 1.
Finally, upload the following code to the Uno:
#include <SoftwareSerial.h>

SoftwareSerial SP1MLserial(10, 11); // RX, TX

void setup() {
  Serial.begin(115200);  // set this to the baud rate of the Serial Monitor
  SP1MLserial.begin(9600);  // set this to the baud rate of the module
}

void loop() {
  if (SP1MLserial.available()) {
    Serial.write(SP1MLserial.read());
  }
  if (Serial.available()) {
    SP1MLserial.write(Serial.read());
  }
}

This is the equivalent of the simple echo code you posted above and can be used to verify that everything is working before moving on to more complex code. I have arbitrarily chosen pin 10 for the Uno software serial RX pin 11 for the TX pin but you can modify the code to any pins that are convenient for you. You should make the connections with the module as RX-TX, TX-RX.

Thanks for the answer!  However, I tried your suggestions and it still does not work. I send a command to the module (i.e. "+++\r", to enter command mode) and get nothing in return. If it helps, this module's serial comm is done with an STM32L1 ARM MCU, which connects to the SPIRIT1 radio via SPI protocol. Maybe there is a mismatch between the SoftwareSerial protocol and the one used in the ARM?


text:
Connecting ESP8266 to Arduino Uno
I want to get data from ESP to my Arduino. I added firmware v2 to my ESP and it works correctly in my serial USB to TTL and shows the JSON data that I send to it.
But when I connect to my Uno serial it shows some unknown chars.
#include <SoftwareSerial.h> //Including the software serial library
#define DEBUG true
SoftwareSerial esp8266(2, 3); // This will make the Arduino pin 2 as the RX pin and Arduino pin 3 as the TX. Software UART
/* So you have to connect the TX of the esp8266 to the pin 2 of the Arduino and the TX of the esp8266 to the pin 3 of the Arduino. This means that you need to connect the TX line from the esp to the Arduino's pin 2 */

void setup() {
  Serial.begin(115200); // Setting the baudrate to 9600
  esp8266.begin(115200); // Set it according to your esp’s baudrate. Different esp’s have different baud rates.
  pinMode(11, OUTPUT); // Setting the pin 11 as the output pin.
  digitalWrite(11, LOW); // Making it low.
  pinMode(12, OUTPUT); // Setting the pin 12 as the output pin..
  digitalWrite(12, LOW); // Making pin 12 low.
  pinMode(13, OUTPUT); // Setting the pin 13 as the output pin.
  digitalWrite(13, LOW); // Making pin 13 low.
  sendData("AT+RST\r\n", 2000, DEBUG); //This command will reset module to default
  sendData("AT+CWMODE=2\r\n", 1000, DEBUG); // This will configure the mode as access point
  sendData("AT+CIFSR\r\n", 1000, DEBUG); // This will get ip address and will show it
  sendData("AT+CIPMUX=1\r\n", 1000, DEBUG); // This will configure the ESP8266 for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n", 1000, DEBUG); // This will set the server on port 80
}

void loop() {
  if (esp8266.available()) {
    // Checking that whether the esp8266 is sending a message or not (Software UART Data)
    while (esp8266.available()) {
      // Checking whether ESP8266 has received the data or not
      char c = esp8266.read(); // Read the next character.
      Serial.print(c);
      // Storing the response from the ESP8266
    }
  }
}

String sendData(String command, const int timeout, boolean debug) {
  // Function to send the data to the esp8266
  String response = "";
  esp8266.print(command); // Send the command to the ESP8266
  long int time = millis();
  while ((time + timeout) > millis()) {
    // ESP8266 will wait for some time for the data to receive
    while (esp8266.available()) {
      // Checking whether ESP8266 has received the data or not
      char c = esp8266.read(); // Read the next character.
      response += c; // Storing the response from the ESP8266
    }
  }
  if (debug) {
    Serial.print(response);
   // Printing the response of the ESP8266 on the serial monitor.
  }
  return response;
}

Prints this for me:
???AR)?WS?TZ?eO?C?AJ+CIFSR
+CIFSR:APHP,"192.168.4.1"
+CIFSQ:APMAC,"62:01:94:22:96:7e"

OK
AZ??R????jC?u?H?AT+CIPSERVDR=1,80

OK
0,CONNECT

+IPD,0,385:POST / HTTP/1.1
cache-control: no-cache
Postman-Token; 45494ff7-b3e1-400f-8afc-fcda26514705
Content,Type: application/jsonUser-Agent: PostmanRunthme/6.1.6
@ccept: */*Host: 192.178.4.1
accept-encoding: gzip, defl`te
content,length: 14Connection: keep-alive
{"name":"`li"}0,CLOSED

My correct JSON is: {"name":"ali"}. But it shows incorrectly. And I set the mt serial library to #define _SS_MAX_RX_BUFF 1024.
How can I fix this?
My connection is:

i used AT+UART_DEF=9600,8,1,0,0 and it works correctly now

Software serial doesn't work reliably at 115200. You need to use a lower baud rate:

Connect the ESP8266 back to your serial USB to TTL setup.
Send the following command to reconfigure the ESP8266 to do AT communication at 9600 baud: AT+UART_DEF=9600,8,1,0,3
Change line 9 of your sketch to esp8266.begin(9600);. This will cause the Uno to communicate with the ESP8266 at 9600 baud.
Upload the revised sketch to your Uno and connect it back up to the ESP8266.

when i use this command AT+UART_DEF=9600,8,1,0,3 and i change to 9600 do not show any thing or command AT no response from esp why this happen

Try connecting arduino's TX and RX pins (0 and 1) with esp8266's RX and TX and see if it works. Upload a blank sketch. Whatever you type in serial box will be sent to esp.
Instead of using voltage divider you should use logic level converters with LM2596.

i used pin 0 and 1 but nothing changed why some characters shows wrong


text:
Ultrasonic Sensor returns com3 false
Im a very beginner with Arduino. Recently started with the blink code. Thats my only experience with these. Ive got an ultrasonic sensor (As in this tutorial http://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/). So I setup the connections as trigger to Pin3 , Echo to 4, Vcc to 5v marked pin, GND to gnd next to 5v. Im using Arduino nano clone. When I run the program same as in the above example Im getting the following error. Other than that Im not getting any information.

Im sharing the same program I tried.
// defines pins numbers
const int trigPin = 3;
const int echoPin = 4;
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}

Where are you getting that error? That's not like any Arduino error I have ever seen.

I'm doing the code in Arduino web editor. I saw the above message in web console of the Arduino editor

That doesn't look like an error message - "level=info". I've never used the web editor but this page says you need to open the sidebar to see the serial monitor. Did you do that?

@JohnnyMopp Thanks a lot for that. I was using wrong console window. I was using the plugin console instead of the web console by mistake. Thanks a lot for guiding the correct way


text:
'tmElements_t' does not name a type
I've connected a real time clock ZS-042 to my Arduino Uno. I tried to set the time, using an example from DS1307RTC library. Here is my code:
#include <DS1307RTC.h>
#include <Time.h>
#include <Wire.h>

*const* char *monthName[12] = {
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

  tmElements_t tm;//it says that problem is in here

void setup() {

  bool parse=false;
  bool config=false;

  // get the date and time the compiler was run
  if (getDate(__DATE__) && getTime(__TIME__)) {
    parse = true;
    // and configure the RTC with this info
    if (RTC.write(tm)) {
      config = true;
    }
  }

  Serial.begin(9600);
  while (!Serial) ; // wait for Arduino Serial Monitor
  delay(200);
  if (parse && config) {
    Serial.print("DS1307 configured Time=");
    Serial.print(__TIME__);
    Serial.print(", Date=");
    Serial.println(__DATE__);
  } else if (parse) {
    Serial.println("DS1307 Communication Error :-{");
    Serial.println("Please check your circuitry");
  } else {
    Serial.print("Could not parse info from the compiler, Time=\"");
    Serial.print(__TIME__);
    Serial.print("\", Date=\"");
    Serial.print(__DATE__);
    Serial.println("\"");
  }
}

void loop() {
}

bool getTime(const char *str)
{
  int Hour, Min, Sec;

  if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
  tm.Hour = Hour;
  tm.Minute = Min;
  tm.Second = Sec;
  return true;
}

bool getDate(const char *str)
{
  char Month[12];
  int Day, Year;
  uint8_t monthIndex;

  if (sscanf(str, "%s %d %d", Month, &Day, &Year) != 3) return false;
  for (monthIndex = 0; monthIndex < 12; monthIndex++) {
    if (strcmp(Month, monthName[monthIndex]) == 0) break;
  }
  if (monthIndex >= 12) return false;
  tm.Day = Day;
  tm.Month = monthIndex + 1;
  tm.Year = CalendarYrToTm(Year);
  return true;
}

and this is my output:
Arduino: 1.6.12 (Windows 10), Плата:"Arduino/Genuino Uno"

In file included from C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino:1:0:

C:\Users\папа\Documents\Arduino\libraries\DS1307RTC/DS1307RTC.h:19:22: error: 'tmElements_t' has not been declared

     static bool read(tmElements_t &tm);

                      ^

C:\Users\папа\Documents\Arduino\libraries\DS1307RTC/DS1307RTC.h:20:23: error: 'tmElements_t' has not been declared

     static bool write(tmElements_t &tm);

                       ^

SetTime:10: error: 'tmElements_t' does not name a type

   tmElements_t tm;

   ^

C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'void setup()':

SetTime:21: error: expected primary-expression before ')' token

     if (RTC.write(tm)) {

                     ^

C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'bool getTime(const char*)':

SetTime:54: error: expected unqualified-id before '.' token

   tm.Hour = Hour;

     ^

SetTime:55: error: expected unqualified-id before '.' token

   tm.Minute = Min;

     ^

SetTime:56: error: expected unqualified-id before '.' token

   tm.Second = Sec;

     ^

C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'bool getDate(const char*)':

SetTime:71: error: expected unqualified-id before '.' token

   tm.Day = Day;

     ^

SetTime:72: error: expected unqualified-id before '.' token

   tm.Month = monthIndex + 1;

     ^

SetTime:73: error: expected unqualified-id before '.' token

   tm.Year = CalendarYrToTm(Year);

     ^

exit status 1
'tmElements_t' does not name a type

Check the order of header files and check the dependencies. Do you have the right libraries. Looks like you have modified this example sketch; https://github.com/PaulStoffregen/DS1307RTC/blob/master/examples/SetTime/SetTime.ino

IDE 1.6.10: compilation of sketches wich time library fails

Welcome to Arduino Stack Exchange.  You can take the tour at https://arduino.stackexchange.com/Tour to get the best out of this site.

Clearly the compiler does not know what tmElements_t means.
It is defined in TimeLib.h
In your program you reference Time.h instead, where it is not defined.
So:  Change
include <Time.h>

to
include <TimeLib.h>

and it should clear that error.

Time.h was changed to TimeLib.h specifically to combat this problem. The compiler started providing time.h, and on operating systems like Windows that use a case-insensitive filesystem it confuses Time.h and time.h.

Thank you for help! It works! The problem was in TimeLib.h. Literally, it wasn't in my lib, so i had to re-install it. Then I changed include as you said and it works.

But for now I've got another trouble. My serial port doesn't print anything.

Take out the while (!Serial) - once you do the Serial.begin(9600) you can assume it is ready to receive output.  Also, be aware that in the Arduino IDE, opening the serial monitor will restart your program.


text:
NodeMCU stops responding after several hours
I'm controlling some devices through a relay and a NodeMCU, it works fine and reconnects without problem in the meantime I'm testing it, but after I leave it like for 3 or more hours, it stops responding. I need this system to always be working without sleeping or anything. Here is my code:

#include <ESP8266WiFi.h>

const char* ssid = "wifi_Guerrero ";
const char* password = "3245968530";

int ledPin = 13; // GPIO13
int ledPin2 = 12; // GPIO13
int desconectado = 5;
int conectado = 4;
WiFiServer server(80);
WiFiClient client;

int counter = 0;

void setup() {
  Serial.begin(9600);
  delay(10);

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);

  pinMode(ledPin2, OUTPUT);
  digitalWrite(ledPin2, LOW);

  pinMode(conectado, OUTPUT);
  pinMode(desconectado, OUTPUT);
  digitalWrite(desconectado, HIGH);

  connectWifi();

  Serial.print(F("Setting static ip to : "));
  Serial.println(WiFi.localIP());

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

}

void loop() {

  delay(200);

  if (WiFi.status() != WL_CONNECTED) {
    delay(100);
    digitalWrite(conectado, LOW);
    digitalWrite(desconectado, HIGH);
   connectWifi();
  }

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

  // Wait until the client sends some data
  Serial.println("new client");
  int t = millis();
  while(!client.available()){
  delay(1);
  if (millis()-t>130) return;
  }

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

  // Match the request
  if (request.indexOf("/switch") != -1)  {
    digitalWrite(ledPin, !digitalRead(ledPin));
    digitalWrite(ledPin2, !digitalRead(ledPin2));
    printSwitch();
  }else if (request.indexOf("/uno") != -1) {
    client.print("Canal 1 apagagado | Canal 2 encendido");
    digitalWrite(ledPin, HIGH);
    digitalWrite(ledPin2, LOW);
  }else if (request.indexOf("/dos") != -1){
    client.print("Canal 1 encendido | Canal 2 apagado");
    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin2, HIGH);
  }else if (request.indexOf("/tres") != -1){
    client.print("Canal 1 apagado | Canal 2 apagado");
    digitalWrite(ledPin, HIGH);
    digitalWrite(ledPin2, HIGH);
  }else if (request.indexOf("/cuatro") != -1){
    client.print("Canal 1 encendido | Canal 2 encendido");
    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin2, LOW);
  }else if (request.indexOf("/cinco") != -1){
    printIP();
  }else if (request.indexOf("/apagaruno") != -1){
    client.print("Canal 1 apagado");
    digitalWrite(ledPin, HIGH);
  }else if (request.indexOf("/apagardos") != -1){
    client.print("Canal 2 apagado");
    digitalWrite(ledPin2, HIGH);
  }else if (request.indexOf("/prenderuno") != -1){
    client.print("Canal 1 encendido");
    digitalWrite(ledPin, LOW);
  }else if (request.indexOf("/prenderdos") != -1){
    client.print("Canal 2 encendido");
    digitalWrite(ledPin2, LOW);
  }else if (request.indexOf("/canaluno") != -1){

    if(digitalRead(ledPin) == HIGH) {
      client.print("Off");
  } else {
    client.print("On");
  }

  }else if (request.indexOf("/canaldos") != -1){

    if(digitalRead(ledPin2) == HIGH) {
    client.print("Off");
  } else {
    client.print("On");
  }

  }

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

  // Return the response

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

}

void printSwitch(){
  if(digitalRead(ledPin) == LOW) {
    client.print("Canal 1 Encendido");
  } else {
    client.print("Canal 1 Apagado");
  }
  Serial.println("");
  if(digitalRead(ledPin2) == LOW) {
    client.print("Canal 2 Encendido");
  } else {
    client.print("Canal 2 Apagado");
  }
}

void printIP(){
  delay(100);
  client.print(WiFi.localIP());
}

void connectWifi()
{
  Serial.print("Connecting to "+*ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
  }

  // config static IP
  IPAddress ip(192, 168, 0, 8);
  IPAddress gateway(192, 168, 0, 1);
  IPAddress subnet(255, 255, 255, 0);
  WiFi.config(ip, gateway, subnet);
  digitalWrite(conectado, HIGH);
  digitalWrite(desconectado, LOW);
  Serial.println("");
  Serial.println("Connected");
  Serial.println("");

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

You need to understand why it is stopping.  Start with something like printing serial log messages and capturing them to a log file that you can examine after failure.  Preferably do this over a pure UART connection (to a distinct USB to logic-level-serial) without using the on-board USB converter, unless you plan to have the USB connected to a PC in operation.  Though you can of course start with the on-board USB and see if you learn something, it's just that there's a risk that having that plugged in could hide power-related failure causes.

You should also consider if there are design errors in your unspecified electrical circuit.  Particularly things like insufficient input voltage to a regulator, relay coils without catch diodes, or any sharing of the logic and load power supplies.

I think the problem is not about the circuit or power supply, because I also left it on AP mode and when the static ip I assigned to it stopped responding, I connected directly to it's AP with 192.168.4.1 and it responded, after trying that, I tried again with static IP and worked fine, it seems like it sleeps or something programatically

The answer here might help you: https://arduino.stackexchange.com/questions/75494/esp8266-not-responding-after-random-intervals-of-time

I think thatthe problem lies with this definition
String request = client.readStringUntil('\r');

which you define dynamically in loop this leads possibly to heap fragmentation, causing resets after sometime
Define a global char array
char request [256] ={'\0'};
char c;
uint cc = 0;

and work instead the String functions with
while(client.available()){
c = client.read();
if (c != '\r'){
  request[cc] = c;
   cc++;
 }
 else return;
}

then handle the filled request buffer like
if (strcmp(request,"/switch") != 0)  {
  ....
 }

This should keep you esp running

That doesn't compile. You need a closing round bracket in your while loop. I also get:
error: empty character constant
char c = '';

You need to add a line where you’re reading into that buffer to make sure you don’t overrun.  Make sure cc doesn’t go over 255.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Boat project - object detection
My project is to control a dual motor model boat via bluetooth hand-held device. I am using an Adafruit feather 32u4 bluefruit LE and Adafruit DC Motor + Stepper FeatherWing Add-on. I am using the Apple IOS Adafruit Bluefreuit BLE app as the controller. I have this part of the design nearly done.  I plan to use this in a swimming pool.
How can I have the boat automatically avoid the sides of the pool or any other obstruction?  Also how can I have the boat steer toward a buoy in the water?
I would like to have any solutions as low-cost.
Thanks in advance

I'm voting to close this question as off-topic because it is about a challenging and open-ended robotics sensing problem which must be solved before the practical details of the limited aspects that an Arduino could help with can be considered.

You might be able to accomplish something with underwater sonar transducers on the sides of the boat detecting the walls at one frequency, and also differentialy listening for a sonar beacon on the buoy at another, but this is far beyond the scope of the Arduino site - both in understanding the sonar issues, and in the drive/transducer electronics for underwater use.  Similarly, an optical solution will require a far more sophisticated computation platform - the actual spinning the motors that that the Arduino could handle is relatively trivial in comparison.

Chris, I take your point about being open-ended, but I was unaware that open-ended questions were off-limits.  Sorry.  I was only asking for some ideas some of which you included in your response.  I thank you for that.

Open-ended questions don't really fit the Stack Exchange model in general, but the main point is that this isn't ready for the Arduino site yet - you have a robotics problem, then an electronics one, and only possibly at the end an Arduino one.   It does occur though that your needs are likely short range enough that you may not need efficient underwater transducers, but merely audio parts that can tolerate being wet and be operated in bistatic mode - neither of which is true of the HC-SR04 type modules familiar to Arduino folks.

Thanks for all your feedback Chris.  This was my first post and I now have more of an understanding of the types of questions that this site is designed for.  Future posts will keep that in mind.  I love the site... a great resource for people who enjoy arduino projects like myself.

@Will, please take another look at the tour at https://arduino.stackexchange.com/Tour and you can see that the whole idea is to set a goal, make an attempt to make it work, then when you need help, post your efforts (including code) as you form a specific question that will generate useful answers.  This is a database where people with similar problems can find answers.  Their queries are usually pretty specific.  I can't vote to close a first post on the first day, but I highly suggest that you edit this question to make it conform to the way people will use this in the future.

@SDsolar - while that is correct, a question like this probably can't be edited to fit the Arduino site at this point, because the information being sought right now is precisely that which would narrow the broadness and off-topicness that keeps it from being a fit.


text:
Unknown type name 'IRsend'
In the C file in simplesample_mqtt.c, which connects Arduino to the Azure IoT hub, I need to use the IRsend and IrRemoteESP8266 libraries to send an infrared signal with Azure IoT hub.
 #include <IRremoteESP8266.h>
 #include <IRsend.h>
 IRsend irsend(10); // An IR LED is controlled by GPIO pin 4 (D2)

I don't have any problem when I use this code in my main Arduino file. But when I use these includes in a C file (simplesample_mqtt.c), I get this error from line 3: "unknown type name 'IRsend'".

error full info :
Arduino: 1.8.2 (Windows 10), Board: "NodeMCU 0.9 (ESP-12 Module), 80 MHz, 115200, 4M (3M SPIFFS)"

In file included from sketch\simplesample_mqtt.c:29:0:

C:\Program Files (x86)\Arduino\libraries\IRremoteESP8266\src/IRsend.h:29:1: error: unknown type name 'class'

class IRsend {

C:\Program Files (x86)\Arduino\libraries\IRremoteESP8266\src/IRsend.h:29:14: error: expected '=', ',', ';', 'asm' or 'attribute' before '{' token

class IRsend {

simplesample_mqtt.c:31: error: unknown type name 'IRsend'

IRsend irsend(10); // An IR LED is controlled by GPIO pin 4 (D2)

simplesample_mqtt.c:31: error: expected declaration specifiers or '...' before numeric constant

IRsend irsend(10); // An IR LED is controlled by GPIO pin 4 (D2)

exit status 1
unknown type name 'IRsend'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

error: unknown type name 'class' Classes only exist in C++. Try changing the file extension to ".cpp".

And if that doesn't work, make sure the class in IRremoteESP8266.h has a ; after the closing }

I solved this problem. The reason for this is because main Arduino is c++ and simplesample_mqtt.c is c code and we have to use c++ code in c code:
In main Arduino file you have to declare function like this :
extern "C" void TurnOn();
void TurnOn()
{
    digitalWrite(RELAY_SONOFF, HIGH);
    digitalWrite(LED_SONOFF, HIGH);
}

and use this function in c code:
void TurnOn();
EXECUTE_COMMAND_RESULT TurnOn(ContosoAnemometer* device)
{
    (void)device;
    TurnOn();
    (void)printf("Turning fan on.\r\n");
    return EXECUTE_COMMAND_SUCCESS;
}


text:
ESP8266 disconnects after relay switch
the aim of the project I'm working on is to water my bonsai automatically, depending on numerous sensor inputs. So basically I have Arduino Nano with huminity and light sensor, a relay to switch the water pump and ESP8266 wifi module, which I use to check the data from the sensors in the Blynk app on my phone. I use two isolated circuits. The first one is used only by the DC motor (water pump) and is supplied by a 5V 600 mA power source. The second takes care of the rest (arduino, ESP, sensors, relay) while it's supplied by a 5V 1A power source. I'm using this with the ESP8266 board.
Once I run the program, it connects to the Blynk server and I can read data from the sensors on my phone. The problem comes when I want to switch the relay from the Blynk app. Than the ESP8266 disconnects (nearly immediately, or after few seconds). I tried a different DC motor (not a water pump) and it worked fine. I also tried to switch the pump without using EPS8266, that worked as well (so the code should be ok). I think this has something to do with the current draw caused by the water pump, but that makes no sense - I'm using two independent circuits, the pump draws maximally 300 mA from the 600 mA source, while the rest of the electronics draws no more than 200 mA from the 1 A power supply. Neither different power supplies, nor another relay worked.
Here's my code:
#define BLYNK_PRINT Serial
#define BLYNK_DEBUG

#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>

#include <BH1750.h>
#include <Time.h>
#include <SoftwareSerial.h>

#define PUMP  10
#define SENSOR A0
#define BUTTON 2

char ssid[] = "XXXXX";
char pass[] = "XXXXXXXXXXXXXXXXXX";

SoftwareSerial EspSerial(11, 12);
ESP8266 wifi(&EspSerial);

BlynkTimer timer;
BH1750 lightMeter;
int humidity;
int light;
bool pressed = 0  ;
bool pump=1;
char auth[] = "XXXXXXXXXXXXXXXXXXXXXXXXXX";

void sendData(){
      humidity=analogRead(SENSOR);
      light=lightMeter.readLightLevel();
      Blynk.virtualWrite(V0,humidity);
      Blynk.virtualWrite(V1,light);
//      Serial.print("humidity: ");
//      Serial.println(humidity);
//      Serial.print("light: ");
//      Serial.println(light);
}
void checkConnection(){
  if(!Blynk.connected()){
    digitalWrite(PUMP,1);
    Blynk.begin(auth, wifi, ssid, pass);
  }
 }
void checkButton(){
  if(digitalRead(BUTTON) && pressed){
     Blynk.virtualWrite(V3,digitalRead(BUTTON));
     pump=!pump;
//      Serial.println("pump from button");
     }
  else if(digitalRead(BUTTON) && !pressed){
    pressed=1;
    }
  else{
    pressed=0;
    }
}
BLYNK_WRITE(V2)
{
    Serial.println("switching pump");
    pump=!param.asInt();
    digitalWrite(PUMP,pump);
}
void setup() {
  Serial.begin(9600);
  delay(10);
  EspSerial.begin(9600);
  delay(10);
  lightMeter.begin();
  pinMode(PUMP, OUTPUT);
  pinMode(BUTTON, INPUT);
  digitalWrite(PUMP, pump);
  Blynk.begin(auth, wifi, ssid, pass);
  timer.setInterval(5000L, sendData);
  //timer.setInterval(5L, checkButton);
//  timer.setInterval(2000L, checkConnection);
  }

void loop() {
  if (Blynk.connected()) {
      Blynk.run();
      timer.run();
    }
}

and the Blynk log:
[2631095] <[06|05|14|00|00]
[2631389] >[00|05|14|00|C8]
[2632112] <[14|05|15|00|08]vw[00]0[00]632
[2632280] <[14|05|16|00|07]vw[00]1[00]28
[2637109] <[14|05|17|00|08]vw[00]0[00]630
[2637214] <[14|05|18|00|07]vw[00]1[00]28
[2641393] <[06|05|19|00|00]
[2651445] Cmd error
[2656470] Cmd skipped:20
[2656471] Cmd skipped:20

[EDIT] and the circuit:

Your question does not have any schematic or other details regarding the hardware.  Optical relay?  Mechanical relay?  If mechanical did you use a fly-back diode? Or mechanics.  Were you testing the motor under load? (For example with water in the pump?)  Or did you try it with no load?  (For example, dry?)  Are the power supplies floating?  Did you share a common ground?

@st2000 Hi, thanks for your response. I added the circuit to my post. I'm using this 1 channel relay from ebay. The motor was tested under load. I'm sharing a common ground. Neither of the power supplies is connected to the ground pin in the power socket (so they're both floating, I guess).

Separate your grounds.  The relay provides isolation.  The optical coupler even more.  I see you may be driving the EPS8266 with a 5 volt signal.  Yet it is power from a 3.3 volt source.  This is not a good arrangement.  Unless the EPS8266 has over voltage protection on its input, this could lead to unexpected results.  The relay in your schematic is very confusing.  I am hoping that it actually is something very different from the symbol.

Separating the grounds really did the thing - thanks a lot! I just don't understand why? And is there any way I could power both the electronics and the water pump from only one power supply?
@st2000 As I mentioned in my question, I'm using this board with the ESP8266. Regarding the relay - I used the symbol I found in Fritzing. Link to the relay I'm actually using is mentioned in my previous comment.

Not absolutely sure w/o testing why separating the grounds works.  However, it is likely you are still (and this still might the the root cause of your problems) driving a 3 volt powered ESP8266 with a 5 volt serial port signal.  This is not good.  You might, at the very least, look into a resistor divider circuit to reduce the serial port voltage down to 3 volts.

The problem was hidden in a wrong relay wiring. Once I'm using only COM and NO PIN as it is showed in this article, not only that the whole system is stable and the ESP8266 is not disconnecting any more, but I can also power the circuit using only one 5V 2A power supply.
Here's my updated schematics


text:
Elegoo "Uno R3" not being recognized in any computer anymore
I used to be able to use my Elegoo Uno R3, just fine. It worked with my computer no problem. Except I used the USB cable on a power bank and now the Uno isn't being recognized on any computer. I tried uninstalling and re-installing the IDE and drivers. But nothing works. I don't even get the serial 2.0 USB in the device manager. the Uno itself works. The orange and green lights stay on continuously when plugged in and It's still outputting the code I put in it before it stopped connecting to my computer. Any help to be able to fix my Uno. The button on the UNO doesn't seem to do anything either.

Worth trying a different cable, but likely you've damaged it.  That power bank should be considered suspect, and probably not used again with anything you value.

I did try a different cable but no luck


text:
WiFi101 Client HTTP POST fails after 3rd request
I would really appreciate any help, my home project has been put on hold for weeks as I haven't been able to figure this out. In a nutshell, I'm connecting to my wifi network, measuring temperature from a sensor, and sending that temperature data to a server via a HTTP Request. All of that stuff works.
I have it in a loop, and on the 3rd HTTP request I get 'Connection Failed' when it's trying to client.connect(server, 80) - I don't understand why it fails. I've tried adding client.stop() and client.flush() after each HTTP request, but nothing fixes it. Below is my sketch file with some of the temperature code removed to make it easier to read
#include <SPI.h>
#include <WiFi101.h>
#include <string.h>
#include <stdlib.h>
#include <OneWire.h>
#include <DallasTemperature.h>

//WiFi Client Setup
char ssid[] = "HIDDEN";    //  your network SSID (name)
char pass[] = "HIDDEN";       // your network password
int status = WL_IDLE_STATUS;    // the WiFi radio's status
char server[] = "HIDDEN";
WiFiClient client;

// Setup for temperature sensor
#define ONE_WIRE_BUS A5
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
DeviceAddress insideThermometer;

void setup() {
  Serial.begin(9600);
  WiFi.setPins(8,2,A3,-1);
  while (!Serial) {
    Serial.println("Waiting for serial");
  }

  //Connect to wifi shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    while (true);
  }
  wifiConnect();
  sensors.begin();
}

void loop() {
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }
  /*
  Code to get temperature here
  */
  httpRequest(temp);
  delay(10000); // 5min
}

void httpRequest(String temp) {
  String request = "POST /api/webhooks/temp?temperature=" + temp + " HTTP/1.1";

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connected to server");
    client.println(request);
    client.println("Authorization: Token HIDDEN");
    client.println("Host: HIDDEN");
    client.println("Connection: close");
    client.println();
  }
  else {
    Serial.println("Connection failed");
  }
}

void wifiConnect() {
  //Attempt to connect to WiFi network:
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    delay(1000);
  }

  Serial.println("You're connected to the network");
}

I am so disappointed by the lack of support in arduino community, lack of good documentation, and poorly written hardware/libraries. Even the example sketches fail.

I tried changing the strings to char's, that didn't work.
Verified that it was closing connections with the server, check.
Was reading around and saw someone who tried a soft reset of the wifi client here. I added the following to the end of my httpRequest() method
client.stop();
WiFi.end();
delay(10);
WiFi.begin(ssid, pass);

And now it's working just fine. I'm going to have it run all night and see if there are any issues, but it's definitely an improvement as I can make more than 3 requests :|
This seems like a terrible work around. Clearly something isn't getting reset after each HTTP request on the wifi client, and this (right now) is the only way to solve it. I'd really love any other feedback on a better ways to solve it. Seems like some issues with the WiFi101 Library.

Are you still using this method?

I had the same issue. I can send consecutive requests, but if client.connect fails (e.g. timeout or whatever), then all subsequent requests fail. The only way of recovering is doing what you have done WiFi.end() + WiFi.begin(), in my case only after failure.
It happens with both WiFi101 and WiFiNINA (my project runs on both boards)


text:
2 Channel Relay normal open is not working with NodeMCU but led on board light up
I am pretty new to NodeMCU (ESP8266) and Arduino IDE in general. I followed various documentation / blogs to set up 2 Channel Relay with NodeMCU chip.
Below is sketch code for it.
#include<CayenneMQTTESP8266.h>
#define CAYENNE_DEBUG
#define CAYENNE_PRINT Serial

#define LEFT_GARAGE 4
#define RIGHT_GARAGE 5

char ssid[] = "XXXXXXXXXXXXXXXXXXXXXXXX";
char password[] = "XXXXXXXXXXXXXXXXXXXXXX";

char username[] = ""XXXXXXXXXXXXXXXXXXXXXX";";
char mqtt_password[] = ""XXXXXXXXXXXXXXXXXXXXXX";";
char client_id[] = ""XXXXXXXXXXXXXXXXXXXXXX";";

void setup() {
  Cayenne.begin(username, mqtt_password, client_id, ssid, password);
  pinMode(LEFT_GARAGE, OUTPUT);
  digitalWrite(LEFT_GARAGE, HIGH);
  pinMode(RIGHT_GARAGE, OUTPUT);
  digitalWrite(RIGHT_GARAGE, HIGH);
}

void loop() {
  Cayenne.loop();
}

// Left Garage Door
CAYENNE_IN(0){
  int currentValue = getValue.asInt();
  digitalWrite(LEFT_GARAGE,!currentValue);
}

//Right Garage Door
CAYENNE_IN(1){
  digitalWrite(RIGHT_GARAGE,!getValue.asInt());
}

On relay board I tried to connect wire in 2 different configuration.
1st Config:
vcc -> 3.3v from NodeMCU
in1 -> D1/GPIO 04 from NodeMCU
in2 -> D2/GPIO 5 from NodeMCU
GND -> GRD from NodeMCU

2nd Config:
vcc -> 5v USB from NodeMCU
in1 -> D1/GPIO 04 from NodeMCU
in2 -> D2/GPIO 5 from NodeMCU
GND -> GRD from NodeMCU

In 1st config, On relay board respective LED's are turning on when Cayenne buttons are pressed but when I check for continuity on multi meter I don't get anything.
In 2nd config, no LED and no continuity.
am I missing something here? Any feedback/comments are highly appreciated.

Your second configuration is right because from picture of relay module it clear that it requires 5V supply.
 relay working principal is:

when the signal port(in1/in2) is at low level, the signal light will light up and the optocoupler (it transforms electrical signals by light and can isolate input and output electrical signals) will conduct, and then the transistor will conduct, the relay coil will be electrified, and the normally open contact of the relay will be closed.
When the signal port(in1/in2) is at high level, the normally closed contact of the relay will be closed. So you can connect and disconnect the load by controlling the level of the control signal port.

As you mentioned that in second configuration there is no LED glow. For find out solution of your problem, you have do one test. Test voltage level of D1/D2. Just make connection on breadboard as mentioned in image.
If voltage level is correct that it might be problem with your relay module.
Also I have attached here relay connection reference for your directness.


text:
How to listen for an incoming serial string inside loop with long delay?
I'm trying to build a datalogger using Arduino UNO, I'll use RS232 for the communication between PC and Arduino, the problem I'm facing now is that I'm using delay(10000) : 10 seconds as a timestep for data acquisition. however, I can't find any solution to receive a string from the serial input to Arduino while delay is executing. Here is the code :
void setup() {
  Serial.begin(9600);
}

void loop() {
  serialRoutine();
  dataLoggingEvery10Second(); // That's a function to receive data from the sensor and store it in SD card.
  delay(10000);
}

  // A function to handle all the serial in out
  void serialRoutine(){
  // print the string when a newline arrives:
  while(Serial.readString() == ""){
    String serstr = Serial.readString();
      /*
      *  Getters
      */
      if(serstr == "GETDATA"){
        Serial.println("Here is my data");
      }
      serstr = "";
  }
}

Any help would be highly appreciated !

You could also look at interrupts.

Why the delay at all? Nothing will happen until it receives GETDATA anyway, so what is the point of the delay?

I can't find any solution to receive a string from the serial input to Arduino while delay is executing. - why do you need to receive data anyway? Aren't you sending it?

Sorry guys, I forgot to put the data acquisition function between serialRoutine(); and delay(10000);

while(Serial.readString() == ""){String serstr = Serial.readString(); - this seems to me to be reading two strings.

void loop() {
  static unsigned long prev = 0;
  unsigned long now = millis();

  if (now - prev >= 10000L) {
    serialRoutine();
    dataLoggingEvery10Second();
    prev = now;
  }
}

This will executed at time 10s, 20s, etc. I

Thank you so much ! is this code applicable for a timestep of 15 to 30 minutes ?

Sure. You only have to change the 10000L value for the interval that you want.

If your PC is sending GETDATA, then it can send it every 10 seconds (or every 15 or 30 minutes) so you don't need any delays at the Arduino end at all.
I have a page about getting serial data without blocking which illustrates how you can be doing other things (like reading sensors) without blocking.
An example sketch is:
/*
Example of processing incoming serial data without blocking.

Author:   Nick Gammon
Date:     13 November 2011.
Modified: 31 August 2013.

Released for public use.
*/

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop


text:
Android, Raspberry, Atmega, SQL communication
Hej there,
I have a small project at home and I'm curious if people have some advice/idea for me. Because I'm not sure if the communication between the different devices is the way to go.
This is my current setup:
I have a Android application running on an Android device (tablet). This Android device can communicate with a MySQL server with a json/PHP. The Android device is receiving data from the database but also writing data to it. The MyQL/web server is running on a Raspberry.
The second device is an atmega328p microcontroller(http://www.ebay.com/itm/2-x-ATMEGA328P-PU-ATMEGA328-MICROCONTROLLER-IC-Free-Shipping-/280994585126) that is sending temperature/humidity to the MySQL server on the Raspberry. The ATmega is communicating through a 433 MHz chipRF(MX-05V). The Raspberry also has a 433 MHz chip RF(MX-05V) that is receiving this data and writing it to the MySQL server.
So actually the ATmega is communicating with the Raspberry and the Raspberry is communicating with the MySQL server.
It is working properly but I'm not sure if this is the way to go. So my question, what are you thoughts of this setup, what would you do different and why?
Thanks, Matthijs

A picture says a thousand words.  I really don't know how to answer you question because I'm not sure what your setup is.  Also people are going to vote to close the question because its not at all clear.  Can you draw a system diagram and try and clarify what you mean by a 433MHz chip (I think you mean a radio, but...)   If the Raspberry (or Pi for short) is running the SQL server then if the ATMega is talking straight to the SQL socket that is different to it talking to a daemon or app which talks to SQL.  Hope that helps, give it an edit and I'll look again :) (I'm meant to say Hi but

I've run out of letters :)

If it is stupid and it works ... it ain't stupid! Though i see how you do it ive done the same some other way, ive used the ESP8266 to transmit the data to the cloud skipping the raspberry pi server and the android app just leaving a website to check the data. Not saying your suggestion is wrong. Just inspiration.

@Magic-Mouse thanks for the responce. My raspberry also have a NRF24L01. This is similar to the ESP8266  i thinks. I use it to communicate with the Milight lights.

@CodeGorilla Thanks for responding, edit the text a bit. Thanks, going to add a classdiagram later.

Not a class diagram, I suspect the code is trivial (no offence intended).  You need a diagram of the 'bits' the exes the hardware, the 'links'.  Don't think like a softie think like a "systems engineer"

What are your concerns? Stability, costs, bandwith, expandability, reliability?

@Paul reliability. Don't want to lose data because I have to mucht incoming data.

If I understand correctly:

You have a Pi hosting MySQL and a web server.
A Mega writes temp/humidity data to the server.
An android device reads data from the web server.
The Pi and the Mega talk over a 433(MHz) radio?

Is it the write way to go?
What you have is a tried an tested design, a central server responsible for collating at serving the data.  My one concern is the 433 radios, I think you might be limiting the scalability of your design by using that.  What happens if you want to add a second Mega to report a different sensor?  You PI needs a second receiver and a second app to read, although the PI will handle 2, easily, there will be a point where it can't handle any more.  I'd suggest that you look at technology that allows multiple nodes on the same network, WiFi.
You could use WIFI by either getting adding a WiFi device to you Mega or ditching the expensive Mega and buying a $2 Wemos D1.
But that's just my opinion, and unfortunately that's the reason this question will get closed, because asking for people's opinions is taboo.

Thanks for the responce, i tested it with 2 atmega's and this works properly. But i can agree on the fact that it can be limited when i want to add more atmega's. I need to test it to see if it still works with for example 5 atmega's.

But why spend $40 on a mega when you can spend $2 on an ESP and program it exactly the same way?

sorry for the confusion.. i mean the atmega328p microcontroller: http://www.ebay.com/itm/2-x-ATMEGA328P-PU-ATMEGA328-MICROCONTROLLER-IC-Free-Shipping-/280994585126

OIC.  I Still reckon this is better http://www.ebay.com/itm/D1-Mini-NodeMcu-4M-bytes-Lua-WIFI-Development-Board-ESP8266-by-WeMos-/182035363514?epid=514207412&hash=item2a622736ba:g:NSYAAOSwe7BWzu4m  :)

https://i.stack.imgur.com/Uq7w1.jpg on the right u see the atmega with a movement sensor, light sensor, temp and humi. On the left the same only in testing format. I do not know the esp8266. I will check it out. Thanks!

The D1 Mini NodeMcu looks impressive! Thanks for the inspiration!


text:
Dynamic SSID + Password from ESP8266WiFi
I'm using the ESP8266WiFi library on a NodeMCU, running the arduino bootloader in the arduino software (Windows 10 app version).
I'm trying to load the SSID and password from SD-card (this part is successfull).
My problem this far is when i use the Wifi library it looks like this:
 Wifi.begin(const char*, const char*);

Since it takes 2 const parameters i cannot change it later. Is there anyway i can add SSID and PASSWORD to my sketch without having to recompile it. (I have to send it to people who does not know how to compile and flash an arduino)
I'm not attached to the ESP8266WiFi library, i'm not attached to SD-card, other solutions are welcome.
SD-reader works as planned, WiFi works as planned with a static password and SSID.

The const keyword there does not force the data you call it to be constant, it only forbids certain assignments with the parameters inside that function but it's just superfluous in most cases. Meaning you can call it with input you got from serial or some other source (for ex. setup page accessible from hotspot->Store in EEPROM->Next boot connect to set WiFi AP). There's also a nice StackOverflow thread about this here and why it's not actually a good idea in many cases.

I've considered this, but i think the user is on a level here where connecting to a temp hotspot would be too advanced. I even think that downloading a configuration file to an SD card is on the edge of too advanced - Thats my problem. Though i think your reply gave me an idea on how to fix it. Let me just try it out and if it works you get the correct answer.

The problem was not const char*, but bad conversion from string to char*.
Thing that lead me to believe it was the const char* was an unclear compiler message, and poor understanding of C++ data types.
but the correct answer was:
 ssid.toCharArray(ssidc, ssid.length());


text:
Can we use yx5300 to play audio from a file in Arduino?
I want to play a file that I have in my USB device through a yx5300 mp3 module.
I have a file in my USB device at path Music/hello.mp3. I want to play this file using the yx5300 module or some other module, if available.
I have already read this file using a shield. I want to pass the data to the yx5300.

No. That chip can only play files on an SD card that is directly attached to it.

So what else can I use..??

The Itead music player shield (https://www.itead.cc/wiki/ITEAD_Music_Player_Shield) may be of use. It can play direct from a USB memory stick.

This shield is unavailable ...Can you tell any other or where to buy....

No better than Google can.

https://github.com/Seeed-Studio/Music_Shield?files=1.  Can this library for music shield provided by seed used with any other music shield


text:
Solution to interrupt Arduino every n seconds
I'm a very beginner with electronics and of course with Arduino. Actually I've been in the software field (.NET) for the past 12 years. I am trying to develop a simple system to run for longer using Arduino Nano. Longer means roughly it could be for years continuously, expecting normal wear and tear.
So what I understood is Arduino loop always executes based on any values from sensors while in the loop. And also Arduino has some interrupt mechanism too.
But since the looping system feels pretty awkward for some situations, I tried to stop the loop using exit(0); inside the loop. So loop will stop  after the first execution.
I am trying to build an external simple interrupt hardware system (like any timer object in software) which interrupts Arduino in a specified interval, say 20 sec. So when that interrupt on that particular pin occurred we can call some function there to do the job and that's all from Arduino side and it can go back to sleep.
So I believe this will reduce the load on Arduino and of course since no looping it will not get heated at all. How can we make such a system (external timer) to interrupt Arduino in specific intervals? This is just a theory in mine, not an idea how to implement it in electronics.
How can I achieve this above scenario?

You can implement sleep timers in code. No need for external circuits

So, since you're coming from the application domain there are some things you might want to consider:

Make sure to always stay inside the super loop. With an Arduino or any other Microcontroller (not using a RTOS) you do not have anything defined that's going to happen after the superloop. Everything that happens after this loop is basically undefined (it typically is a reboot or jump to a default interrupt handler but may also be a lockup). Simply telling the processor to "exit" will .. well, exit - but you have no idea where it's going after that. To allow for interrupts and further execution of your main code, you need to have your processor in a defined state (and that basically is the super-loop). as a comparison with your PC, after you exit a thread, the operating system will take over. On your Arduino there is no such concept. The super-loop IS your OS (well, at least it's some minimum implementation of a non-preemptive scheduler).
If you want to have only interrupt actions active while the processor is using only little power, you will need to use the processors sleep modes. These are modes, where special functionality is disabled but which keeps the processor alive or in some idle mode where it's actually just waiting. Whilst the Arduino may have various sleep modes, none of them are what can be achieved with other architectures, such as the MSP430 platform or some SAMxL platform. Those are dedicated as low power processor and provide the necessary deep sleep modes.
When using a deep sleep mode, it depends on the actual sleep mode which interrupts can wake the processor. Typically for the deepest sleep modes, only few interrupt sources will actually wake the processor up as all other peripherals are inactive either because their clock was gated or power was turned off for that function block.
You will always have some power drain for the processor but keep in mind that it's not only the processor which will require power. At some point, you have leakage currents through your capacitors/resistors and other ICs on your board which require power as well. When you're talking about "years", you will also need to account for the battery discharge as well. No battery is perfect.
Jack Ganssle is probably well known for his insight into anything related embedded, but he explicitly wrote some articles for ultra-low-power systems. You must read those if you want to start somewhere. While having the software side covered using low power techniques you will also need to tackle the hardware side, yet as I said - the Arduino wasn't made for such tasks even if it provides some basic sleep modes.

Thats really a great explanation. That means no need to worry about the continuous loop ever there is nothing in the loop? isnt it?

Not exactly. You will need to consider the loop, even if the processor does nothing, it still executes one operation (a NOP operation) all the time and thus requires more power. Only transitioning to a sleep mode will allow for reduced power. The loop itself is a concept to keep the processor in a defined state.

OK.. thats sounds great.. OK I will have a try with that..

Although they may not be as good sleepers as the other MCUs you mentioned, the AVRs can sleep pretty deep. I have one of them running since June 2012 off the same pair of AA cells. And it's awake more than 4 min/day. 2) An empty loop() does perform some CPU operations, but none of them is a nop.

You can refer below links once for understanding sleep concept on Arduino.
1) http://playground.arduino.cc/Learning/ArduinoSleepCode
2) http://www.gammon.com.au/power

You wrote:

I'm a very beginner with electronics [...] the looping system feels
  pretty awkward

I think these two statements are highly correlated. It feels awkward to
you simply because you are not used to it.

So what I understood is Arduino loop always executes based on any
  values from sensors while in the loop.

This sounds like a misunderstanding. The Arduino loop() is a function
you write, and whether its behavior is “based on any values from
sensors” or not is up to you. The main() function provided by the
Arduino core library will just call your loop() repeatedly.

I tried to stop the loop using exit(0);

As explained by Tom L. in his answer, there is nowhere to exit to. In
this kind of embedded system, exit() essentially means “stop doing any
useful work”. On AVR microcontrollers (like in the Nano), exit() is
implemented as an empty infinite loop running with interrupts disabled.

I believe [sleeping] will reduce the load on Arduino and of course
  since no looping it will not get heated at all.

Heat? What heat? The CPU core of the Arduino does not generate heat. Not
at any significant level. Think about this: it's clocked at 16 MHz.
Yes, those are megahertz: snail pace! The MCU can get hot if you
have it source or sink too much current, but this is completely
unrelated to CPU load.

I am trying to build an external simple interrupt hardware system
  [...] which interrupts Arduino in a specified interval, say 20 sec.

Since you come from the software world, you probably know about
“premature optimization”: this is exactly what you are doing here. I
recommend you stop right now. Do not build into your system complexity
that may not be useful. Instead, start simple: read the Blink without
delay[] Arduino tutorial, and apply this technique to solve your
problem. In a nutshell, you will put, inside your loop(), something
like:
if (millis() - previousMillis >= JOB_PERIOD) {
    do_the_job();
    previousMillis += JOB_PERIOD;
}

Note that the tutorial I mentioned would instead do something like
previousMillis = millis();, which is fine if you want to ensure that
JOB_PERIOD is the minimum time between the jobs. The code above,
instead, assumes you want to enforce an average period.
Once you have this working, test it, and see whether you do need to
optimize it. There are two aspects that could be optimized: current
consumption and period accuracy. Either may be useful for your
particular application. Or none. Or both. It all depends on your
specific requirements.
Current consumption
There is a low hanging fruit here. You can put the CPU to sleep on every
loop iteration, simply by calling sleep_mode():
#include <avr/sleep.h>

const uint32_t JOB_PERIOD = 20000;  // 20 seconds

void do_the_job()
{
    // The stuff you have to do every 20 seconds.
}

void loop()
{
    static uint32_t previousMillis;
    if (millis() - previousMillis >= JOB_PERIOD) {
        do_the_job();
        previousMillis += JOB_PERIOD;
    }
    sleep_mode();
}

The Arduino core library has a timer interrupt triggered every
1024 µs. This is the interrupt responsible of updating the variable
that millis() returns, and it will wake you up. With the code above,
the Arduino will be awake for only a few CPU cycles per iteration
(update millis(), subtract, compare) and spend most of its time
sleeping. In the default sleep mode, only the CPU does sleep. But it is
also the only mode in which the timer does not sleep, and is thus the
appropriate mode here.
The trick above should suppress most of the power consumption of the
CPU. If it's still consuming too much for your liking (i.e. if you want
your Nano to run for years on a couple of AA cells), you should know
there are ways to push the microcontroller into the ultra-low power
realm. But it is not so simple, and you will have to tune not only the
software, but also the hardware. Your journey into microamp hunting
should start by reading Power saving techniques for
microprocessors, by Nick Gammon. The link has already been
mentioned in Chirag Patel's answer.
Period accuracy
The Arduino Nano being clocked from a ceramic resonator, you should
expect its timing accuracy to be pretty poor. The standard solution for
when you need accurate timings is to use an RTC. You could query the RTC
periodically to ask for the current time or, better yet, you can choose
an RTC with “alarm” capability. This is not unlike an alarm clock: you
program it to send you an interrupt signal at a time of your choosing.
Read the manual of your RTC for details.


text:
I2C communication between Arduino Due and Nano
I'm trying to communicate between two Arduino Due and Nano. Nano as Master and Due as a slave. As given in the library description Wire Lib
When the master request for data from the slave, first it goes to Request ISR. Wire.onRequest(requestEvent)    But when compile the program for Arduino Due I get following errors.
In file included from C:\Users\\Slave_Test3.ino:14:0:

C:\Users\..\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\libraries\Wire\src/Wire.h:59:7: error:   initializing argument 1 of 'void TwoWire::onRequest(void (*)())' [-fpermissive]

 void onRequest(void(*)(void));

       ^

But If I change from Arduino Due to any other board this error does not come.
Thank you

It looks like a problem with the Wire lib that the Due BSP includes.

Dead easy !!
(Well only because I had a -fpermissive yesterday :) )
You are trying to implicitly cast, and you can't do that with modern GCC versions (quite rightly).
So you need to explicitly cast the first parameter to void*.
Because this is in a "core" library for the Due I would get the latest version of the board package and see if it goes away.  You can turn the check off, but you will need to google on how to do that.

Thank you for the solution. Yes, I have the latest version of the board package. Still, I'm getting those errors. Can please elaborate your last suggestion I am new to this.

Not really because I can't see the code that has the problem.

I have written the same come as given here .

That link won't help.  This "error" is not in your code, its in Wire.h as per your original post


text:
Built-in capacitive touch detection with SAMD21 development board (Arduino Zero Compatible)
I bought this SAMD21 development board which shows up as an "Arduino/Genuino Zero (Native USB Port)" when plugged in. And I've successfully got a blink sketch running on it all good so far:

The reason I picked up this board was to experiment with the built-in capacitive touch sensor on the SAMD21. In the datasheet for this chip it claims to support a 'Peripheral Touch Controller with 256-Channel capacitive touch and proximity sensing'.
Does anyone know what this exactly means and how I would access this functionality to detect touches in my Arduino code? Obviously there are not 256 IO pins so how would this work? Is there some kind of internal multiplexer?
The 256 channel capacitive touch controller is also mentioned in a Sparkfun video about their SAMD21 board, so it must be possible to access this functionality.
Can someone direct me towards an Arduino library or method and more information on the wiring and pin connections for this. Thanks.

15 dollars at AliExpress. It is the same processor as in the Arduino Zero and Arduino M0. As far as I know there is a small difference for the pins between the Zero and the M0. You can find the complete datasheet here: http://www.microchip.com/wwwproducts/en/ATsamd21g18 The pins can be used in a matrix. For using it, they point to the Atmel QTouch library. Someone at Arduino has done a good job by mentioning the PTC pins in the table: https://github.com/arduino/ArduinoCore-samd/blob/master/variants/arduino_zero/variant.cpp So far I can only find this: https://github.com/jgilbert20/Libre_PTC

Thanks for pointing me towards this Libre_PTC library, it looks very promising. I really hope Jeremy continues work on this and adds support for SAMD21 soon.

You have three options for the silicon-based PTC (peripheral touch controlller).

LibrePTC - My own library that targets the SAMD11 but should work with some modifications for other SAMD architectures. The README file has lot of information on how the PTC works and how to specify designs for it.
Adafruit FreeTouch - Works only with the SAMD21. Given the high quality of the register documentation, I suspect they may have had inside help from Atmel but I haven't been able to reach Ladyada, their primary contributor, to learn more.
QTouch, which is Atmel's library available in closed source only but is extremely feature-rich. Arduino team decided not to allow closed source stuff in their IDE so its been banned from official distributions. However, it is possible to hack it into the Arduino IDE and I've used it successfully that way. However this requires esoteric modification to boards.txt that are beyond the scope of this answer.

The PTC hardware peripheral on the SAMD chips works on self-capacitance using "Y" lines specified in the data sheet. See the README on LibrePTC for details. Some chip variants have more pins broken out. For instance, the SAMD21G has fewer available Y pins than the SAMD21J, although the J series is not as readily available in breakout boards as of the summer of 2017 and it has limited Arduino IDE support. I personally prefer the SAMD11 because it is cheaper ($1.00) and has way more available Y lines in the QFN package.
As of August 2017, I intend to attempt a merge between the Adafruit and LibrePTC libraries but no guarantees when this will happen. I don't have access to insider documentation so my library was 100% reverse engineered through trial and error.

Great. Thanks Jeremy. I’ll start with trying out that Adafruit FreeTouch library, I did’t know Ladyada had written something like this. Then I’ll search for an affordable SAMD11 development board to order and then I'll play around with your library beginning with the SAMD11 and then the SAMD21. And I also really look forward to seeing your updates after merging your’s and the Adafruit libraries.

Will do. The AF library does not work out of the box. For anyone following this, you will need to install the Adafruit_ASFCore library too or use my fork here: https://github.com/jgilbert20/Adafruit_FreeTouch

I had a play with your Adafruit_FreeTouch branch on the SAMD21… It’s doing something when I touch an input so that’s a good thing, but it doesn't seem right. Maybe you could advise me in setting it up, I’m getting very noisy readings with the example code.

Seems to be easy to include the qtouch library now a days... https://github.com/arduino-libraries/Arduino_MCHPTouch


text:
RFM95 LoRa module frequency options
I live in India, and unfortunately here the unlicensed band ranges only from 865MHz to 867M Hz. The IBM LoRa code for Arduino (as node) for RFM95 module allow you to choose between 915 Mhz and 868 Mhz only. I initially created a gateway using a Pi3 listening at 865.7 (to conform with Indian rules), but it couldn't receive any payloads from my node running at 868 Mhz. Then, eventually, I tried again with my gateway listening at 868 Mhz, and it worked like a charm. No hiccups.
But, obviously, it seems to be against the rules, and I don't fancy prison. So I want to know if I can get the RFM95 module working somewhere in the range of 865 Mhz to 867 Mhz? And if yes, how can I do it? There certainly doesn't seem to be an option to choose a frequency other than 868 Mhz or 915 Mhz in the IBM Lora code. Here is the link to the code library. https://github.com/matthijskooijman/arduino-lmic

Are you sure that limitation also applies for such low powered radios and home appliances?

The various LoRa projects I've come across online make an effort to conform with their respective nationalities' frequency regulations. Hence, the question.

The RF networks of the RFM95 board are ideally configured for the general range of frequencies, but the difference between your 865.7 MHz and the 868 MHz tuning of a European (vs US) version of the board is likely smaller than the error with which the RF networks can be tuned to begin with, so that is unlikely to be a problem unless there is some hard lockout of your desired frequency in the SX1272 chip.  I've even heard claims that some people have managed to at least somehwat use US vs European tuned versions on the opposite bands, which is far more drastic than what you are trying to accomplish.
So assuming there is no hard lockout of your desired frequencies in the hardware, basically what you will need to do is to change the frequency list in the source of the software you are using to operate the module.
Basically you would edit src/lmic/lorabase.h and make a modified version of the EU configuration.  Ideally you'd add that as an additional option and select it, but for an initial test you could just edit the European version to fit your needs.
Do keep in mind the code will probably want to use multiple frequencies - if you have a gateway that receives only on a single frequency, you'll need to modify the code to always use that, after determining if doing so fits with usage-rate rules in your jurisdiction.
It's probably worth doing some online research to see if anyone has already put thoughts into operating LoRa in India - if so, there may already be a modified branch of the LMiC code you can use.

Unfortunately there isn't much LoRa stuff going on here. 5 TTN gateways in total in India. Speaks for itself.

5 Things Network gateways is a non-zero number, and a sufficient number for you to determine what frequencies they are using if you can find an email address, post or other information for one of their owners.  For that matter, you'd probably be better off asking in a global Things Network forum than asking here, since your question is really about the radios and the LMiC code, not Arduino.