text:
Multiple HC-SR04 with one 5v 7805 regulator
I am working on a autonomous track vehicle. I have mounted
3 HC-SR04 sensors
1 Sharp infrared distance sensor
3 infrared led distance sensors
1 Arduino Mega 2560
1 H-bridge Board HG7881
I am trying to use 7.5 v 1700 mAh Nicd battery (also tried 11.1 Lipo 2200 mAh)
For all sensors power (5v) I developed 5v regulator using 7805 which is connected directly from battery as input. The output 5v is going to power distribution board (used from quadcopter extra board) which provides 5v to every sensor.
The real problem starts here when I am not getting correct or nothing in reading from Ultrasonic sensors and my vehicle starts behaving abnormal. I checked that sensor reading is either 0 or wrong. I used both simple and with NewPing library.
I checked when using 7.2v battery the output from 5v regulator is 3.72v.
Now my question is if the power is below 5v, does sensors starts behaving like this? How can we supply voltage so every sensor will receive full 5v to work properly?
My vehicle will not work until sensors provide correct distance reading. I worked successfully with one sensor but with number of these, tired working since many days.

The sensors are 5V so yes, very likely they will behave erratic at 3.7v. Have you measured the current draw from the battery while everything is running? Do you have input/output capacitors? Any thin/long wire being used? All connections are ok? Does any part gets hot? Not a problem but a switching regulator might be more efficient.

What's the voltage into the regulator?

How is the Arduino wired into the sensor schematic?

@Talk2, yes 5v sensors, should I check drawing current from battery by multi-meter just touching +v -v?, yes several thin but strong long wires being used. Yes checked connections to every sensor by multi-meter. Nothing hot just my mind :).

@Dave X, on 7.2v battery, 3.7v. On 11.1 battery it is 5v.

@Majenko, this is not the first time I am using these sensors, this is my third similar project but first time with all so many sensors. I connected ultra sonic on analog pins then tried to change to digital pin but same result. I also replaced one of sensor with brand new and new wires.

quazifarhan  It does not make sense to have 3.7V into the regulator and 3.72 out of the regulator.    Also, regarding your answer to @Talk2 --you measure current by putting a current meter in-line (in between) with the circuit, not across the V+/V- terminals. Put it between the battery's V+ and the regulator's Vin to see the current pulled out of the battery.  Or between the regulator's Vout and the rest of the circuit to see the current delivered to the circuitry.  Or between the regulator's GND and the circuit GND to see the current wasted by the regulator.

Does the Arduino share the same power source as the sensors?

Majenko, Arduino getting full 7.2 or 11.1 from battery to vin pin and parallel connention from battery to regulator. So Regulator and Arduino both connected directly to battery.

You really could benefit from a DC/DC switching power supply.  For instance you are wasting about 20% of the power of the 7.2V battery and something like 50% of the power of the 11.1V battery.
That said, could it be that you are triggering the 3 ultrasonic HC-SR04 too closely together?  If you don't wait for the sound to die out from the 1st sensor the 2nd sensor could give unexpected results.  Same goes for the 3rd sensor.

Is this an answer to the question Now my question is if the power is below 5v, does sensors starts behaving like this? How can we supply voltage so every sensor will receive full 5v to work properly?

No.  But it appears that the author was having difficulties phrasing the question.  And that the actual goal was a working "autonomous track vehicle".  In the end I believe this question suffers from the XY Problem.

Your 7805 regulator isn't working, it should have a output of 5v, 3.72v is way off. 2-4% diff from 5V is the normal specification. https://www.fairchildsemi.com/datasheets/LM/LM7805.pdf
Vin should be between 7-20volt even if the datasheet indicate that you can have as low as 5volt in.
Causes could be:

Wrong design
Low battery voltage
Faulty component
Faulty connection


text:
Posting to EEPROM via HTML - ESP8266 Arduino IDE
For those of you familiar with my somewhat steep EEPROM learning curve...thank you for continuing to share your knowledge.  I see how it's supposed to work and it's falling into place.
I've run into a new problem and I've spent two nights (~15hrs of Googling/trial and error...mostly error) trying to understand where I'm going wrong.
Below is a chunk of code that take user inputs from a webpage and saves it to EEPROM.  It works as intended when only SSID and PASS fields are provided on the form.  I added an "owner" field to add my name to the EEPROM (because why not?) and now the PASS field is ignored and the OWNER information is saved to the PASS and OWNER EEPROM locations.
I think it has something to do with the string.indexof("&") and repeated string.lastindexof("=") but I'm still wrapping my head around what these actually do.  If I understand it correctly, the second string.lastindexof("=") is actually overwriting the PASS which was saved milliseconds earlier.  If this is correct, how do I prevent this?  If I'm wrong, why?
  s += "<form method='get' action='a'>SSID: <input name='ssid' length=32>
PASS: <input name='pass' length=64>
OWNER: <input name='owner' length=32>

<input type='submit'></form>";
  s += "\r\n\r\n\r\n";
  Serial.println("Sending 200");
}
else if ( req.startsWith("/a?ssid=") ) {
  Serial.println("clearing eeprom");
  for (int i = 0; i < 128; ++i) {
    EEPROM.write(i, 0);
  }
  String qsid;
  qsid = req.substring(8, req.indexOf('&'));
  Serial.println(qsid);
  Serial.println("");
  String qpass;
  qpass = req.substring(req.lastIndexOf('=') + 1);
  Serial.println(qpass);
  Serial.println("");
  String owner;
  owner = req.substring(req.lastIndexOf('=') + 1);
  Serial.println(owner);
  Serial.println("");

  Serial.println("writing eeprom ssid:");
  for (int i = 0; i < qsid.length(); ++i)
  {
    EEPROM.write(i, qsid[i]);
    Serial.print("Wrote: ");
    Serial.println(qsid[i]);
  }
  Serial.println("writing eeprom pass:");
  for (int i = 0; i < qpass.length(); ++i)
  {
    EEPROM.write(32 + i, qpass[i]);
    Serial.print("Wrote: ");
    Serial.println(qpass[i]);
  }
  Serial.println("writing eeprom owner:");
  for (int i = 0; i < owner.length(); ++i)
  {
    EEPROM.write(96 + i, owner[i]);
    Serial.print("Wrote: ");
    Serial.println(owner[i]);
  }
  EEPROM.commit();

To summarize, my questions are:
-what is causing the code to skip over my PASS field and save a duplicate of OWNER into both PASS and OWNER?
-is one \r\n pair required for every field on the html form?  If I used 100 fields would I need 100 * \r\n pairs after  tag?
If you're interested in seeing the whole shebang, chriscook8 has graciously posted the Access Point sketch for the ESP8266 here (~250 lines).  There is also a very helpful discussion about this sketch here.

Edit: 3 July 2016
I've amended the code:
s += "<form method='get' action='a'>SSID: <input name='ssid' length=32>
PASS: <input name='pass' length=64>
OWNER: <input name='owner' length=32>

<input type='submit'></form>";
s += "\r\n\r\n\r\n";
Serial.println("Sending 200");
}
    else if ( req.startsWith("/a?ssid=") ) {
      Serial.println("clearing eeprom");
      for (int i = 0; i < 128; ++i) {
        EEPROM.write(i, 0);
      }
      String qsid = server.arg("ssid");
      String qpass = server.arg("pass");
      String owner = server.arg("owner");
    }
    Serial.println("writing eeprom ssid:");
    for (int i = 0; i < qsid.length(); ++i)
    {
      EEPROM.write(i, qsid[i]);
      Serial.print("Wrote: ");
      Serial.println(qsid[i]);
    }
    Serial.println("writing eeprom pass:");
    for (int i = 0; i < qpass.length(); ++i)
    {
      EEPROM.write(32 + i, qpass[i]);
      Serial.print("Wrote: ");
      Serial.println(qpass[i]);
    }
    Serial.println("writing eeprom owner:");
    for (int i = 0; i < owner.length(); ++i)
    {
      EEPROM.write(96 + i, owner[i]);
      Serial.print("Wrote: ");
      Serial.println(owner[i]);
    }
    EEPROM.commit();
    s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\nHello from ESP8266 ";
    s += "Found ";
    s += req;
    s += "
 saved to eeprom... reset to boot into new wifi\r\n\r\n";
  }
  else
  {
    s = "HTTP/1.1 404 Not Found\r\n\r\n";
    Serial.println("Sending 404");
  }
}

I also made the following replacement per your recommendations:
//WiFiServer server(80);
ESP8266WebServer server ( 80 );

...and receive an error on this line:
WiFiClient client = server.available();

'class ESP8266WebServer' has no member named 'available'
I'm sure that there is a simple replacement for this.  Any idea what it might be?
Otherwise, I think I see where you're going with this and it seems much cleaner than I anticipated.
Thank you!

if you're using ESP8266WebServer - it has a function, arg(String name) ... so you'd do something like String ssid = ws.arg("ssid"); to get the ssid parameter from the request - ws in the example is a ESP8266WebServer object

I'll look that up.  Would that replace "String qsid" or "qsid = req.substring(8, req.indexOf('&'))"?

A code snippet for you - will expand later (just got tied up)
ESP8266WebServer server ( 80 );
...

else if ( req.startsWith("/a?ssid=") ) {
  Serial.println("clearing eeprom");
  for (int i = 0; i < 128; ++i) {
    EEPROM.write(i, 0);
  }
  String qsid = server.arg("ssid");
  String qpass = server.arg("pass");;
  String owner = server.arg("owner");

  Serial.println("writing eeprom ssid:");
  ... rest of your code

I will try this tonight.

I amended my OP with the new code and an error I get when I compile.

The best practice with EEPROM is only write it when absolutely necessary. Your clearing of EEPROM will quickly kill it.

source: Stack Exchange

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

sort: votes


text:
Modbus RTU over TCPip
I have developed my arduino code using below library. I tested code working fine over modbus RTU slave. Now i am planning to use RS485 to wifi instead of wire connection. In order to get data over web apllication i need to add another layer of modbus TCP-IP. can some one suggest me is it possible to without changing any hardware add library function which can acts like MODBUS RtU over TCP-IP protocol.
if any library avilable please share it
I am using WIFI device like below.
rs485 to wifi
MODBUS RTU

Modbus TCP simply put is a Modbus packet wrapped in a TCP packet.
There is no 'additional layer of Modbus' added on top. If we look at the osi model pictured below you can see there is only one Modbus application layer (i.e modbus slave/server)

Essentially if the wifi->RS485 gateway strips the payload from the TCP packets and simply spits it out the serial side then no modifications are necessary (apart from the obvious RS485 transceiver you will need to interface the arduino with the gateway).
What you will need to make sure is that the gateway will only send packets directed to port 502 to the arduino (502 is the Modbus TCP port) as it is possible other IP traffic could cause some drama for the modbus slave.
Additionally, you will have to ensure that you set the slave ID of the arduino to be what is specified by the master. Are you also building the Modbus TCP client? If not it is very possible that the required slave ID is 255 which is not supported by the modbus library you have linked.
Modbus (serial) slave IDs can only be between 1 and 247 for traditional reasons when Modbus was first standardised as it was only envisioned to be on serial, however when Modbus TCP was introduced an additional addressing layer (TCP / IP) meant that the unit ID (slave ID when using Modbus TCP) could be anything from 0 - 255. It is common for some vendors (at least in industrial automation) to use a unit ID of 255 for standard Modbus transactions scanning IO and diagnostic or configuration transactions to be send to other unit IDs (essentially making the TCP server a modbus router, forwarding packets to one of the multiple Modbus servers running on that single slave device)

I am not having plan to develop any modbus TCP ip protocol or make any hardware changes. I would like to know with existing library how can i convert the modbus packets into tcp-ip packets to make work as modbus RTU over TCP IP. There is library for modbus TCPIP can use to implement my code

A mentioned in my post whether or not the mobus library you linked will work depends on the master/client and what unit id it will be polling. Do you what this will be? What is the master/client? Do you have any control over it?

the device going to be client.Scada system acts like Master. Intially we used wired connections and now we wanted to go with wireless without changing hardware. By USR model , USR-630 we can config either server or client.we just passing data like modbus packets. I found its working fine with modbus packets. We expected to wifi device convert modbus packets into TCP-IP packets. Since it not doing it , how we can convert into TCP-ip packets

I suspect you mean the arduino device is going to be server/slave? If you want to change from wired to wireless you must change hardware , seeing how that is what you want to do. As I have said before you need to make sure the client I.e your scada can use a unit id in the Renee of 1-247. What is a USR630? What do you mean exactly by "we expected wifi device to convert modbus packets into tcp ip packets" this does not describe your problem at all.

I am using connection from A and B connection from Existing arduino Slave device and connected to rs485 to wifi.  we can config device ID up to 248 device. with device i could able to communicate like wired connection but i could not able to connection in scada over web app. our scada engineer asking  to give protocol that convert MODBUS packets into TCP-IP packets. Thats reason i am looking for expert suggestions here

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


text:
use more then one timer
I'm working on Arduino uno and trying to use more then one timer.
I'm using timer1 for my software watchdog (I needed bigger interval for that, so my program won't reset itself after 8 seconds).
In addition, I'm using timer2 for regular interrupt like turn off pin after 8 seconds.
The problem is that the timer1's interrupt override timer2's interrupt.
Is it possible to to use both of them?

No, timer1's interrupts do not override timer2's interrupts.

Why are you using a timer for the watchdog instead of the normal watchdog timer in interrupt-and-reset mode?

Could you post some code, so we could see why the timer1 interrupt might override the timer2 interrupt?

In general, once an embedded processor's interrupt fires, the interrupt routine clears the interrupt.  Usually inside the interrupt routine.  Failure to clear the interrupt normally inhibits further interrupts.
That said, in the Arduino paradigm, this is "taken care of" by the Arduino Timer library described here.  In the example code:
/*
 *  Timer1 library example
 *  June 2008 | jesse dot tane at gmail dot com
 */

#include "TimerOne.h"

void setup()
{
  pinMode(10, OUTPUT);
  Timer1.initialize(500000);         // initialize timer1, and set a 1/2 second period
  Timer1.pwm(9, 512);                // setup pwm on pin 9, 50% duty cycle
  Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
}

void callback()
{
  digitalWrite(10, digitalRead(10) ^ 1);
}

void loop()
{
  // your program here...
}

...you can see that the example does not actually contain "the" Timer interrupt routine but rather a callback() routine which the Timer library calls when the Timer interrupt occurs.  Code to clear the Timer interrupt is missing and assumed to be in the Timer library.
Consider this if you are writing you own interrupt routine instead of using the Arduino's Timer library.
I'm going to have to call foul on myself.  Clearing interrupts in their own interrupt routine is very common.  But looking at this page, where the Atmel timer hardware is directly controlled (that is, the normal Arduino Timer library is not being used) and the real interrupt handler exists in the sketch, I see where this is not done.  So, for the Atmel, there must be at least one timer mode where the timer interrupt does not have to be clear for the interrupt to happen again.
If you are using the Arduino's Timer library consider this warning from the Timer's library web page linked to above:

Be careful about trying to execute too complicated of an interrupt at
  too high of a frequency, or the CPU may never enter the main loop and
  your program will 'lock up'.

Finally, hardware timed interrupts are normally reserved for operations which are time sensitive and occur much faster than executing code can handle.  For events that happen on the order of seconds, most applications setup 1 timed interrupt to count off a convenient interval.  Say 1 second.  Code is used to keep count and call the proper functions at the intended time.

On the AVR microcontrollers (and the Uno is AVR-based) most interrupt flags are cleared by the hardware when it executes the corresponding interrupt vector. This is the case for all the interrupts generated by the timers in all of their modes.

@Edgar Bonet, thanks.  That does appear to go against what other embedded processor makers do.  At least that's been my experience.  So not clearing the interrupt is not Rotem problem.  Maybe he is doing too much in the interrupt.  But at 8 seconds intervals, I doubt it.  So it looks like we need Rotem to show us his code if we are to help.

@IgnacioVazquez-Abrams: What architecture are you talking about? On the AVR, for most interrupt flags, the datasheet states (emphasis mine): “[The interrupt flag] is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, [the interrupt flag] is cleared by writing a logic one to the flag.” Note that the “vector” is the jmp to the ISR located in the interrupt vector table, thus it is executed before the ISR proper.


text:
Power arduino from 5v rail of pc molex
I'm building a small device using arduino that should be connected to my pc via a usb header to exchange data with the PC.
What I'd like to achieve is that arduino turns on when the pc is on, whereas it shuts down when the pc is turned off. If I rely on the usb port to provide power to the arduino that might not happen, since some motherboards still provide power to the usb connections even when the pc is off.
Therefore I'd like to power the arduino using the 5v rail directly from a Molex. I know that theoretically I can connect that rail straight to the 5v pin, but what about power spikes? How can I be sure that the 5v input voltage is properly filtered and stabilized? Would it be better to use a LM317 and transform the 12v rail into 7.5v to feed arduino from the vin?

The Arduino will be fine with the 5V rail as long as you don't have a garbage-of-the-garbage PSU. After all, the rest of the computer is much more sensitive than the Arduino.

Yes, I think that as well, but just to be sure what kind of filter could I build to prevent possible (even if unlikely to happen) spikes?

The 5V on the USB port, is coming from the same power supply as the 5V from the molex. You could also switch to e.g. an Arduino Leonardo, which would be able to detect whether the PC is actually on.

So you're saying that if the USB is powered when the pc is off then so is the molex 5v rail? What about the 12v then? I might be able to regulate it down to like 7.5v with a lm317 and then feed it to the vin pin... Changing the board is not a viable option for me in this case.

FYI only the DC Power port (12v) and USB (5v) are regulated, vin is not. 3v and 5v pins are only for output.

The 5v of an ATX power supply will be perfectly adequate for powering an Arduino.
It will already be very heavily filtered and stabilised.

Now @Gerben made me think that maybe the 5v rail is still powered on when the pc is off. If so, then will a regulated 12v rail work? What do you think?
ps. I need 15 rep here to upvote you, so if you upvote the question that might help :)

An ATX supply has a 5v standby rail that is always on which is used to control the computer's power circuitry. The main 5v rail will be off. The only time I have seen a computer's USB providing power when turned off has been when an external powered hub is back feeding power into the port.

Some motherboards do have the option of providing standby power to USB for wake-up purposes, but that usually has to be explicitly enabled by the user.


text:
How to call class A's method from class B?
I wish to access methods and fields, as well as change them, of class A from class B. Since the main Arduino sketch is not a class, but a list of fields and methods, I created a separate MainClass with a method printStuff() that I want to call from class DoClass. This is how I go about it:
The main sketch:
#include "MainClass.h"
MainClass m;
void setup() {
  m.setup();
}
void loop() {
  m.loop();
}

MainClass.h:
/*
  MainClass.h
*/
#ifndef MainClass_h
#define MainClass_h
#include "Arduino.h"
class MainClass
{
  public:
    MainClass();
    void setup();
    void loop();
    void printStuff();
};
#endif

MainClass.cpp:
/*
  MainClass.cpp
*/

#include "Arduino.h"
#include "MainClass.h"
#include "DoClass.h"
MainClass::MainClass()
{
  d DoClass(this);
}
void MainClass::setup(){
  Serial.begin(9600);
}
void MainClass::loop(){
  d.callMainClassFunct();
}
void MainClass::printStuff(){
  Serial.println("printing stuff");
}

DoClass.h:
/*
  DoClass.h
*/
#ifndef DoClass_h
#define DoClass_h

#include "Arduino.h"
#include "MainClass.h"
class DoClass
{
  public:
    DoClass(MainClass m);
    void callMainClassFunct();
  private:
    MainClass _m;
};
#endif

DoClass.cpp:
/*
  DoClass.cpp
*/

#include "Arduino.h"
#include "MainClass.h"
#include "DoClass.h"

DoClass::DoClass(MainClass m)
{
  _m = m;
}

void DoClass::callMainClassFunct(){
  _m.printStuff();
}

This produces a myriad of errors. Each time I change something, a new kind of error appears, as though I was in a vicious cycle. Clearly, I am unfamiliar with C++. It would greatly help me if you could alter my code so that it works, keeping in mind that I would like to both access methods and fields of class MainClass from class DoClass and change those fields from class DoClass.
For reference, in Java, I would achieve the same in the following way:
MainClass.java:
public class MainClass{
    DoClass d;

    public MainClass(){
        d = new DoClass(this);
}

    public void setup(){

}

public void loop(){
    d.callMainClassFunct();
}

public void printStuff(){
    Serial.println("print stuff");
}

}

DoClass.java:
public class DoClass{
       MainClass _m;
       public DoClass(MainClass m){
          _m = m;
       }
       public callMainClassFunct(){
         _m.printStuff();
}

}

Passing this to the constructor od DoClass passes the value of the reference pointing to MainClass instantitated in the main sketch file. Then, by prepending the name of the instantiated object (in this case, "m"), followed by a dot, I can simply access and change all values of that object from DoClass (provided those methods and fields are visible to DoClass, which is the case here).
I have posted before about this issue, but did not receive any answers to my specific question and could not comment because I do not have enough reputation. Thank you to those who tried to answer me, but the answers did not pertain to my specific question. This time I have included more information to show my problem more clearly. Thank you in advance for your help.

Why are you putting the whole sketch inside a class? This is like shoehorning a Java paradigm into C++. Why don't you ask about the actual problem you want to solve, instead of asking for help in following your misguided attempt at transforming C++ into Java?

I am trying to create a program, which performs various tasks. Each class executes a task: in loop(), I call task1.loop(), task2.loop() etc. depending on the state of the program. Those classes need to respond to the main sketch to update the state of the program based on their completion. I haven't found a way to reference any fields or methods from the main sketch, so I created a MainClass, which would then be passed to those tasks to create aliases and access MainClass. The example that I gave is just a proof of concept - to see if I can reuse a very handy schematic from past Java projects.

In your Java version, you define MainClass like this (my comments added):
public class MainClass{ // Define a new Class
    DoClass d;          // Add a member variable to the class
    public MainClass(){
        d = new DoClass(this); // Initialise the member variable
    } // MainClass()
} // MainClass

In your C++ you don't do the same thing - but you should! The class needs a DoClass member so that you can use it in other MainClass functions:
// MainClass.h
...
#include "DoClass.h" // Need the .h here - remove it from the .cpp
class MainClass
{
  public:
    MainClass();
    void setup();
    void loop();
    void printStuff();
  private:
    DoClass _d; // Create a private member variable to use
};

and
// MainClass.cpp
MainClass::MainClass() : // MainClass constructor (note colon)
           _d(*this) // Initialise member
{
} // MainClass::MainClass()

Now, you want DoClass to be able to use MainClass, so you passed it into DoClass's constructor. But DoClass cannot have a MainClass inside it - MainClass already has a DoClass inside it! Infinite impossibility! So you need DoClass to merely contain a reference to the MainClass that it sits inside. That's the C++ unary & operator (different from the binary & operator), which is used similar to the pointer * operator:
// DoClass.h
...
// Need to advise compiler MainClass exists...
// but can't #include MainClass.h! Infinite loop!
class MainClass;

class DoClass
{
public:
    DoClass(MainClass &m); // Reference to MainClass
    void callMainClassFunct();
private:
    MainClass &_m; // Reference to MainClass
};

and
// DoClass.cpp
DoClass::DoClass(MainClass &m) : // DoClass constructor - note colon
         _m(m) // Initialise member variable
{
}


text:
How to send Serial.Print only If Serial Connection is open?
So I looked through the Arduino Mega2560 documentation and searched the web for a solution, and so far I haven't had any success.
What I'm trying to accomplish is fairly simple. I need to send a serial command over serial, ONLY if there is a serial connection between the PC and the Arduino. I've tried:
If(Serial){
   Serial.Println("COMMAND");
}

That doesn't work, and I think it's because the Arduino cannot distinguish between listening to the Serial port versus establishing a Serial connection.
Any help would be appreciated.
Cheers!

The Arduino Mega's "serial" connection comes from an external chip implementing USB-serial conversion.  While this chip knows if a session is open with a host, the standard design has no way to share that information with the main ATmega.
In contrast, on a Leonardo type board the main processor implements the USB interface, so it does know.
Your options include changing the requirement, having the PC program send some data to the Arduino, changing the processor to an ATmega or ARM with integrated USB, or perhaps modifying the USB implementation.

Thank you for the clarification. I'll have to go with 'having the PC program send some data to the Arduino'.


text:
Problems returning char array from function, value gets messed up
I use the Base64 library for Arduino (but I don't think the problem is related to the library) and have the following function definition:
char* decodeImage(char inputString[], unsigned int inputStringLength) {
  int decodedLength = Base64.decodedLength(inputString, inputStringLength);
  char decodedString[decodedLength];
  Base64.decode(decodedString, inputString, inputStringLength);
  Serial.printf("%s",decodedString); // prints "Base64DecodeExample"
  return decodedString;
}

Later on, I use the following snippet to access the function:
  char inputString[] = "QmFzZTY0RGVjb2RlRXhhbXBsZQA=";
  char* output = decodeImage(inputString, sizeof(inputString));
  Serial.printf("%s",output); // prints garbage

The problem is, that the result of the decoding INSIDE the function seems to be correct, but when I return the value to the calling code, the value get garbled somehow.
I suppose this has something to do with pointer magic or "decaying" of references. Has someone a suggestion?

Your variable decodedString[] is created inside the function, used inside the function - and destroyed inside the function before it returns.
See how your function decodeImage() returns a char *? That's a pointer to a character array, not the whole array - and you can't return a whole array. The pointer is successfully returned all right - but what it is pointing to is overwritten by future calls and future created variables.
This is the perennial problem of C programmers: how to return something created inside the function. You have four choices (each with their own problems):

You can make the variable global - put it outside the function and let anyone access it. Then you don't even need to return the string - it's already accessible.
You can make decodedString a permanent part of the function by making it static:
static char decodedString[64];

Note that the above two solutions have the same two problems:
  a. There is only one array. That means that if the same function is called again, it will overwrite the results from last time - use it before you lose it!
  b. You can't calculate the length and then use it - it has to be created at the maximum possible size.

You can make the caller pass in the array to fill. Rather than return the array, have another parameter that is the array to fill - and for safety's sake, get them to pass in the size of the array too. You'll have to check that and return an error if it's not big enough - or do something else sensible.
You can allocate the memory from a different area that where it's currently being allocated from. That area is called the "heap" - it's just a heap o' memory that you can request chunks from - and don't forget to give it back!

To request memory from the heap, you call the function malloc and pass in the number of bytes that you want. It returns a pointer to that lump of memory:
char *decodedString = (char *)malloc(decodedLength);

Note that malloc doesn't know what you're going to use the memory for, so you have to tell the compiler - that's what the (char *) before the call to malloc does.
But if you use malloc, at some stage you must give the memory back with a call to free:
free(returnedString);

The function that did the malloc doesn't have to be the function that frees it - any function can, as long as some function does! Otherwise you'll run out of heap.
Another thing that you must NOT do is call free on the same block twice: that will corrupt the heap, since it will mark the same block on the heap twice, and hand it back out twice later, corrupting the data when it is used again.
EDIT
There's a C++ version of malloc / free called new / delete. You use them similarly:
char *decodedString = new char[decodedLength];
...
// And later...
delete [] returnedString;

It looks and behaves similarly to malloc and free, without the ugly (char *) type-cast. Note that since an array was allocated with the new, you need to call the array version of delete by adding the [] as shown.

+1 for option 3. It avoids the bugs of global and disorderly access in option 1; the risks of over-writing of option 2; and the memory fragmentation of option 4. If the caller needs a larger return value than a single value, it provides the memory space for it. Of course if the caller isn't the end-user of the return, but has to return to its caller, the same conditions apply: caller's caller provides the memory, and so on up to the final consumer. Then it up to that consumer function('s author) how to allocate the memory buffer, but that is the one and only place that choice should be made.

... Coming to embedded systems from other environments, one will have seen all manner of "solutions" to doing this, including returning a local buffer and having gotten away with it (before the system ships!). An embedded system is expected to be able to run 24/7. "Fatal error: out of memory!" is not a option. Neither is stopping or any of the host of failures due to corrupted data. It has to "just work", and option 3 is the least likely to break.


text:
Arduino oscilloscope
I have been working on a recent project to build an Arduino Oscilloscope interfaced with a 4X4 keypad membrane with Nokia 5110 LCD display.I have successful individual code fragments/portions which
1)Generate waves interfaced with the keyboard
2)Display the same on the Nokia LCD 5110
i am using the Arduino Due and the 1st part of my code generates waves on DAC1 with the code as follows:-
#include "Waveforms.h"
#include <Keypad.h>
#include <LiquidCrystal.h>

//Set the desired duty cycle in percentage

double dc,t,a,d;
long d_milli,d_micro,a_milli,a_micro,m,n;
int stage =0;

int sample_delay1;
LiquidCrystal lcd(A2, A3, A4, A5, A6, A7);
float sample_delay;
String num1,num2;
int wave1;
String wave_name;
double duty_cycle,k;
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the cymbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'.','0','#','D'}
};
byte rowPins[ROWS] = {23,25,27,29}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {31,33,35,37}; //connect to the column pinouts of the keypad
int i = 0;
int sample;
//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
boolean in_setup = true;
void setup()
{
  Serial.begin(9600);
  analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
  analogReadResolution(12);
  lcd.begin(20,4);
  char key = customKeypad.getKey();
  lcd.setCursor(0, 0);
  lcd.print("choose wave: ");
  lcd.setCursor(0, 1);
  lcd.print("A=Sine");
  lcd.setCursor(8, 1);
  lcd.print("B=Triangular");
  lcd.setCursor(0, 2);
  lcd.print("C=Sawtooth");
  lcd.setCursor(11, 2);
  lcd.print("D=Square");

  while( true)
  {
        char key = customKeypad.getKey();
        if(stage == 0)
        {
              Serial.println("in stage 0");
              if(key == 'A' )
              {
                wave1 = 0;
                lcd.clear();
                lcd.setCursor(0,0);
                lcd.print(" Sine?      ");
                wave_name ="Sinusoidal";
                Serial.println(wave_name);

              }
              else if(key == 'B')
              {
                wave1 = 1;
                lcd.clear();
                lcd.setCursor(0,0);
                lcd.print("Triangular?");
                wave_name ="Triangular";
                Serial.println(wave_name);
              }
              else if(key == 'C')
              {
                wave1 = 2;
                lcd.clear();
                lcd.setCursor(0,0);
                lcd.print("Sawtooth?  ");
                wave_name ="Sawtooth";
                Serial.println(wave_name);
              }
              else if(key == 'D')
              {
                wave1 = 3;
                lcd.clear();
                lcd.setCursor(0,0);
                lcd.print("Square?    ");
                wave_name ="Square";
                Serial.println(wave_name);

              }
              else if(key == '#')
              {
                stage++;
                //lcd.clear();
                lcd.setCursor(0,1);
                lcd.print("Frequency=");
                Serial.println("Frequency=");
              }
        }
       else if(stage == 1)
        {
              if(key != NO_KEY &&(key=='1'||key=='2'||key=='3'||key=='4'||key=='5'||key=='6'||key=='7'||key=='8'||key=='9'||key=='0'))
              {
                num1 = num1 + key;
                //int numLength = num1.length();
                //to adjust one whitespace for operator
                lcd.setCursor(10,1);
                lcd.print(num1);
              }

              else if(key == '#')
              {
                    k = num1.toInt();
                    Serial.print(k);

                          int sample_delay_int = 1000000/(k*120);
                          float sample_delay_float = 1000000/(k*120);
                          float difference= sample_delay_float-sample_delay_int;
                          sample_delay1 = sample_delay_int - 6;
                          if(difference > 0.5)
                          {
                            sample_delay1++;
                          }

                          Serial.println(sample_delay1);
                          lcd.clear();
                          lcd.print(wave_name);
                          lcd.setCursor(0,1);
                          lcd.print("Frequency=");
                          lcd.print(num1);
                          lcd.print(" Hz");
                          break;
                  }
              }
   }
}

void loop()
  {
  analogWrite(DAC1, waveformsTable[wave1][i] );
  i++;
  if(i == maxSamplesNum)  // Reset the counter to repeat the wave
    i = 0;
  else
    delayMicroseconds(sample_delay1);
  }

Next, I input these waves from DAC1 into analog input A0 to display on the LCD with code as below:-
#include <Adafruit_GFX.h>
#include <Adafruit_PCD8544.h>
#include <SPI.h>

#define DISPLAY_WIDTH 84
#define DISPLAY_HEIGHT 48

#define ARDUINO_PRECISION 1023.0
Adafruit_PCD8544 display = Adafruit_PCD8544(8,9,10,12,11);

//Analog Pins
int channelAI = A0;      // probe

#define DELAY_POTENTIMETER //disabled it I don't have it connected
#ifdef DELAY_POTENTIMETER
int delayAI = A1;       // delay potentiometer
#endif

float delayVariable = 0;
float scale = 0;
int xCounter = 0;
int yPosition = 0;
int readings[DISPLAY_WIDTH+1];
int counter = 0;

unsigned long drawtime = 0;
unsigned long lastdraw = 0;
int frames = 0;

void setup(void)
{
  display.begin();
  display.setContrast(30);// you might have a slightly different display so it might not be the optimal value for you
  display.clearDisplay();
}

void loop()
{
  #ifdef DELAY_POTENTIMETER
  delayVariable = analogRead(delayAI);
  delayVariable = (delayVariable/100);
  #endif
  scale = (float)(DISPLAY_HEIGHT-1)/ARDUINO_PRECISION;

  //record readings
  for(xCounter = 0; xCounter <= DISPLAY_WIDTH; xCounter++)
  {
    yPosition = analogRead(channelAI);
    readings[xCounter] = (yPosition*scale);
    #ifdef DELAY_POTENTIMETER
    delay (delayVariable);
    #endif
  }

  display.clearDisplay();

  //Draw Voltage Ref Lines
  display.drawLine( 10, 0, 10, DISPLAY_HEIGHT-1, BLACK);
  display.drawLine( 5, (DISPLAY_HEIGHT-1)-(.2 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.2 *ARDUINO_PRECISION * scale), BLACK);
  display.drawLine( 0, (DISPLAY_HEIGHT-1)-(.4 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.4 *ARDUINO_PRECISION * scale), BLACK);
  display.drawLine( 5, (DISPLAY_HEIGHT-1)-(.6 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.6 *ARDUINO_PRECISION * scale), BLACK);
  display.drawLine( 0, (DISPLAY_HEIGHT-1)-(.8 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.8 *ARDUINO_PRECISION * scale), BLACK);
  //display.drawLine( 5, (DISPLAY_HEIGHT-1)-(.84 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.84 *ARDUINO_PRECISION * scale), BLACK);

  //Draw Voltage Ref Numbers
  display.setCursor(0,((DISPLAY_HEIGHT-1)-(.2 *ARDUINO_PRECISION * scale))-3);
  display.print((int)(5.0*0.2));
  display.setCursor(0,((DISPLAY_HEIGHT-1)-(.4 *ARDUINO_PRECISION * scale))-3);
  display.print((int)(5.0*0.4));
  display.setCursor(0,((DISPLAY_HEIGHT-1)-(.6 *ARDUINO_PRECISION * scale))-3);
  display.print((int)(5.0*0.6));
  display.setCursor(0,((DISPLAY_HEIGHT-1)-(.8 *ARDUINO_PRECISION * scale))-3);
  display.print((int)(5.0*0.8));

  for(xCounter = 0; xCounter <= DISPLAY_WIDTH; xCounter++)
  {
    display.drawPixel(xCounter, (DISPLAY_HEIGHT-1)-readings[xCounter], BLACK);
    if(xCounter>1){
      display.drawLine(xCounter-1, (DISPLAY_HEIGHT-1)-readings[xCounter-1], xCounter, (DISPLAY_HEIGHT-1)-readings[xCounter], BLACK);
    }
  }
  //Draw FPS
  display.setCursor((DISPLAY_WIDTH-1)-11,0);
  display.print(frames);

  //Draw Voltage
  display.setCursor(((DISPLAY_WIDTH-1)/2),0);
  display.print(analogRead(channelAI)/ARDUINO_PRECISION*5.0);

  display.display();

  //Calculate FPS
  drawtime = micros();
  frames=1000000/*a second*//(drawtime-lastdraw);
  lastdraw = drawtime;
}

Now the problem arises when i try doing the 2 things on d same arduino due board.
I got perfect results when i used arduino due and arduino uno simultaneously but have not been able to generate waves on the LCD using the same board.
Is it possible to do the same. Can some1 help me incorporate the 2 programs into 1  ..Thanxx
I tried playing around with my setup() and loop() and have reached a point where my program does everything ,ie takes keypad input ,displays options on the LCD ,takes in freq and generates a splashscreen but the only thing i'm missing out on is d wave display on the LCD (I'm able to see the selected wave on the DSO) ..So i guess i'm pretty close, and the edited code is as follows:-
#include "waveforms.h"
#include <Keypad.h>
#include <SPI.h>

#include <Adafruit_GFX.h>
#include <gfxfont.h>

#include <Adafruit_PCD8544.h>

 //Set the desired duty cycle in percentage
Adafruit_PCD8544 display = Adafruit_PCD8544(8, 9, 10, 12, 11);
double dc,t,a,d;
long d_milli,d_micro,a_milli,a_micro,m,n;
int stage =0;

int sample_delay1;
float sample_delay;
String num1,num2;
int wave1;
String wave_name;
double duty_cycle,k,Z;
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the cymbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'.','0','#','D'}
};
byte rowPins[ROWS] = {23,25,27,29}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {31,33,35,37}; //connect to the column pinouts of the keypad
int i = 0;
int t_sample;

#define DISPLAY_WIDTH 84
#define DISPLAY_HEIGHT 48

#define ARDUINO_PRECISION 1023.0
//Adafruit_PCD8544 display = Adafruit_PCD8544(8,9,10,12,11);

//Analog Pins
int channelAI=A0;

#define DELAY_POTENTIMETER //disabled it I don't have it connected
#ifdef DELAY_POTENTIMETER
int delayAI = A1;       // delay potentiometer
#endif

float delayVariable = 0;
float scale = 0;
int xCounter = 0;
int yPosition = 0;
int readings[DISPLAY_WIDTH+1];
int counter = 0;

unsigned long drawtime = 0;
unsigned long lastdraw = 0;
int frames = 0;

//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
boolean in_setup = true;
void setup()
{
  Serial.begin(9600);
  analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
  analogReadResolution(12);
  display.begin(20,4);

  char key = customKeypad.getKey();

  display.begin();
  display.display();
  display.setContrast(40);// you might have a slightly different display so it might not be the optimal value for you
  display.clearDisplay();

  display.setTextSize(1);
  display.setTextColor(BLACK);
  display.setCursor(0, 0);
  display.print("choose wave: ");
  display.display();
  display.setCursor(1, 8);
  display.print("A=Sine");
  display.display();
  display.setCursor(1,16);
  display.print("B=Triangular");
  display.display();
  display.setCursor(1,24);
  display.print("C=Sawtooth");
  display.display();
  display.setCursor(1,32);
  display.print("D=Square");
  display.display();

  while( true)
  {
    char key = customKeypad.getKey();
    if(stage == 0)
    {
      Serial.println("in stage 0");
      if(key == 'A' )
      {
        wave1 = 0;
        display.clearDisplay();
        display.setCursor(0,0);
        display.print(" Sine?      ");
        display.display();
        wave_name ="Sinusoidal";
        Serial.println(wave_name);

      }
      else if(key == 'B')
      {
        wave1 = 1;
        display.clearDisplay();
        display.setCursor(0,0);
        display.print("Triangular?");
        display.display();
        wave_name ="Triangular";
        Serial.println(wave_name);
      }
      else if(key == 'C')
      {
        wave1 = 2;
        display.clearDisplay();
        display.setCursor(0,0);
        display.print("Sawtooth?  ");
        display.display();
        wave_name ="Sawtooth";
        Serial.println(wave_name);
      }
      else if(key == 'D')
      {
        wave1 = 3;
        display.clearDisplay();
        display.setCursor(0,0);
        display.print("Square?    ");
        display.display();
        wave_name ="Square";
        Serial.println(wave_name);

      }
      else if(key == '#')
      {
       stage++;
       display.clearDisplay();
       display.setCursor(20, 8);
       display.println("Freq=");
       display.display();
       Serial.println("Frequency=");
      }
    }
    else if(stage == 1)
    {
      if(key != NO_KEY &&(key=='1'||key=='2'||key=='3'||key=='4'||key=='5'||key=='6'||key=='7'||key=='8'||key=='9'||key=='0'))
      {
        num1 = num1 + key;
        //int numLength = num1.length();
        //to adjust one whitespace for operator
        display.setTextSize(1);
        display.setTextColor(BLACK);
        display.setCursor(48, 9);
        display.print(num1);
        display.display();
      }
      else if(key == '#')
      {
        stage++;
        k = num1.toInt();
        Serial.print(k);
        display.setTextSize(1);
        display.setTextColor(BLACK);
        display.display();
        display.setCursor(10, 1);

        int sample_delay_int = 1000000 / (k * 120);
        float sample_delay_float = 1000000 / (k * 120);
        float difference = sample_delay_float - sample_delay_int;
        sample_delay1 = sample_delay_int - 6;
        if (difference > 0.5)
        {
          sample_delay1++;
        }

        display.display();
        Serial.println(sample_delay1);
        display.clearDisplay();
        display.print(wave_name);
        display.setCursor(1, 8);
        display.println("Freq=");
        display.print(num1);
        display.println(" Hz");
        break;
      }
    }
  }

  //record readings
  for(xCounter = 0; xCounter <= DISPLAY_WIDTH; xCounter++)
  {
    yPosition = analogRead(A0);
    readings[xCounter] = (yPosition*scale);
    #ifdef DELAY_POTENTIMETER
    delay (delayVariable);
    #endif
  }

  display.clearDisplay();

  #ifdef DELAY_POTENTIMETER
  delayVariable = analogRead(delayAI);
  display.display();
  delayVariable = (delayVariable/100);
  #endif
  scale = (float)(DISPLAY_HEIGHT-1)/ARDUINO_PRECISION;

  //Draw Voltage Ref Lines
  display.drawLine( 10, 0, 10, DISPLAY_HEIGHT-1, BLACK);
  display.drawLine( 5, (DISPLAY_HEIGHT-1)-(.2 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.2 *ARDUINO_PRECISION * scale), BLACK);
  display.drawLine( 0, (DISPLAY_HEIGHT-1)-(.4 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.4 *ARDUINO_PRECISION * scale), BLACK);
  display.drawLine( 5, (DISPLAY_HEIGHT-1)-(.6 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.6 *ARDUINO_PRECISION * scale), BLACK);
  display.drawLine( 0, (DISPLAY_HEIGHT-1)-(.8 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.8 *ARDUINO_PRECISION * scale), BLACK);
  //display.drawLine( 5, (DISPLAY_HEIGHT-1)-(.84 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.84 *ARDUINO_PRECISION * scale), BLACK);

  //Draw Voltage Ref Numbers
  display.setCursor(0,((DISPLAY_HEIGHT-1)-(.2 *ARDUINO_PRECISION * scale))-3);
  display.print((int)(5.0*0.2));
  display.setCursor(0,((DISPLAY_HEIGHT-1)-(.4 *ARDUINO_PRECISION * scale))-3);
  display.print((int)(5.0*0.4));
  display.setCursor(0,((DISPLAY_HEIGHT-1)-(.6 *ARDUINO_PRECISION * scale))-3);
  display.print((int)(5.0*0.6));
  display.setCursor(0,((DISPLAY_HEIGHT-1)-(.8 *ARDUINO_PRECISION * scale))-3);
  display.print((int)(5.0*0.8));

  for(xCounter = 0; xCounter <= DISPLAY_WIDTH; xCounter++)
  {
    display.drawPixel(xCounter, (DISPLAY_HEIGHT-1)-readings[xCounter], BLACK);
    if(xCounter>1){
      display.drawLine(xCounter-1, (DISPLAY_HEIGHT-1)-readings[xCounter-1], xCounter, (DISPLAY_HEIGHT-1)-readings[xCounter], BLACK);
    }
  }
  //Draw FPS
  display.setCursor((DISPLAY_WIDTH-1)-11,0);
  display.print(frames);

  //Draw Voltage
  display.setCursor(((DISPLAY_WIDTH-1)/2),0);
  display.print(analogRead(A0)/ARDUINO_PRECISION*5.0);

  display.display();

  //Calculate FPS
  drawtime = micros();
  frames=1000000/(drawtime-lastdraw);
  lastdraw = drawtime;
  display.display();
}

void loop()
{
  analogWrite(DAC1, waveformsTable[wave1][i] );
  i++;
  if(i == maxSamplesNum)  // Reset the counter to repeat the wave
    i = 0;
  else
  delayMicroseconds(sample_delay1);

  analogWrite(DAC0, waveformsTable[wave1][i] );
  i++;
  if(i == maxSamplesNum)  // Reset the counter to repeat the wave
    i = 0;
  else
    delayMicroseconds(sample_delay1);
}

Can some1 possibly tinker around with this ..It'll b a huge help!!

Can you reprogram your signal generator to work on timer interrupts, so the oscilloscope code (+ keypad handling) runs while being interrupted by the wave generation?

Also, I believe you can slightly increase your FPS by moving the "static" part of the drawing in setup(), and greatly by not using the adafruit library - AFAIK it uses offscreen buffer on 5110 and redraws the entire screen. Instead you just write directly to the screen, one or 2 writes per column (one to erase the old samlple and one to draw the new one, unless they overlap - then it is one write) - just draw pixels (actually 8 pixels at once) for each column.

You have two programs. One has a very complicated setup(), but a very quick loop(). The other has a very small setup(), but a very complicated loop(). And you want to merge the two programs?
That will be very, very difficult. Your first program loop() looks like this:
void loop() {
   analogWrite(...); // Very quick code
   i++;              // Very quick code
   if (..)           // Very quick code
      i = 0;         // Very quick code
   else              // ***BUG!!!*** This shoud not be here!
   delayMicroseconds(...); // Very specific timing delay
} // loop()

In other words, to produce the correct waveform it does very few instructions very quickly - and then waits a carefully calculated time.
Your other program's loop() does lots of things, and doesn't care about timing. The code is not time-sensitive at all - and writing to the display takes variable time anyway.
Your only choice is to set a timer to interrupt every sample_delay1 microseconds, and inside the timer interrupt handler do the analogWrite(...); call instead of having the loop() function do it. That is Advanced Arduino programming!

Thanx a lot @John Burger! I tried playing around with my setup() and loop() and have reached a point where my program does everything ,ie takes keypad input ,displays options on the LCD ,takes in freq and generates a splashscreen but the only thing i'm missing out on is d wave display on the LCD (I'm able to see the selected wave on the DSO) ..So i guess i'm pretty close, and the edited code is as follows:-

I've included the edited code in my original question ..KIndly have a look,c if u can tinker around with the code! Thanx a lot

The reason that you are not seeing the wave display is that you're not generating it in loop(). You do understand that setup() is performed once, and when that finishes loop() is called repeatedly. In your edited version you have drawn the wave display once in setup(). Your loop() only generates (now two) waveforms - it needs to also draw the wave, but that will disturb the timing of the waveforms. And now that you're generating two waveforms, why are you waiting sample_delay1 twice? You are also incrementing i twice. You've made it very complicated for yourself!

Yeah you're right!@John Burger! A possible solution to the problem dat i came across was parallel programming..I load 1st part of the code on arduino uno ,2nd part on the 'Due' and program them to run simultaneously.Bt is this feasible?? N do u have any idea of parallel programming possibly,coz i have absolutely no experience of it.

There's no need to do the sort of "parallel programming" that you describe - unless you have the boards necessary, of course! Re-read my answer, paying particular attention to the final paragraph. You can do everything that you want with Timer Interrupts - but we can't give you a course on that from StackExchange! Read, read, read everything you can get your hands on...


text:
Connect GPS module (WeeBee) to Arduino Uno
This is my very first Arduino project. I want to learn about GPS navigation by exploring the NMEA protocol!
Therefore, I bought a WeeBee GPS module. After reading the datasheet, I have two questions:

The official Arduino website states

Note: if you are using an Arduino Uno, keep in mind that you can't use the GPS module at the same time as your computer is connected on the USB port.

But I you go to the end of his tutorial, you will see he can transmit the GPS data to his computer. I don't understand why it would not be possible...
The GPS module datasheet (download link here) states that the maximum voltage is 5V. But it also states

serial connections are 3.3V CMOS Logic Levels

and

Suitable decoupling must be provided by external decoupling circuitry.

So, does it mean I need a logic level converter to prevent damage to the GPS module?

The article on the Arduino website means that you can't upload sketches from your PC to the Arduino or receive any sort of data, through the serial monitor or otherwise, from your PC, while the GPS module uses the RX pin. Any attempt to send data from PC to Uno in this condition would cause the Arduino to receive only corrupted data, since 2 devices (GPS module and PC) would be trying to send data at the same time, with the same line. This limitation is easily resolved by connecting the GPS module to a SoftwareSerial port instead; this keeps the HardwareSerial port (pins 0 & 1) free for bidirectional PC-Arduino communication.
The datasheet says that the maximum power supply voltage is 5 V. However, the serial connections are 3.3 V logic, so yes, you will need logic level shifters. A simple voltage divider will serve. However, 'external decoupling' refers to circuitry used in decoupling/smoothing out any spikes or dips that may occur in the supply voltage. An untamed spike could damage the device, while a dip (perhaps from large current draw) could cause the device to stop working, if the voltage falls low enough to be considered under-voltage. A 10uF electrolytic capacitor, connected from Vcc to GND close to the GPS module, should be okay.

Thank you for your answer!
-) I will use the "softwareserial" on pins 2 and 3 instead of the "hardwareserial" on pins 0 and 1. But they didn't do it in the tutorial and they still can send GPS data to the computer...
-) I assume that a logic level shifter like this one will do the job? Together with a 10µF capacitor connected with the "VA" and "OE" ports of the level shifter.

Dear  @TisteAndii, Thanks again for you answer.
Could you please look at my reply? Just to know I interpret your answer correctly. Regards, Simon.

@Simon Post a link to the tutorial. Yes, you should use pins 2 and 3 with SoftwareSerial. As for the logic shifter, all you need is a pair of resistors, perhaps 2.2k and 3.3k. Google "resistor voltage divider 5 3.3".

Dear @TisteAndii,I meant the Arduino page. You will see that they connected the GPS module on pin 0, but they could also send it with the SoftwareSerial to the computer (as shown at the buttom of the page).

Thank you for you input regarding the logic level shifter. Indeed, a 1.7k and 3.3k (or 10k and 20k and so on) would work. Although a simple resistor voltage divider is not the recommended solution. The impedance of the surrounding circuitry can affect it (although this is not an issue here, I guess) and high freq. signals (no idea if baud rate of 9600bps will be an issue).

I would like to add that SoftwareSerial is the worst software serial library to use for the GPS device.  AltSoftSerial on pins 8 & 9 is the best, followed by NeoSWSerial on any pins, and the last choice is SoftwareSerial on any pins.  This answer has full details.


text:
How to wire up and trigger this SPDT relay?
How do I connect a SPDT relay to an Arduino?
It's a DC 5V Coil 6 Pin relay and ultimately what I want to do is have the Arduino trigger the relay to allow voltage to pass through.
I couldn't find a data sheet, but apparently this is the layout...
----------------------------------
|....1......2..............3.....|
|................................|
|....4......5..............6.....|
----------------------------------

2 and 5 are the 5v relay coil
3 and 6 are shorted together
3 and 1 are normally closed
3 and 4 are normally open

datasheet for HT4100F. Current through the coil is at least 30mA, which is already above the recommended current for an Arduino pin.

You can use this connection diagram with your relay

6 pin Relay pin out

Code
int Relay = 8;

void setup()
{
  pinMode(Relay, OUTPUT);
}

void loop()
{
      digitalWrite(Relay, HIGH);  // turn on relay
      delay(2000);
      digitalWrite(Relay, LOW);   // turn off relay
      delay(2000);
}

First check your relay with multi meter then find the Coil, Com, NO and NC points for correct connection.
Hope this will help you.

According to the link you've provided, the coil draws very little current, and the person posting that comment suggests that it can be directly driven by an arduino. I would hesitate to use more than one to a board without additional research in that respect.
The comment also suggests that a capacitor be placed across the coil terminals, which will also protect your circuit from excessive power draw causing drop outs.
The research I've done indicates that the digital pins can handle a maximum of 40 ma, but the recommendation is no more than 20 ma, which is lower than the specs for this relay.
If you are going to use more than one on a given arduino board, a shift register or equivalent would protect your board and give you reliable results. For a single relay, consider this resource:
https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/transistors
Some additional research may lead one to believe that even 20 ma is too much current to draw, so the transistor option is certainly the safer route.
Be certain to use pull-up or pull-down resistors, depending on your configuration with the digital pin selected.
You didn't indicate what you were going to be connecting to the N/O or N/C pins, but that won't matter if they are external to the arduino and do not exceed the specifications of the relay.

Use a driver transistor (or MOSFET, with a 4K7 pull-down), and a flyback diode with the anode at the negative terminal, and cathode at positive terminal. I used some tiny ones, which failed, so now I use ones that can handle ~0.5A, but that's probably overkill.
If you want galvanic isolation, use an optocoupler instead of a transistor - I only do this for AC. I have never needed decoupling capacitors for this type of relay.
Edit:

Wire 5V to relay positive terminal.
Wire relay negative terminal to NPN transistor/MOSFET collector/drain.
Wire NPN/MOSFET emitter/source to GND. Wire NPN/MOSFET base/gate to some digital pin. If using a transistor, do it across a 1000 ohms resistor.
If using a N-channel MOSFET add a 4700 ohms pull-down from gate to GND.
Wire diode cathode to relay positive terminal, and anode to relay negative terminal.

I would not use the decoupling cap, but if OP really wants it, go for 50-100V 10uF.

Any chance of a diagram?

The pulldown resistor is needed if you use some kind of FET transistor, but is is useless with an NPN.

Yes, you're right.


text:
Serial.readString() not working becaue of outdated IDE?
I've searched google honestly but can't find an answer nor changelogs for Arduino that might be the answer.
Basically I'm trying to use Serial.readString() to input commands to the Serial Monitor but it shows an error that readString is not a member of 'HardwareSerial'.
I am using Arduino 1.0 as IDE because the device I'm using (Aceduino) seems to have a custom IDE derived from 1.0 so I'm not sure if it will work with newer IDE versions. Wondering if that was what's causing the eror

Stream::readString() is available since version 1.0.1. See:

the changelog, and
the corresponding commit.


text:
Arduino Uno + cc3000 breakout board - read DOM instead of HTML
Is there a way to make the CC3000 read the DOM of a website instead of the HTML on the file?
I'm using the WebClient file which works fine and prints the HTML of the webpage, but the website I'm trying to read from has its HTML different from its DOM (ie: Javascript modifies the HTML once the page loads).
Can I use something other than www.read()?

To get a (programatically changed) DOM you need an HTML parser to construct the initial DOM (and something that runs Javascript to modify it).
The server only sends a file and does not store or send a DOM; a DOM is built by the receiving application, usually a browser.

The DOM is something related to browsers. A web server merely serves up stored HTML and any accompanying JS to the client CC3000. It's up to a browser to parse the document, execute any JS to construct the DOM tree and finally render the webpage based on the DOM--not something an Arduino is built for.
I'm not an expert but you will have to forward the HTML from your Arduino to a browser and then somehow scrape the results after it renders the page. Or use a website that implements server-side rendering.

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


text:
Can I connect my arduino ground to an external battery ground? Are they the same when said battery is powering the arduino?
I need to power my camera peripheral with an external power supply, since apparently I can't power both the camera and the camera's relay switch with my 5V out pin (My relays cut out and continually reset themselves if I try to run my 5V to both the camera relay switch and the relay board VCC.)
So I'm powering the camera with a 5V battery pack and my arduino with my PC, but I still need to communicate with it via UART, so I need the camera ground to be the same as my arduino ground. Can I connect the two? Is this a bad idea? Because I'm doing it now and it seems to work. I just don't want to cause a problem later on down the road, whether I'm connected to my computer or on battery power.Any advice would be greatly appreciated.

A battery's ground is floating. That means that it's "happy" to take on any absolute value by simply connecting it to another ground - it just stops floating. This is why it's easy to connect a battery-powered phone directly to a computer to get the photos off or whatever.
The only time you shouldn't connect two grounds is if neither are floating. A good example would be the grounds of two different houses, which are physically connected to the Earth (as in the planet). It'd be difficult to budge the whole Earth's ground level!
But shouldn't they be the same? Unfortunately not. You could measure a distinct voltage difference (sometimes in the hundreds of volts) between two house earths due to the differences in their makeup.
One small note: if you do connect two grounds, only connect them in one spot. If you have two other ground pins a small distance away from the connected ones, there may be a voltage difference between them: now the two are explicitly relative to each other, so neither can be considered floating relative to each other. The pair as a system - if neither are earthed at least - is still floating.
These so-called "ground loops' can induce current where none is desired.

Outstanding answer. I guess I never realized this happens every time I plug a phone or a camera into a computer!


text:
What is the difference between running code with the scope of the void setup() or void loop() vs. outside their scope?
Good evening everyone,
I have bene playing around with making my own library, specifically for the controlling Timer1 on the Arduino Mega 2560. I'm sort of new to OOP but I am trying my hand at it here.
I wrote some code to generate a PWM wave with a 100 ms period and a 25% duty cycle, and I have Siglent SDS 1052DL, 50MHz oscilloscope that I'm using that verifies the code is successful. I am using clear-timer-on-compare-match mode and timer interrupts to generate the PWM wave. My code is below:
#include "Timer1.h"

Timer1 timer;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  timer.begin();
}

void loop(){
  // put your main code here, to run repeatedly:
}

I made a Timer1.cpp file and a Timer1.h to go along with this file. They are below.
Timer1.cpp
#include "Arduino.h"
#include "Timer1.h"

float frequency = 10.0;
float period_ms;
float clock_pulse = 16.0;

unsigned long opening_time = 25000;

unsigned int ocr1a;
unsigned int ocr1b;

Timer1::Timer1() { // Object used to control 16-bit timer1

}

void Timer1::begin() {
  CRITICAL_SECTION_START; // Clear I bit
  CLEAR_TCCR1A; // Reset TCCR1A
  CLEAR_TCCR1B; // Reset TCCR1B
  SET_CTC_MODE; // Set to CTC mode
  DISABLE_TIMER1_INTERRUPTS; // Disable OCIE1A/B
  TCCR1B |= (1 << CS12); // 256
  period_ms = (1000.0f / frequency);
  ocr1a = 1000UL * (period_ms / clock_pulse);
  OCR1A = ocr1a;
  TIMSK1 |= (1 << OCIE1A);

  ocr1b = (unsigned int)float(opening_time) / clock_pulse;
  OCR1B = ocr1b;
  TIMSK1 |= (1 << OCIE1B);
  TCNT1 = 0; // Reset counter

  CRITICAL_SECTION_END; // Set I bit
}

ISR(TIMER1_COMPA_vect) {
  digitalWrite(13, HIGH);
}

ISR(TIMER1_COMPB_vect) {
  digitalWrite(13, LOW);
}

Timer1.h
#ifndef TIMER1_H
#define TIMER1_H

// ========== HANDY MACROS ========== //
#define CLEAR_TCCR1A                  TCCR1A = 0
#define CLEAR_TCCR1B                  TCCR1B = 0
#define SET_CTC_MODE                  TCCR1B |= (1 << WGM12)
#define DISABLE_TIMER1_INTERRUPTS     TIMSK1 &= ~((1 << OCIE1B) | (1 << OCIE1A))
#define CLEAR_CLOCK_SELECT_BITS       TCCR1B &= ~((1 << CS12) | (1 << CS11) | (1 << CS10))

#define CRITICAL_SECTION_START unsigned char _sreg = SREG; cli()
#define CRITICAL_SECTION_END   SREG = _sreg

class Timer1{
  public:
  // Constructor:
  Timer1();
  // Begin:
  void begin();

};

#endif // TIMER1_H

This code works exactly as I would expect. I originally had placed the whole block of code found in the Timer1::begin() method in the Timer1::Timer1() constructor method. When I did this, I was getting a completely different signal (2.04 ms period with about an 80% duty cycle). Is there a simple explanation for what is occurring?

You are coding in C++ but have variables global to the file Timer1.cpp.  It would be better if you defined these variables with scope of the class Timer1.  Then they should be defined for member functions which should include the constructor.  What I'm wondering ... how did the code in the constructor compile in the Timer1.h file when the defined variables only had scope over the Timer1.cpp file?

In your test code, you declare Timer1 in global scope. This means its
constructor will be called right when the program starts, even before
main() is called. The first thing the Arduino main() does is
to call init(), which configures all the timers for PWM
operation, as expected by analogWrite(). Then, any initialization of
Timer1 done by the constructor will be undone by init(). That's why
you want to defer that initialization until setup().
Edit: I took the liberty to do a code review on your post. Below are
a few suggestions. I hope some of them might be useful.

Put the empty constructor in the .h file, this avoids it being
compiled into a real empty function.
Qualify frequency, clock_pulse and opening_time as const,
and make period_ms local to Timer1::begin(). This way all the
floating point operations are performed at compile time and you
don't get all the floating point support compiled into your program.
Your CRITICAL_SECTION_* macros are redundant with
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) from avr-libc. But
then, do you really need to block the interrupts the whole time?
I don't find the other macros in Timer1.h really useful either: just
put comments next to each access to a hardware register.
I would set TCCR1B last: the timer starts counting the moment you
set this register.
You should subtract 1 from the values you set in OCR1A and
OCR1B: the period and HIGH time are OCR1A+1 and OCR1B+1
respectively.
You may want to round the period and HIGH time to the nearest
integer. It may make no difference here but you users may want to
change frequency and opening_time.
Your variables ocr1a and ocr1b serve no useful purpose, they
just needlessly eat RAM.
You casting opening_time to float, then back to unsigned int,
serves no useful purpose either.
You may want to replace digitalWrite() with direct port access, as
this function is really slow and you are calling it from an ISR.

Below is my throw at Timer1.cpp. Note that port and bit could be
made private data of the class, and the pin number could be a parameter
to the begin() method.
#include "Arduino.h"
#include "Timer1.h"

/* The three constants below can be tuned to taste:  */

const float frequency    = 10;  // hertz
const float opening_time = 25;  // milliseconds
const int   pin          = 13;

/* Nothing should need to change below this line. */

const uint16_t prescaler = 256;
const float f_timer = float(F_CPU) / prescaler;
static volatile uint8_t *port;
static uint8_t bit;

void Timer1::begin() {
    // Prepare the output.
    port = portOutputRegister(digitalPinToPort(pin));
    bit = digitalPinToBitMask(pin);
    pinMode(pin, OUTPUT);

    // Configure Timer 1.
    TCCR1A = 0;  // undo the configuration done by...
    TCCR1B = 0;  // ...the Arduino core library
    TCNT1  = 0;  // reset counter
    OCR1A  = round(f_timer / frequency) - 1;
    OCR1B  = round(f_timer * opening_time * 1e-3) - 1;
    TIMSK1 = _BV(OCIE1A)   // enable TIMER1_COMPA interrupt
           | _BV(OCIE1B);  // enable TIMER1_COMPB interrupt
    TCCR1B = _BV(WGM12)    // CTC mode
           | _BV(CS12);    // prescaler = 256
}

ISR(TIMER1_COMPA_vect) {
    *port |= bit;
}

ISR(TIMER1_COMPB_vect) {
    *port &= ~bit;
}

Thanks for all the helpful comments and suggestions! I will definitely use some of your tips. Some of the other things you pointed out, were as a result of trying to reduce a code down enough to show the problem and exclude the portions that I felt didn't relate to the question. In the end, I want the user to be able to change the frequency/period, the reason for which the Arduino will need to calculate the values.

I mean to say that the user will change the values while the Arduino is running via Serial.

What about setting the TCCR1B starts the counting? Is it the enabling of the CTC mode, or the setting of the prescaler?

@SebastianFreeman: It's the prescaler. When the three CS1x bits are set to zero (which happens when you clear TCCR1B), the timer stops counting. It starts again when you change any of these three bits.

I believe you should be able to put your code back into the constructor if you move all the variable you defined with file scope in Timer1.cpp:
float frequency = 10.0;
float period_ms;
float clock_pulse = 16.0;

unsigned long opening_time = 25000;

unsigned int ocr1a;
unsigned int ocr1b;

...to the Timer1 class definition (either in the public or private section).  This way all the variables will have the scope of the class and the code should work the same regardless where in the class it is.


text:
Programming Problem with a hand gesture controlled robot; the analogwrite() function doesn't work
So I recently tried to make a hand gesture controlled robot but ran into some programming error. Here are the specs:
For the transmitter module, I used the following:
*Arduino Nano 3.0 as the Microcontroller development platform
   *Grove 3 axis digital accelerometer 16g for sensing hand gesture
   *RF transmitter 433 Mhz (Transmitter: JMR-TX1)
   *Power source: 7.2V rechargeable battery unit to power up the Arduino Nano
For the robot, I used the following:
  *Pololu Chassis
  *Two DC geared motors, compatible wheels
  *L293D Dual DC motor controller module
  *Arduino Nano 3.0
  *RF receiver 433 Mhz (Receiver: RXB6)
  *Power source: 7.2V rechargeable battery unit to power up the Arduino Nano
I hooked up all the parts carefully. I uploaded the code entitled "Transimitter_code" to the transmitter. I uploaded a code called "Receiver_test" and used serial monitor to see if the robot's arduino received data from the transmitter, the data I wanted to receive was the angle that the accelerometer was tilted on x and y axis measured by the accelerometer. Fortunately, the Arduino was receiving data wirelessly and displaying it in the serial monitor, which means my basic concept was ok. You can see the code attached to this thread. P.s. You will need three libraries: Wire.h, VirtualWire.h and ADXL345.h to run the codes. You can google them up and get them for free. See the code for the transmitter below:
/* Code for the transmitter of the mind controlled bot */

#include <Wire.h>
#include <ADXL345.h>
#include <VirtualWire.h>

ADXL345 adxl; //variable adxl is an instance of the ADXL345 library
int ledPin = 13; //a sign when the transmitter is working

int TX_PIN = 11;// Tell Arduino on which pin you would like to Transmit data NOTE should be a PWM Pin
int TX_ID = 3; // Transmitter ID address

typedef struct roverRemoteData// Data Structure
{
 int    TX_ID;      // Initialize a storage place for the outgoing TX ID
 int    x1;// Initialize a storage place for the first integar that you wish to Send
 int    y1;// Initialize a storage place for the Second integar that you wish to Send
};

void setup() {
 vw_setup(2000);//Bits per second
 pinMode(ledPin,OUTPUT);
 vw_set_tx_pin(TX_PIN);// Set Tx Pin
 Serial.begin(9600);//Initialise the serial connection

 adxl.powerOn();

//set activity/ inactivity thresholds (0-255)
adxl.setActivityThreshold(75); //62.5mg per increment
adxl.setInactivityThreshold(75); //62.5mg per increment
adxl.setTimeInactivity(10); // how many seconds of no activity is inactive?

//look of activity movement on this axes - 1 == on; 0 == off
adxl.setActivityX(1);
adxl.setActivityY(1);
adxl.setActivityZ(1);

//look of inactivity movement on this axes - 1 == on; 0 == off
adxl.setInactivityX(1);
adxl.setInactivityY(1);
adxl.setInactivityZ(1);

//look of tap movement on this axes - 1 == on; 0 == off
adxl.setTapDetectionOnX(0);
adxl.setTapDetectionOnY(0);
adxl.setTapDetectionOnZ(1);

//set values for what is a tap, and what is a double tap (0-255)
adxl.setTapThreshold(50); //62.5mg per increment
adxl.setTapDuration(15); //625us per increment
adxl.setDoubleTapLatency(80); //1.25ms per increment
adxl.setDoubleTapWindow(200); //1.25ms per increment

//set values for what is considered freefall (0-255)
adxl.setFreeFallThreshold(7); //(5 - 9) recommended - 62.5mg per increment
adxl.setFreeFallDuration(45); //(20 - 70) recommended - 5ms per increment

//setting all interrupts to take place on int pin 1
//I had issues with int pin 2, was unable to reset it
adxl.setInterruptMapping( ADXL345_INT_SINGLE_TAP_BIT,   ADXL345_INT1_PIN );
adxl.setInterruptMapping( ADXL345_INT_DOUBLE_TAP_BIT,   ADXL345_INT1_PIN );
adxl.setInterruptMapping( ADXL345_INT_FREE_FALL_BIT,    ADXL345_INT1_PIN );
adxl.setInterruptMapping( ADXL345_INT_ACTIVITY_BIT,     ADXL345_INT1_PIN );
adxl.setInterruptMapping( ADXL345_INT_INACTIVITY_BIT,   ADXL345_INT1_PIN );

//register interrupt actions - 1 == on; 0 == off
adxl.setInterrupt( ADXL345_INT_SINGLE_TAP_BIT, 1);
adxl.setInterrupt( ADXL345_INT_DOUBLE_TAP_BIT, 1);
adxl.setInterrupt( ADXL345_INT_FREE_FALL_BIT,  1);
adxl.setInterrupt( ADXL345_INT_ACTIVITY_BIT,   1);
adxl.setInterrupt( ADXL345_INT_INACTIVITY_BIT, 1);
}

void loop()
{
struct roverRemoteData payload;
payload.TX_ID = TX_ID; // Set the Radio Address
int x, y, z;
adxl.readXYZ(&x, &y, &z); //read the accelerometer values and store them in variables  x,y,z
payload.x1 = x;
payload.y1 = y;
vw_send((uint8_t *)&payload, sizeof(payload)); // Send the data
vw_wait_tx();// Wait for all data to be sent
if ((x>80) || (x<-80) || (y>80) || (y<-80))
{
digitalWrite(13, HIGH); //ledpin indicator
}
else
{
 digitalWrite(13, LOW);
}
delay(100);

}

Now, I tried to use the received data to control the motion of the bot, that is: run the motors in specific direction. However, this time, the code seems to have some problem. Here's the code for the robot:
/* Mind controlled car - Car's code */

#include <VirtualWire.h>

int RX_PIN = 11;// Tell Arduino on which pin you would like to receive data NOTE should be a PWM Pin
int RX_ID = 3;// Recever ID address
int TX_ID;

typedef struct roverRemoteData// Data Structure
{
int    TX_ID;      // Initialize a storage place for the outgoing TX ID
int    x1;// Initialize a storage place for the first integar that you wish to Send
int    y1;// Initialize a storage place for the Second integar that you wish to Send
};

void setup() {
pinMode(5, OUTPUT); //in 1
pinMode(6, OUTPUT); //in 2
pinMode(9, OUTPUT); //in 3
pinMode(10, OUTPUT); //in 4
Serial.begin(9600);
vw_setup(2000);// Setup and Begin communication over the radios at 2000bps( MIN Speed is 1000bps MAX 4000bps)
vw_set_rx_pin(RX_PIN);// Set RX Pin
vw_rx_start();

}

void loop() {

struct roverRemoteData receivedData;
uint8_t rcvdSize = sizeof(receivedData);//Incoming data size
vw_wait_rx();// Start to Receive data now
if (vw_get_message((uint8_t *)&receivedData, &rcvdSize)) // Check if data is available
{
if (receivedData.TX_ID == RX_ID) //Check if the radio signal recieved matches the ID of the Reciever
{
  if (((receivedData.x1 < 80) && (receivedData.x1 > -80)) && ((receivedData.y1 < 80) && (receivedData.y1 > -80))) //halt
  {
    halt();

  }
  else if (((receivedData.x1 < 80) && (receivedData.x1 > -80)) && (receivedData.y1 > 80)) //forward
  {
    int a = receivedData.y1;
    goForward(a);

  }
  else if (((receivedData.x1 < 80) && (receivedData.x1 > -80)) && (receivedData.y1 < -80)) //backward
  {
    int b = -receivedData.y1;
    goBackward(b);

  }
  else if ((receivedData.x1 > 80) && ((receivedData.y1 < 80) && (receivedData.y1 > -80))) //left
  {
    int c = receivedData.x1;
    goLeft(c );

  }
  else if ((receivedData.x1 < -80) && ((receivedData.y1 < 80) && (receivedData.y1 > -80))) //right
  {
    int d = -receivedData.x1;
    goRight(d);

  }
  }
  }
  }

  void goForward(int y)
  {
  analogWrite(5, y);
  analogWrite(6, 0);
  analogWrite(9, y);
  analogWrite(10, 0);
  delay(50);

  }

  void goBackward(int z)
  {
  analogWrite(5, 0);
  analogWrite(6, z);
  analogWrite(9, 0);
  analogWrite(10, z);
  delay(50);

  }

  void goLeft(int w)
  {
  analogWrite(5, w);
  analogWrite(6, 0);
  analogWrite(9, 0);
  analogWrite(10, 0);
  delay(50);

  }

  void goRight(int x)
  {
  analogWrite(5, 0);
  analogWrite(6, 0);
  analogWrite(9, x);
  analogWrite(10, 0);
  delay(50);

  }

  void halt()
  {
  analogWrite(5, 0);
  analogWrite(6, 0);
  analogWrite(9, 0);
  analogWrite(10, 0);
  delay(50);

  }

I wanted to use the analogWrite() function to control the speed of the motor. However, the code does not work at all if I use the analogWrite() function within the goForward(), goBackward(), goLeft(), goRight() functions to control the speed of the motor, only one of the motors keeps rotating at a certain speed without responding to the transmitter. Surprisingly, if I use digitalWrite() to control the motors, they work fine, instantly responding to the change in direction of the transmitter. P.S. I connected my motors to PWM pins of the Arduino.
What's the problem?

VirtualWire uses timer1, which would disable PWM on pins 9 and 10.

Oh God.. :( What should I do then? :/ I do need pwm to control speed of the motors. and the pins I have are 3,5,6,9,10,11 on the Nano.. Pin 11 is already in use by the radio receiver.. leaving me with 3,5,6..

The RX_PIN doesn't need to be on pin 11. So you could use that one and pin 3 for the motors, instead of 9 and 10.


text:
Compile Error for Arduino Mega
I am using the Arduino IDE 1.6.0,
There is a project that has compiled both for Due and Mega on another computer. But on my machine, it only compiles for Due. When compiling  for "Mega or Mega 2560", I get the following error:

/Arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld: skipping incompatible /Arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/lib/libc.a when searching for -lc
      /Arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld: cannot find -lc
      collect2: error: ld returned 1 exit status
      Error compiling.

My newbie guess is something is wrong with AVR libraries. But how to solve it? Also could someone please explain what -lc is, which cannot be found? At first glance it looks like an option.

tldr; -lc means "link with the libc.a library"
The compiler takes your source code (*.c, *.ino) and produces "object" files ending in *.o.
The linker takes those compiled modules and links them all together to make the final executable, linking symbols in one file (such as variable references and function calls) with the definitions in the others (the actual variables and functions). But it also takes libraries - predefined collections of object files - and links those in as well, if necessary.
Libraries are files of the form lib*.a (a is for "archive"), and are distributed by software vendors as easy containers for their modules. The compiler/linker itself also uses them as the implementations for languages features such as printf() and digitalWrite(). The most fundamental library is libc.a - the library containing the standard C implementation.
When you want to get the linker to use a library, you give it the -l option, with the library name appended (not including the lib prefix and .a extension). In short, -lc means "link with the libc.a library".
But if your development machine has support for numerous processors, there will be a number of libc.a files on it - how does the linker know where to look? Another linker option is -L (note uppercase), which defines the directories to look in to find libraries. The linker will look through the directories in turn until it finds the referenced library.
If you attempt to link modules that have been compiled for different processors, you will get linker errors when it does a sanity check. The reason your fix worked is because it now uses the correct directories to find what it is looking for.

I think you have included some libraries in the sketch. The problem is that one of the libraries doesn't support the Arduino Mega.
As a solution, I suggest you to comment out the libraries one by one and then try to compile the program. If code runs successfully,try to install that library with other versions. Don't forget to remove the previous library.

So what I did that solved the problem was, I downloaded the latest Arduino IDE, titled "Windows ZIP file for non admin install". Then I unzipped the download, and I copied all of the files of the new IDE and pasted them into the old installation. But I did not replace anything. i.e. For each file that existed, I kept the old file.
~400 new files were copied. Now it compiles without error.
BTW since this has been a blind workaround, I will not accept this as the final answer.

What was the point of copying one version over the top of another version? Why didn't you just upgrade to the new version instead?

All i remember right now is that the newest update at the time had compatibility issues. I don't remember what it was. That's why I tried to keep the older files.

authors: عبدالغني الرباعي


text:
How to run stepper motor at its maximum speed
I am running a stepper motor using arduino and IC l293d. What is the maximum possible speed of rotation that I can achieve with the IC and what should be the applied voltage for the same? Earlier, I got the optimum rotation with a step size of 30 at 7V. I want to increase the step size. What should I do?

I want to increase the step size. What should I do? - Change the motor for one with a bigger step size. The step size is a function of the motor - how far it moves with each step - not a function of voltage, current, software, cheese...

If you are asking these types of questions you might consider using an H bridge and a DC motor in place of the stepping motor controller and stepping motor..

It would be informative to review the numerous stepper motor questions at electronics.stackechange.com (do not post another) and the many online resources which explain this.

As this link states:

Stepper motors are normally used for positioning, and are not known
  for their speed.

However, the link is to an on line stepping motor speed calculator.
As for the size of the step, this is a function of the way the stepping motor is built.  Some controllers / stepping motor combinations can do half steps or micro steps.  Disable these feature for the fewest number of steps per revolution.
These are some of the basic concepts which deal with practical stepping motor applications.  As speed increases, other factors come into play.  For example, resonance and inductance.
In this paper resonance is discussed:

If a rigidly mounted stepping motor is rigidly coupled to a
  frictionless load and then stepped at a frequency near the resonant
  frequency, energy will be pumped into the resonant system, and the
  result of this is that the motor will literally lose control.

The paper also discusses the effect of the stepper motor's coil inductance:

An important consideration in designing high-speed stepping motor
  controllers is the effect of the inductance of the motor windings. ...
  The inductance of the motor winding determines the rise and fall time
  of the current through the windings. ...

The speed of the stepper motor (assuming you measure it in RPM) will depend on many factors. I am not sure how the "30 step size at 7V" you mention is relevant.
IMHO, the most important parameters are
1) physical parameters of motor (steps per revolution, rated voltage, motor intetia)
2) Load on the motor
3) software implementation
Normally you shouldn't be able to affect 1( if you are looking like most arduino's developers you should be looking at things like this. i.e. 200 steps per revolution, 5-12VDC and a few tens to hundreds of g*cm^2 or motor inertia.) or 2 (although with higher loads lower velocities can be achieved, normally you select the motor based on the load and not vice versa).
Therefore you are left with Software implementation. Things here can get messy very quickly depending on how experienced you are and what you want to do.
e.g. The arduino Stepper library is simple and you can set parameters but it is blocking (i.e. you can't do anything else until movement is completed, or interrupts are used).
If you want to get your hands dirty (and your head messed up ;-/ ) you can looks at

Arduino timers
micros(), and millis() for updating the steps yourself. (Have a look at here and here - shameless plug)
pin registers (for increasing speed) here.

My experience is that normally you can get up to 150 [rpm] easily. Theoretically you should be able to go higher but the uC should be doing pretty much nothing else.


text:
How do I reset an ESP8266 with an FTDI and no reset button?
How do I reset an ESP8266 with an FTDI and no reset button? I assume that it has something to do with the reset pin on the ESP8266, but I cannot find a step-by-step usage of the pin online.

There is both a "reset" and a "program" pin on the ESP8266. You need both to reprogram it.

But how specifically do I reset it?

there are lots of different esp8266 boards, and several kinds of modules. Which one in particular?

also, are you asking how to do it under program control?

https://www.sparkfun.com/products/13678

No, just how to do it manually.

Pull the reset pin up by connecting it to 3.3v with a 10k ohm resistor, then to reset the ESP you temporarily ground the pin, bringing it down to 0v/GND.
I'd recommend putting in a button for that :)


text:
How to include <SPI.h> outside the .ino file
As I understand, Arduino IDE considers two paths for the libraries:
first,

"C:\Program Files\Arduino\libraries"

and second, the "libraries" folder next to the schetchbook.
I have a configuration.h file, that I include in the main file, Test.ino, like this:
#include <configuration.h>

and in the configuration.h file I try to include SPI.h like this:
#include <SPI.h>

But I get the following error:
fatal error: SPI.h: No such file or directory

It seems that I am obliged to include SPI.h only from the ino file. But why?
And how can I do what I want here? do I have to change IDE?
P.S: the software is large and I am improving maintainability.

It seems that I am obliged to include SPI.h only from the ino file. But why? And how can I do what I want here? do I have to change IDE?

The background is how the Arduino IDE pre-processor works together with the GCC AVR compiler and build tools.
The compiler needs to know the include path to the libraries. This is created by the pre-processor by scanning the ino file and searching the known libraries. A compiler command line is built with the include paths to the located libraries.
If you move the library includes to a configuration file the IDE pre-processor will not be able to locate the libraries and create the include paths. The pre-processor does not recursively scan library files.
Cheers!

Any references for this info?

The wiki https://github.com/arduino/Arduino/wiki/Build-Process gives a hint.

See my answer How the IDE organizes things. There is no easy way to avoid having to put an include in the main .ino file, unless you write your own build process (or perhaps use another toolchain).
I think you could put SPI.h (and other things, like Wire.h) in the main .ino file, even if they aren't used due to your configuration parameters. The linker would strip them out because the modules were not referenced.

The IDE has to be explicitly told each and every library that you use. It also has to be told each and every library that every library that you use uses. And so on.
The Arduino IDE only looks in the INO files. As a result: if the library is not included in the main INO file then the IDE doesn't know that you intend to use it, and so it doesn't look for it.
Only when it's in the INO file will the IDE actually look for where that library is located and append the right flags (-I...path...) to the compilation commands to be able to get at the files for it.
Further, it is only then that it actually knows that it should compile the source code for a library. Without that knowledge, even if you explicitly point to the header file with a relative path, the IDE won't know that it should compile and link the source code.
There is no way around it, it's just the way the IDE works. The only option is to change to a different IDE that has more intelligence and can recursively deep-scan the libraries to maintain a list of prerequisites (such as my popular UECIDE IDE).

I'm not fully agreeing here. It is a decision of the arduino core team to only scan the ino files for libraries.There have been several issues raised to fix this. I do agree that the PO should consider another IDE. I however would advice to use arduino eclipse plugin called sloeber that can be found at sloeber.io.

@jantje Only because you wrote it. At least I have the good grace to mention that UECIDE is mine. If you advise someone to use something you have created you should mention that it is your product.

Sorry I forgot. As it was you I assumed that you knew (which you do) and I forgot to mention (for the other readers) that I do develop the arduino eclipse plugin named sloeber. I think people should use the ide of their choice and choice is a good thing. So I didn't mean I do not fully agree with the IDE you propose. I probably should have done a edit :-(


text:
does eeprom_write_block function of avr.eeprom.h writes a NULL terminated string or we have to manually null terminate it
http://www.nongnu.org/avr-libc/user-manual/group__avr__eeprom.html
I am trying to figure out that if we use eeprom_write_block function or eeprom_update_block function do we need to manually null terminate it?
I came across this tutorial on avr-freaks where in one comment it is said that you have to read the strings and null terminate them but there is no word about writing. Couldnt get anything the avr-libc manual as well.
UPDATE
I have reserved some parts of eeprom using EEMEM  and they are strings. I am not sure how long the string would be except that it would be smaller than a max value. Now When I would read the string back from the eeprom I would just be reading the maximum number of bytes as again I would have no idea of the size of the string. If the eeprom has a null value at the end of the string when writing to it, the read string will have that null at the correct place.
Situation
I am saving mobile numbers of users as:
uint8_t EEMEM users[numberOfUsers][maxChar4Number];

Now when I get a number parsed and then save it to eeprom
#define eepu(message, EEADDR, BLKSIZE) eeprom_update_block((const void *)message, (void *)EEADDR, BLKSIZE);

eepu(user, users[0], strlen(user)); //strlen(user) will be less than the maxChar4Number

This will write the number to eeprom. When I read the i would be reading maxChar4Number bytes and a number could have been shorter than that length.

If you write a block which happens to be null-terminated, then reading it back should be fine. I do that when I want to save a filename in EEPROM. Just declare a suitable length (allowing room for the null terminator) and write the entire block to EEPROM.

Since one normally does not know how long a character string is, we need a way to convey this information.  One technique used to avoid confusion is to add a NULL character (which is a zero) to the end of the string.  Another is to explicitly state how long the string is.
In the case of the function eeprom_write_block() talked about here, we see that we are formally passing not only a pointer to the string but also the size of the string.

I am using   eeprom_read_block((void*)&settings, (void*)0, sizeof(settings));. it has the size argument . do I need to Null terminate??

I have reserved some parts of eeprom using EEMEM  and they are strings. I am not sure how long the string would be except that it would be smaller than a max value. Now When I would read the string back from the eeprom I would just be reading the maximum number of bytes as again I would have no idea of the size of the string.

I would think you do not need a NULL at the end of your character string for the eeprom_read_block() method as you are telling it how many characters you are reading.  I don't think you need it for the sizeof() method call either as sizeof() uses the type of the argument.  That said, I believe you will always read the size of your array number of characters from EEPROM.  Is that what you want?


text:
Controlling a NC connection from two sources?
I'm trying to control a garage door opener. The button that lets you open the door from the inside is a NC connection (press the button and it goes to "open" and makes the motor run).
I want to keep that AND add another source (an Arduino w/ an RF module) that taps in to this.
Is there some sort of splitter I'd add to the garage door button wires to do this?

Just add the arduino switch in series with the button.

Are you certain that your existing circuit is NC?
The typical garage door opener button is a momentary switch. Many third party remote devices, including two that I have installed, tap directly into this circuit. Because the contacts short across the existing switch, activating one, two or three is insignificant. These switches are connected in parallel.
It would be a good idea to use an external isolation circuit to the Arduino, either a relay or SSR in order to ensure that there is no "injected" power from your circuit to the garage door circuit.
If your circuit is indeed an NC type, you would connect your new relay or SSR in series, using the device's NC connections. The locations for tapping into the circuit would be where your existing button resides or where those two wires engage your garage door mechanism.
I suppose my older garage door opener is NO, while newer models would use a different architecture, aka NC.