text:
Change UART pin
I am developing GPRS HTTP send request code using a GSM/GPRS module. I found the following code via google:

/*************************************************************************
* SIM800 GPRS/HTTP Library
* Distributed under GPL v2.0
* Written by Stanley Huang <stanleyhuangyc@gmail.com>
* For more information, please visit http://arduinodev.com
*************************************************************************/

#include <Arduino.h>

// change this to the pin connect with SIM800 reset pin
#define SIM800_RESET_PIN 7

// change this to the serial UART which SIM800 is attached to
#define SIM_SERIAL Serial

// define DEBUG to one serial UART to enable debug information output
//#define DEBUG Serial

typedef enum {
    HTTP_DISABLED = 0,
    HTTP_READY,
    HTTP_CONNECTING,
    HTTP_READING,
    HTTP_ERROR,
} HTTP_STATES;

typedef struct {
  float lat;
  float lon;
  uint8_t year; /* year past 2000, e.g. 15 for 2015 */
  uint8_t month;
  uint8_t day;
  uint8_t hour;
  uint8_t minute;
  uint8_t second;
} GSM_LOCATION;

class CGPRS_SIM800 {
public:
    CGPRS_SIM800():httpState(HTTP_DISABLED) {}
    // initialize the module
    bool init();
    // setup network
    byte setup(const char* apn);
    // get network operator name
    bool getOperatorName();
    // check for incoming SMS
    bool checkSMS();
    // get signal quality level (in dB)
    int getSignalQuality();
    // get GSM location and network time
    bool getLocation(GSM_LOCATION* loc);
    // initialize HTTP connection
    bool httpInit();
    // terminate HTTP connection
    void httpUninit();
    // connect to HTTP server
    bool httpConnect(const char* url, const char* args = 0);
    // check if HTTP connection is established
    // return 0 for in progress, 1 for success, 2 for error
    byte httpIsConnected();
    // read data from HTTP connection
    void httpRead();
    // check if HTTP connection is established
    // return 0 for in progress, -1 for error, bytes of http payload on success
    int httpIsRead();
    // send AT command and check for expected response
    byte sendCommand(const char* cmd, unsigned int timeout = 2000, const char* expected = 0);
    // send AT command and check for two possible responses
    byte sendCommand(const char* cmd, const char* expected1, const char* expected2, unsigned int timeout = 2000);
    // toggle low-power mode
    bool sleep(bool enabled)
    {
      return sendCommand(enabled ? "AT+CFUN=0" : "AT+CFUN=1");
    }
    // check if there is available serial data
    bool available()
    {
      return SIM_SERIAL.available();
    }
    char buffer[256];
    byte httpState;
private:
    byte checkbuffer(const char* expected1, const char* expected2 = 0, unsigned int timeout = 2000);
    void purgeSerial();
    byte m_bytesRecv;
    uint32_t m_checkTimer;
};

The problem is I have no idea how to change or define Rx and Tx Pin. If I define SIM_SERIAL serial1 it's showing me error. I want to change it to pins 10 and 11.
Here is other code whenever I try to compile it shows me error on "serial1" online. above code is sim800.h file
here is program code of send data through http
"SIM800.h"

#define APN "connect"
#define con Serial
static const char* url = "http://arduinodev.com/datetime.php";

CGPRS_SIM800 gprs;
uint32_t count = 0;
uint32_t errors = 0;

void setup()
{
  con.begin(9600);
  while (!con);

  con.println("SIM800 TEST");

  for (;;) {
    con.print("Resetting...");
    while (!gprs.init()) {
      con.write('.');
    }
    con.println("OK");

    con.print("Setting up network...");
    byte ret = gprs.setup(APN);
    if (ret == 0)
      break;
    con.print("Error code:");
    con.println(ret);
    con.println(gprs.buffer);
  }
  con.println("OK");
  delay(3000);

  if (gprs.getOperatorName()) {
    con.print("Operator:");
    con.println(gprs.buffer);
  }
  int ret = gprs.getSignalQuality();
  if (ret) {
     con.print("Signal:");
     con.print(ret);
     con.println("dB");
  }
  for (;;) {
    if (gprs.httpInit()) break;
    con.println(gprs.buffer);
    gprs.httpUninit();
    delay(1000);
  }
  delay(3000);
}

void loop()
{

  char mydata[16];
  sprintf(mydata, "t=%lu", millis());
  con.print("Requesting ");
  con.print(url);
  con.print('?');
  con.println(mydata);
  gprs.httpConnect(url, mydata);
  count++;
  while (gprs.httpIsConnected() == 0) {
    // can do something here while waiting
    con.write('.');
    for (byte n = 0; n < 25 && !gprs.available(); n++) {
      delay(10);
    }
  }
  if (gprs.httpState == HTTP_ERROR) {
    con.println("Connect error");
    errors++;
    delay(3000);
    return;
  }
  con.println();
  gprs.httpRead();
  int ret;
  while ((ret = gprs.httpIsRead()) == 0) {
    // can do something here while waiting
  }
  if (gprs.httpState == HTTP_ERROR) {
    con.println("Read error");
    errors++;
    delay(3000);
    return;
  }

  // now we have received payload
  con.print("[Payload]");
  con.println(gprs.buffer);

  // show position
  GSM_LOCATION loc;
  if (gprs.getLocation(&loc)) {
    con.print("LAT:");
    con.print(loc.lat, 6);
    con.print(" LON:");
    con.print(loc.lon, 6);
    con.print(" TIME:");
    con.print(loc.hour);
    con.print(':');
    con.print(loc.minute);
    con.print(':');
    con.println(loc.second);
  }

  // show stats
  con.print("Total Requests:");
  con.print(count);
  if (errors) {
    con.print(" Errors:");
    con.print(errors);
  }
  con.println();
}

i already know how to send data through http using AT command and software serial library here is  my code
#include <SoftwareSerial.h>

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

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.write("AT\n");
  delay(1000);
  mySerial.write("AT+CSQ\n");
  delay(1000);
  mySerial.write("AT+SAPBR=3,1,\"APN\",\"internet\"\n");
  delay(2000);
  mySerial.write("\nAT+SAPBR=1,1\n");
  delay(1000);
  mySerial.write("AT+HTTPINIT\n");
  delay(1000);

}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
    delay(1000)
    serial.print(enter key)
  }
  if (Serial.available()) {
    delay(2000);
     mySerial.write("AT+HTTPPARA=\"URL\",\"http://www.mydomain.in/index.php?dt=testdata\"\n");
     delay(2000);
     mySerial.write("AT+HTTPACTION=0\n");
      delay(2000);
      mySerial.write("\n");
    mySerial.write(Serial.read());
  }

In this code I define Rx Tx (UART)pin. Can you please suggest me any idea how can i define RX Tx pin in sim800.h file. because serial1 give me error on compiling time

That doesn't look like your code.

yes i said i found code on google

How would you possibly expect us to be able to tell you what to change it to without seeing any of your code?

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

Well there you are.
#define SIM_SERIAL mySerial

thank you. should i add SoftwareSerial mySerial(10, 11); // RX, TX code in sim800.h file  above #define SIM_SERIAL

I think Serial1 has to do with the Hardware serial Port(tx1,rx1) on Arduino mega . But since you are not using Serial.print i suggest you try "Serial/Serial0" if you are using UNO.
If you want (10,11) like you said then i think you should use Softwareserial
 #include SoftwareSerial.h //check spelling online not sure
SoftwareSerial allex(10,11);
 #define SIM_SERIAL  allex
 try it and see if it works.

should i change #define con Serial also..

i set default serial port using only serial declaration but default RX and TX pin not working

I change sim800.h code "#define SIM_SERIAL mySerial" to "#define SIM_SERIAL Serial'


text:
What's the difference between pow and sqrt in this code?
I'm not the best at Arduino so I'm sorry for my "noobiness".
I'm extending some code that I found online to work on the gyroscope that I'm building.
I'm wondering what the difference is between pow and sqrt in this code.
I'm also wondering what the 180/pi is used for. I haven't gotten my mind around this part yet.
arx = (180/3.141592) * atan(ax / pow((ay, 2) + pow(az, 2));

What's the difference here?
ary = (180/3.141592) * atan(ay / sqrt(square(ax, 2) + square(az, 2)));

pow(x, 2)  is the second power, so x² or x*x. sqrt(x) is the square root of x, so $\sqrt x$. A whole circle is 360 degrees or 2π when measuring in radians. So this ratio of 180/3.141592 is used to convert an angle in radians to an angle in degrees.

@Gerben That should be an answer, n'est pas?

@Gerben Do you know why im getting this error?                                                              In function 'void loop()':
error: too few arguments to function 'double pow(double, double)'
GettingValues:41: error: at this point in file
error: too many arguments to function 'double square(double)'
GettingValues:42: error: at this point in file
error: too many arguments to function 'double square(double)'

Your parentheses are wrong. Change pow(( to pow(.

Converting Gerben's comment into an answer:

pow(x, 2) is the second power, in other words:

sqrt(x) is the square root of x, that is:

A whole circle is 360 degrees or 2π when measuring in radians. So this ratio of 180 / 3.141592 is used to convert an angle in radians to an angle in degrees.

source: Stack Exchange

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

sort: votes


text:
USB detect on Arduino DUE
I want to know when something is connected to USB port by blinking an LED.
I suppose have to check PB10 UOTGVBOF, but how to do this ?

What I'm going to say is probably not the most efficient way to do it, but it should work: if your DUE is used as gadget and you wnat to detect the presence of a master, connect a GPIO to the +Vcc line of the usb port and either poll or program an edge triggered interrupt to detect when the line goes high.

Got it working by testing some internal registers state. Thanks for the reoly though

@Siddharth Would you care to put your solution as an answer.  It'll help others who come by later with the same question.  Regards,

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


text:
Help choosing servo motor for Arduino crane
I'm building an automated Arduino crane where the base material is PVC pipes. The arm consists of the picking mechanism and other sensors, so the total arm might come to about 2-3 Kg (I haven't built it yet).
Can you please suggest to me an appropriate make/model of servo motor which I can purchase (preferably from India only)?

It really depends on where you are placing the servo, how much peak load & at what kind if distance from the servo.
These Corona servos are capable of lifting 2-3Kg at a distance of 2cm from the servo centre. (look at the torque entry on the specification sheet)

Thanks, I actually went ahead using a normal 10 RPM motor and stopped it when an object was detected. It is quite accurate


text:
Arduino IDE says fcould not convert 'pinMode(buttons[((inti)], 0u)' from 'void' to 'bool'. How do I fix
Alright, so this code is for a game that is a power source connected to 6 buttons at ports 1, 2, 9, 11, 12, and 13. These are consequently supposed to light up 6 LEDs, each connected to 1. If you press the buttons in the right order, all the LEDs blink at once. Does it work?
#define DEBOUNCE 10  // button debouncer, how many ms to debounce, 5+ ms is usually plenty

// here is where we define the buttons that we'll use. button "1" is the first, button "6" is the 6th, etc
byte buttons[] = {1, 2, 9, 11, 12, 13}; // the analog 0-5 pins are also known as 14-19
// This handy macro lets us determine how big the array up above is, by checking the size
#define NUMBUTTONS sizeof(buttons)
// we will track if a button is just pressed, just released, or 'currently pressed'
volatile byte pressed[NUMBUTTONS], justpressed[NUMBUTTONS], justreleased[NUMBUTTONS];

void setup() {
byte i;

// set up serial port
Serial.begin(9600);
Serial.print("Button checker with ");
Serial.print(NUMBUTTONS, DEC);
Serial.println(" buttons");

// pin1 LED
pinMode(1, OUTPUT);

 // Make input & enable pull-up resistors on switch pins
 for (i=0; ipinMode(buttons[i], INPUT);
 digitalWrite(buttons[i], HIGH);
  }

 // Run timer2 interrupt every 15 ms
 TCCR2A = 0;
 TCCR2B = 1<<CS22 | 1<<CS21 | 1<<CS20;

 //Timer2 Overflow Interrupt Enable
  TIMSK2 |= 1<<TOIE2;

 }

SIGNAL(TIMER2_OVF_vect) {
check_switches();
}

void check_switches()
{
  static byte previousstate[NUMBUTTONS];
static byte currentstate[NUMBUTTONS];
 static long lasttime;
 byte index;

  if (millis() // we wrapped around, lets just try again
     lasttime = millis();
  }

  if ((lasttime + DEBOUNCE) > millis()) {
    // not enough time has passed to debounce
return;
  }
  // ok we have waited DEBOUNCE milliseconds, lets reset the timer
  lasttime = millis();

  for (index = 0; index digitalRead(buttons[index]);   // read the button

    /*
    Serial.print(index, DEC);
    Serial.print(": cstate=");
    Serial.print(currentstate[index], DEC);
    Serial.print(", pstate=");
    Serial.print(previousstate[index], DEC);
    Serial.print(", press=");
    */

    if (currentstate[index] == previousstate[index]) {
      if ((pressed[index] == LOW) && (currentstate[index] == LOW)) {
          // just pressed
          justpressed[index] = 1;
      }
      else if ((pressed[index] == HIGH) && (currentstate[index] == HIGH))        {
          // just released
          justreleased[index] = 1;
      }
      pressed[index] = !currentstate[index];  // remember, digital HIGH     means NOT pressed
    }
    //Serial.println(pressed[index], DEC);
    previousstate[index] = currentstate[index];   // keep a running tally  of the buttons
  }
}

void loop() {
  for (byte i = 0; i if (justpressed[i]) {
      justpressed[i] = 0;
      Serial.print(i, DEC);
      Serial.println(" Just pressed");
      // remember, check_switches() will CLEAR the 'just pressed' flag
    }
    if (justreleased[i]) {
      justreleased[i] = 0;
      Serial.print(i, DEC);
      Serial.println(" Just released");
      // remember, check_switches() will CLEAR the 'just pressed' flag
    }
    if (pressed[i]) {
      Serial.print(i, DEC);
      Serial.println(" pressed");
      // is the button pressed down at this moment
    }
  }
}

int questionNumberArray[] = {1, 2, 9, 11, 12, 13};//the array itself
const size_t n = sizeof(questionNumberArray) / //the array used
sizeof(questionNumberArray[0]);//the base of the array

for (size_t i = 0; i < n - 1; i++) //the loop itself
{
size_t j = random(1, n - i);
int t = questionNumberArray[i]; //integer output for increase
questionNumberArray[i] = questionNumberArray[j];//the value definition
questionNumberArray[j] = t;
pinMode(questionNumberArray, INPUT);
if (digitalRead(questionNumberArray) == HIGH) {
  then(digitalRead(1, 2, 9, 11, 12, 13 == High(3))
  break;
}
}

Also, how do I make it so that people have infinite times to try

int QuestionNumberArray[] = {1, 2, 9, 11, 12, 13};//the array itself - seems related to your other question.

Maybe Mr. Google will help you: Fairly Simple Simon – an Arduino memory game for 4 LEDs and 4 switches

There is very little about the code you are producing at the moment that could be classified as "right".
You are like a child who has been playing with LEGO® being let loose on the workings of a nuclear reactor.  You're sticking things together without a) knowing what they do and b) knowing how they are supposed to work, and it's all going to end in tears.
I suggest that, for the time being, you forget this game project of yours and go back to the basics.  Start by learning how to make an LED light up when you press a button.  That will teach you both how to read the state of a button and how to control an LED.  Then move on to doing it with multiple LEDs and multiple buttons.
As it stands you are just going to end up getting frustrated and annoyed.  You're asking questions without either knowing just what it is you are asking or how to understand the answers when you are given them.  And that is going to end up reflecting badly on the rating of your various users (hint: if you ask reasonable questions you get reasonable answers, and that means upvotes and reputation, which then means you can ask more questions so you don't have to keep creating new users to ask more questions where you don't actually understand what you're asking).

If only this "game project" wasn't an assigment due to be handed in tomorrow.

@CharlieHanson Sometimes you have to be cruel to be kind.  If someone just jumps in at the end of a project at the last minute without doing any of the preliminary research then they're doomed to fail.  After a few repeats they may finally learn. When you do a project on a piece of equipment or in an environment you don't know the first thing to do is learn how to use it. Only then can you even begin to consider doing anything more complex than blink an LED or print "Hello World".

I'm not disputing that, I was simply adding that this project has been mandated rather than willingly chosen.

@CharlieHanson That's still no excuse for not starting at the beginning of the correct sequence of steps - or maybe paying attention in class instead of playing Candy Crush Saga on his phone...

I was referring to "forget this game project of yours". OP does not have the luxury of time to go back to basics. Never mind, it was a whimsical comment.

@CharlieHanson This is a project which would take about 30 minutes of actual work once you know how to perform the basics.  An evening of learning those basics should be all that is needed.  Without learning those basics the project will fail, so it must therefore be sensible, since there is now nothing to lose, to spend the rest of what time is left trying to learn those basics with the hope of having 30 minutes at the end to actually write the code.  In fact, for someone like you or I probably nearer 10 minutes is needed.

So...can u plz use the 10 minutes to write it to make it work then? just this once?

I agree with Majenko. Forget this game and learn how to code in C. If you don't know, and want us to write your code for you, then you will be fraudulently passing this test. Even if you don't care about that, someone will, one day. Imagine your teacher asks you a simple question about the code: "why did you do X?".  Your complete inability to explain the code, or modify it, will expose that someone else wrote it.

regardless of the convincing nature of your argument, the idea is pass now, learn later. I realize that this is far from good, but, hey, it's all that can  work now. However, if not acceptable, can you at least tell me what I missed?

"can you at least tell me what I missed?" @errr About 6 lectures by the sound of things.  We are not going to do your work for you.

the teacher has not taught anything. He said cheating is fine, if you know where to look. It's digital electronics, he doesn't know anything at all, in fact even less than  me, about arduino ide @majenko

how is telling me I missed 6 lectures useful@majenko

Instead of posting your question four or five times here, how about using the time on your hands constructively by learning some coding? The IDE comes with examples. There are lots of web sites about how to program in C. No-one will want to do your homework for you. the teacher has not taught anything. He said cheating is fine - especially now.

how is telling me I missed 6 lectures useful ... He said cheating is fine  - how is cheating useful? You pass a course by cheating? Does that mean you then design an aircraft without knowing what you are doing because you cheated your way through the course? Please supply your teacher's name so we can write to his supervisor. That teacher should be sacked. If you are telling the truth, that is. Which I doubt.


text:
Issue with leOS2 for one-time tasks
I'm trying to use the last version of leOS2 scheduler from Leonardo Miliani ( https://github.com/leomil72/leOS2 ) but I have a strange behavior with a very simplistic ONETIME task.
Platform : Arduino Uno clone, so Atmel Atmega 328P CPU.
My code is very straightforward :
#include "leOS2.h"
leOS2 myOS; //create a new istance of the class leOS

bool test = true;

void setup()
{
    myOS.begin(); //initialize the scheduler
}
void loop()
{
    // Do some stuff ...

    if(test)
    {
       DoAndUndo(3000);
       test = false;
    }
}

void DoAndUndo(unsigned long duration)
{
    doSomething();

    myOS.addTask(cancelTheThing, myOS.convertMs(duration), ONETIME);
}

void doSomething()
{
    Serial.println("thing on");
}

void cancelTheThing()
{
    Serial.println("thing is off");
}

In case it can be some kind of conflict, my code also relies on the following :
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <IRremote.h>

The problem is :
        myOS.addTask(cancelTheThing, myOS.convertMs(duration), ONETIME);
is supposed to call asynchronously the "cancelTheThing" method 3 seconds later, and for only one time, and then forget it.
But for an unknown reason, it's called after the expected delay, but it loops infinitely on this method ! In the example case above, my serial stream is filled with a lot of "thing is off" messages, and the µc is unresponsive to anything apart a reset.
The call to DoAndUndo() will produce a such like output :
 thing on

And 3s later, in a very fast infinite loop :
 thing is off
 thing is off
 thing is off
 thing is off

If I remove the "ONETIME" flag, the task is called every three seconds (exactly as it's suppose to do, so the scheduler works, but it's not what I want in my use case).
note : As a try of workaround, I've tried some tricks like calling haltScheduler() inside my cancelTheThing() and reenable it with restartScheduler() in DoAndUndo(), and also tried to call removeTask once it has ran, but it didn't help.
Thank you for your help

There appears to be a fault with the library whereby if the only registered task is a one-shot task it doesn't get cancelled when it has executed.
Adding another periodic task in setup() (say to blink an LED every 500ms) so there are now 2 tasks instead of one works around the problem.
The way the system is written it will always try an execute task number 0 even when there are 0 tasks registered because they erroneously used a "do {...} while" construct instead of a "while { ...}" construct.

I  have filed a bug report, corrected the error, and raised a pull request with the fix in it.  Until it gets accepted you can obtain the fixed version here: https://github.com/majenkotech/leOS2

Hello, thanks to have answered but it's not the solution. The above sample was not accurate (I've edited it, sorry for the lack of precision). The "infinite loop" issue I encounter effectively comes from the scheduler as I explained, not a such trivial issue as you thought. If it was a so simple mistake, my "doSomething" method would have loop too...

@AFract If you want our help you will have to provide a piece of code that compiles and executes exactly as shown and demonstrates the problem. An approximation is of no use at all.

And the one in first post should be ok. The original code was only slightly different, i just add an "if" to show that the true one doesn't do what you thought. And even without it, the explanation below it were already enoughly clear to make you figure your answer cannot help to fix the issue.

@AFract What you write below your code describes precisely what I would expect from the original code you posted. Now you have changed the code so it doesn't compile it is of no use at all.  What is "test"?

It's an EXAMPLE. What you need to focus on is : When i call "DoAndUndo(3000);" ONE time it continuously executes cancelTheThing() instead of just calling it once, as the ONETIME flag passed to the scheduler should do. Exactly like explained in the post content.

With your ORIGINAL code I would expect that to happen since the way it was written you were CONSTANTLY creating the task over and over again.  Now with this code it's not the case because you added something that hasn't been defined.  WITHOUT KNOWING WHAT THAT IS WE CANNOT HELP YOU!!!

The question was clear, the code sample is here to illustrate the use I do of leOS. Maybe if you had read it instead of posting ironical-useless answers like "Here's a hint... What do you think the name of this function signifies...?", you'd have notice it. To be kind with you, I changed the sample to make it build and behave "as you want" till the part with the scheduler. To be clear : the problem does not look to be in the algorithm, it's in the behavior of the scheduling lib.

It's NOT "to keep me happy"!  It is to make it physically possible for us (NOT JUST ME) to HELP you!  Quite frankly, to be brutally honest, I really don't know if I can be bothered now.  You probably won't listen to the answer because apparently you already know everything!

@AFract Incidentally, you clearly haven't even tried running the code you have posted, since it still CAN NOT work.

I can't upload it right now to the Arduino (I don't have it here) but it builds well for me. But the point is really simple :     "myOS.addTask(cancelTheThing, myOS.convertMs(duration), ONETIME);" doesn't do what its documentation suggests : instead of calling cancelTheThing one time, it locks up in infinite loop. If the original author of the lib or somebody who knows it well read my msg, he could probably have an hint about the problem.

@AFract Now that I have re-written your program so that it actually works, I can replicate your results - something that I couldn't have done before.  Now I can actually analyse the problem and find the cause.

I didn't "rewrite" it and I didn't change the example since 20 minutes. But nevermind, thanks for your help and your efforts. I'm glad to see you meet the same issue than me, even on a so simple example.

No, I had to re-write it.  I have traced the problem and found a workaround for it - I have also corrected the underlying problem and raised a bug report and pull request with the repository.  More info in my answer.

Wow ! great work of debugging. I'll try it ASAP, I hope your pull request will be accepted. I'll tell you if it's effectively ok with your little change.


text:
Error while compiling
I made a code which can send the message to the entered phone number while it receieves a specific message or when the push button is pressed.
but it is showing the error that 'smsReceivingFunction' was not declared in this scope.
I'm a beginner and don't know what i'm doing wrong.
to know the working of functions of library--
http://1sheeld.com/docs/sms/#example
here is the code--
#include <OneSheeld.h>
float lat ;
float lon ;
char charlat [30];
char charlon [30];
char readings [150];
int buttonPin=11;
int ledPin=12;

void setup() {
  // put your setup code here, to run once:
  OneSheeld.begin();
    /* Set the button pin as input. */
  pinMode(buttonPin,INPUT);
  /* Set the LED pin as output. */
  pinMode(ledPin,OUTPUT);
  SMS.setOnSmsReceive(&smsReceivingFunction);
}

void loop()

{
    charlat[0] = 0;
  charlon[0] = 0;
  readings [0] = 0;
if(digitalRead(buttonPin) == HIGH)
  {
    /* Turn on the LED. */
    digitalWrite(ledPin,HIGH);
    delay( 1000);
    digitalWrite(ledPin,HIGH);
    delay( 500);

      lat = GPS.getLatitude();
      lon = GPS.getLongitude();
      dtostrf(lat, 3, 7, charlat);
      dtostrf(lon, 3, 7, charlon);
      strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
      strcat(readings, "http://maps.google.com/maps?q=");
      strcat (readings, charlat);
      strcat(readings, ",");
      strcat (readings, charlon);
      SMS.send("+917771914436", readings);

      void smsReceivingFunction(const char * number,const char * text);

       if(!strcmp(number,"+7771914436"))               /* phone number from which you will send the sms "PUT YOURS IN PLACE OF +1234567890" */
      {
        if(!strcmp(text,"?"))
        lat = GPS.getLatitude();
      lon = GPS.getLongitude();
      dtostrf(lat, 3, 7, charlat);
      dtostrf(lon, 3, 7, charlon);
      strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
      strcat(readings, "http://maps.google.com/maps?q=");
      strcat (readings, charlat);
      strcat(readings, ",");
      strcat (readings, charlon);
      SMS.send("+917771914436", readings);
      }
  }

  }
}

If course it says its undefined. How could it say otherwise? Maybe you should actually define and write the function.

Basically the formatting and layout of your program is completely wrong.  You haven't actually defined this smsReceivingFunction anywhere.  You have created a prototype to it part way through your loop() function, but not created the actual function.
You should learn to strictly indent your program properly.  It is important, since by doing so you can follow the flow and structure of your program much easier.
For instance, if I pass your program through Artistic Style to attempt to automatically correct your indenting it results in this:
#include <OneSheeld.h>
float lat ;
float lon ;
char charlat [30];
char charlon [30];
char readings [150];
int buttonPin = 11;
int ledPin = 12;

void setup() {
    // put your setup code here, to run once:
    OneSheeld.begin();
    /* Set the button pin as input. */
    pinMode(buttonPin, INPUT);
    /* Set the LED pin as output. */
    pinMode(ledPin, OUTPUT);
    SMS.setOnSmsReceive(&smsReceivingFunction);
}

void loop()
{
    charlat[0] = 0;
    charlon[0] = 0;
    readings [0] = 0;
    if (digitalRead(buttonPin) == HIGH) {
        /* Turn on the LED. */
        digitalWrite(ledPin, HIGH);
        delay( 1000);
        digitalWrite(ledPin, HIGH);
        delay( 500);
        lat = GPS.getLatitude();
        lon = GPS.getLongitude();
        dtostrf(lat, 3, 7, charlat);
        dtostrf(lon, 3, 7, charlon);
        strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
        strcat(readings, "http://maps.google.com/maps?q=");
        strcat (readings, charlat);
        strcat(readings, ",");
        strcat (readings, charlon);
        SMS.send("+917771914436", readings);
        void smsReceivingFunction(const char * number, const char * text);

        if (!strcmp(number, "+7771914436")) {           /* phone number from which you will send the sms "PUT YOURS IN PLACE OF +1234567890" */
            if (!strcmp(text, "?")) {
                lat = GPS.getLatitude();
            }

            lon = GPS.getLongitude();
            dtostrf(lat, 3, 7, charlat);
            dtostrf(lon, 3, 7, charlon);
            strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
            strcat(readings, "http://maps.google.com/maps?q=");
            strcat (readings, charlat);
            strcat(readings, ",");
            strcat (readings, charlon);
            SMS.send("+917771914436", readings);
        }
    }
}
}

As you can now see you have an extra } at the end of your sketch, so your brackets are not balanced. That in itself is a syntax error.  Also you can see your function prototype slap bang in the middle of your loop() function:
...
        SMS.send("+917771914436", readings);
        void smsReceivingFunction(const char * number, const char * text);

        if (!strcmp(number, "+7771914436")) {           /* phone number
...

I think, though of course I can't actually test this since I don't have your hardware, that you really meant to start a new function at that point in your program, and of course that would mean finishing the previous function first: you cannot nest functions inside each other.  So I would guess your program should have looked something more like this:
#include <OneSheeld.h>
float lat ;
float lon ;
char charlat [30];
char charlon [30];
char readings [150];
int buttonPin = 11;
int ledPin = 12;

void setup() {
    // put your setup code here, to run once:
    OneSheeld.begin();
    /* Set the button pin as input. */
    pinMode(buttonPin, INPUT);
    /* Set the LED pin as output. */
    pinMode(ledPin, OUTPUT);
    SMS.setOnSmsReceive(&smsReceivingFunction);
}

void loop()
{
    charlat[0] = 0;
    charlon[0] = 0;
    readings [0] = 0;
    if (digitalRead(buttonPin) == HIGH) {
        /* Turn on the LED. */
        digitalWrite(ledPin, HIGH);
        delay( 1000);
        digitalWrite(ledPin, HIGH);
        delay( 500);
        lat = GPS.getLatitude();
        lon = GPS.getLongitude();
        dtostrf(lat, 3, 7, charlat);
        dtostrf(lon, 3, 7, charlon);
        strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
        strcat(readings, "http://maps.google.com/maps?q=");
        strcat (readings, charlat);
        strcat(readings, ",");
        strcat (readings, charlon);
        SMS.send("+917771914436", readings);
    }
}

void smsReceivingFunction(const char * number, const char * text) {
    if (!strcmp(number, "+7771914436")) {           /* phone number from which you will send the sms "PUT YOURS IN PLACE OF +1234567890" */
        if (!strcmp(text, "?")) {
            lat = GPS.getLatitude();
        }
        lon = GPS.getLongitude();
        dtostrf(lat, 3, 7, charlat);
        dtostrf(lon, 3, 7, charlon);
        strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
        strcat(readings, "http://maps.google.com/maps?q=");
        strcat (readings, charlat);
        strcat(readings, ",");
        strcat (readings, charlon);
        SMS.send("+917771914436", readings);
    }
}

+1 for Artistic Style. I'm sure it'll come in handy when I come across badly formatted code online.


text:
Using random() in a header file
#ifndef FOO_H
#define FOO_H

struct Foo{
  int randInt = random(0, 101);
};

#endif

I have a header file with a struct like above but when I compile I get this error:
'random' was not declared in this scope
How can I use random() in a header file?

Add #include <Arduino.h> like this
#ifndef FOO_H
#define FOO_H

#include <Arduino.h>

struct Foo{
  int randInt = random(0, 101);
};

#endif

The struct is a declaration of a type. You cannot mix it with the initialization. This is how it could be:
In foo.h:
#ifndef FOO_H
#define FOO_H

struct Foo{
  int randInt;
};

extern struct Foo foo;
struct Foo *initFoo(struct Foo *foo_ptr);
#endif

In foo.c:
#include "foo.h"

struct Foo foo;
struct Foo *initFoo(struct Foo *foo_ptr) {
  if (!foo_ptr)
    return NULL;
  foo_ptr->randInt = random(0, 101);
  return foo_ptr;
}

random() is a function and therefore its return value cannot be used as static initializer.
Unless -std=c++11 or -std=gnu++11 are enabled.

It's valid C++ code I don't see why it would be different for an Arduino. The code works fine after I #include <Arduino.h>.

What is the outcome?  Did you try to compile exactly the code you put in your question?

I answered my question and it works as is. The only problem was that random() was defined in my header file so I had to include the Arduino library. Someone commented for me to do but it's gone now, I guess they deleted it.

With gcc, it works only with -std=c++11 or -std=gnu++11.
Probably the Arduino ide turns them on by default.

Maybe so, I didn't actually want to use random() as an initializer (I'm using it in another function within the header) it was just easier to use it in the initializer here (less code to display). It works for me though granted I am using stino with sublime text 3.

Arduino does in fact have -std=gnu++11 by default


text:
Unable to tell if error is from receiving or transmitting end
so I am having trouble sending data using software serial's write function.
TX Code:
#include <SoftwareSerial.h>

SoftwareSerial TX(2,3);

void setup() {
  // put your setup code here, to run once:
  TX.begin(1200);
}

void loop() {
    TX.write(60);
}

Is the delay necessary?
RX Code:
#include <SoftwareSerial.h>
SoftwareSerial RX(2,3); //(rx pin, tx pin)
const unsigned int bufferSize = 100;

void setup() {
  Serial.begin(9600);
  RX.begin(1200);

}

void printBuffer(const uint8_t *serialBuffer)
{
  //print contents of buffer
  for (int i = 0; i<100; i++)
    Serial.println(serialBuffer[i], BIN);
}

void processBytes(const uint8_t value)
{
  static uint8_t serialBuffer[bufferSize]; //buffer to hold values
  static unsigned int startPosition=0;

  if(startPosition < bufferSize)
    serialBuffer[startPosition++] = value;

  else
  {
    printBuffer(serialBuffer);
    startPosition = 0;
  }

}//end of processBytes
void loop() {

  //check if data is available in serial buffer
  while(RX.available())
  {
    //process data
    processBytes(RX.read());
  }
}

If i transmit the number 60, it prints 226 constantly for 2-3 seconds, then prints 60 for a short while, then goes back to printing 226. Am I doing something wrong with my code?
FIRST QUESTION: In the case when startPosition (in the process function) equals 100, it will call print. Print will then print 100 integers. Now, when doing that, there could still be data being transmitted from the transmitter. But the read function won't be executed until printBuffer returns, process returns, and the while loop iterates again. So during that time, couldn't some transmitted values potentially not be read?
SECOND QUESTION How come Software serial doesn't synchronize incorrectly more often? How is it being so accurate if the start bit is just a single bit and it's a 0. So for instance, if payload has some 0s, how come one of those 0s aren't being assumed to be the startbit? How does this get resolved? I looked at the software serial library, but I am not able to find out why. Any guidance here?
THIRD QUESTION Other than getting the startbit syncing right, are there other ways to sync the data? I was reading of NRZ encoding, manchester encoding, etc. Can any of these be implemented here? Also, would it be wise to alter the softwareSerial library to have more than one startbit?
Any guidance would be very appreciated! Thank you so much!
This is all being done with wireless RF modules.

Q2: RS232 serial idles high (aka Mark state). A transition to low (aka Space state) signals the beginning of a frame. It is assumed (read: part of the spec) that the two systems' clocks accurate enough to stay well-enough synced for the duration of a frame.  Q3: There are other serial protocols including synchronous ones, and others could probably be adapted. But what problem are you trying to solve by doing so?

Q2: Sorry I am mistaken, but isn't RS232 for wired connection mostly? And since this is wireless, i believe it idles low? Plz correct me if I am wrong.  I could be mistaken. Also, when transmitting at high speeds, the device doesn't have that much time to "idle" at either state, because the next frame will already begin to  transmit right?

Q3: The reason I am trying to use UART instead of synchronous communication is, synchronous utilizes a clock signal which is constantly being sent, therefore there will be greater battery consumption and the bandwidth might not be fully utilized for the data frame. My end result is to have a very very battery efficient mesh network using RF modules that works efficiently even when placed amidst medium disturbance(using error correction code) and is able to transmit large data packets quickly. I want it to be cost-effective and power-effective. I am demoing it on these modules first.

And since this is wireless, i believe it idles low? - whether or not it is wireless is irrelevant. Why do you believe this?

How come Software serial doesn't synchronize incorrectly more often? How is it being so accurate if the start bit is just a single bit and it's a 0. So for instance, if payload has some 0s, how come one of those 0s aren't being assumed to be the startbit? - because there should be a nice big gap between the start of a transmission (which your sending code does not now have). Assuming you have a gap long enough, the first 0 will be the the start bit, it then clocks in 8 characters, and then the stop bit, which is a 1, which makes sure that you don't mistake it for another start bit.

Once the byte starts being received, any internal 0 bits are not considered start bits. Read my page about serial comms - you seem to not understand the process in general. Also, would it be wise to alter the softwareSerial library to have more than one startbit? - no, because you would then have no alternative but to ignore the second one. You are thrashing around with these suggestions.

I was reading of NRZ encoding, manchester encoding, etc. - certainly there are other ways of transmitting data, remote controls and remote-controlled vehicles use other methods than serial. This now is making this question extremely broad.

The "idles low" comment was w/ respect to the comment by JRobert, and before I actually had some amount of delay in the TX code. But is there a methodical way to estimate exactly how much the delay should be? And for the "longer start sequence" suggestion, I read that often times the start bit is actually a sequence, not just 1 bit. In a separate post, someone told me that exactly. That, typically, it's longer than just a bit.

For the synchronization question, I wanted to get a feel of how to implement such a thing, regardless of if it will be apt. Specifically NRZ encoding. Sorry! I really don't mean to sound ignorant or rude. Please forgive my foolishness. I will do more reading on serial comm.

Also if ample gap is what is required the start bit to be correctly recognized, then why is there the following scenario. I had asked this in a pervious question regarding delays. But to reiterate, when I transmitted with delays of microseconds, it was very low error rate, and delay of 3 or more was more error. And I read your explanation on the error rate based on how long NOP instructions take and the rounding down of the delay time/instruction time. However, based on the comment that you informed me now, shouldn't 3 microsecond delay potentially give better results?

@NickGammon Hello, should i make the above questions a new question?

In a separate post, someone told me that exactly. - where did they say that? Link? The start bit has to be exactly one bit length or the timing of everything else would be out.

should i make the above questions a new question? - your question about Manchester and NRZ vs Serial should be a new question, certainly. And your questions about start bit length seem to me to be another question again. This question started off being about "why doesn't this code work?" and is now morphing into "how does serial comms work, exactly?".

void loop() {
  Serial.println("NEW-------------");
  int x;
  int y[100];
  for(int i = 0; i<100; i++){
    x=RX.read();
    y[i] = x;
  }
...
}

You are reading data without checking if there is any data there. That's like watching the TV without checking if it is turned on. Of course you get weird data.

SoftwareSerial RX(0,1); //(rx pin, tx pin)

Pins 0 and 1 are used by HardwareSerial. Why are you using them for SoftwareSerial?

SoftwareSerial RX(0,1); //(rx pin, tx pin)
...

  Serial.begin(9600);
  RX.begin(1200);

So you initialized HardwareSerial, which now controls pins 0 and 1.
Then you try to initialize SoftwareSerial on those same pins! Would you mind explaining why?
Whatever your explanation is, it won't work.

I've added in the changes you mentioned, but the data still seems to be skewed.

You've changed things, for sure:
 for(int i = 0; i<100; i++){
    if(RX.available())
      x=RX.read();

    y[i] = x;
    }

Let's see. In a loop of 100 iterations you see if anything is available (and if so, put it into x).
Then, regardless of whether or not you got anything you now assign x to y[i]. So, most of the time, y[i] will have garbage in it.

the data still seems to be skewed

Not surprised. Do it differently. Only write to the array if you have data. In fact you may want a complete rework. Read this:
How to read serial without blocking

I have posted the amended code. Change: Only add to the array is data is being read from buffer.

  int y[100];
  for(int i = 0; i<100; i++){
    if(RX.available())
    {
      x=RX.read();
      y[i] = x;
    }
  }

 for (int j = 1; j<=64; j++){
    Serial.println(y[j]);
  }

You still have not fixed it. Let me talk you through what it is doing now.
You are making 100 attempts to read some data. One or two may succeed, and they will be put into the buffer y (funny name for a buffer, right?).
So imagine . is garbage and X is good data, after doing that loop of 100 the buffer will look like this:
........X...........X...........X...X......................X.............................................

So your buffer is still 80% unchanged garbage. Then you print the first 64 elements (why 64 and not 100?) and you get a lot of garbage out. Exactly as expected.

You need to think about what you are doing. Draw it out on a bit of paper, perhaps.
Here is some example code from the page I linked for you, more than once. Please compare:
// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

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

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

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

  switch (inByte)
    {

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

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

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

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

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

    }  // end of switch

  } // end of processIncomingByte

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

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

  }  // end of loop

It seems to be a common misconception that you have to use software serial to talk on the TX and RX pins, and that your computer communicates with the main chip through eTelepathy.  I wish people would read the manual!

Hello sir, so i looked at your forum. At such high baud rates, the read would execute extremely fact but for ProcessIncomeBytes to execute, it would take longer than the speed at which read is reading right? and whwat else should i rework? i fixed the array part.

I don't understand any of that. The read would be faster than the read? If you fixed some code please post the amended code. At 9600 baud I would not be too worried about code execution time.

What I mean is, processIncomingBytes is called and immediately, read is also called. Then the return of read is being sent to procsessIncomingBytes. Now, processIncomingBytes will execute it's algorithm, and during that time, bits are still being sent to the buffer of the receiver. But read is not being called. So isn't there a possibility of some bytes potentially being lost if the buffer goes into overflow? Maybe not for 9600 baud, but what if i had 115200 baud? I have posted the amended code. Change: Only add to the array is data is being read from buffer.

Well, it won't go into overflow if you code correctly. Take a look at my MIDI interpreter demo (video). That is using SoftwareSerial reading at 31250 baud, interpreting it, and outputting the converted output to the screen. You can see from the video it keeps up with very fast MIDI. Please read my link How to read serial without blocking.

See amended reply.

Sorry, I didn't mean to seem like I didn't look at your link. I did look at it, and the other one you posted before hand of how to do serial communication. I just didn't quite understand. Sorry! I will try to learn it again. Thank you for your help!

Also my thinking behind why I am only printing 64 was because, the buffer only holds 64 bytes.

int y[100]; - how can you say it only holds 64 bytes?

In your code, you have up to the first 50 bytes,
then if it's overflow, we empty buffer, or if end line character
is reached, then we process/print bytes. But the 50 bytes could potentially have lots of garbage right? So is the change you're implying in my code, what i have implemented (see modified
question)? Also, there is only 64 byte serial buffer built for the UART built into the chip, which is why i had 64. But I see why that doesn't matter.

@NickGammon I have editted my question.


text:
Reasons why it is not OK to connect a relay directly from an Arduino digital pin
After looking into various schematics on controlling a relay via an Arduino, I have noticed that, most of the time, transistors are used to switch the separate supply into the relay coil rather than directly supplying the relay with the 5-Volt output from the I/O pin of the Arduino. For example, I have a 5-volt DPDT relay and also a small dc motor. I want to drive both directly from my Arduino UNO (SMD clone) with an Atmel328 processor? Would it be advisable to proceed?
If not (most likely):

Can someone give a detailed explanation and might as well important cautions on current limits and stuff?
How can one control such components without risking the Arduino? What are some common means to accomplish this?
What other devices can generally harm an Arduino board (or any microcontroller unit) in a similar manner?

I'm just a beginner who wants to be extremely cautious. Thanks.

Although recently, with my first encounter with Arduino, I used the I/O pins directly to energize a toy dc motor and change its direction by turning a DPDT relay on and off in the same manner. Nothing seems to be amiss by far.

Processor pins have strictly limited current drive capability.

The rated values may vary depending on whether you want a high or low drive.
Some processors will supply only a few mA and the most you will usually officially get is in the 20 to 30 mA range.
There is usually a total current limit for the processor and only a few pins can provide peak current simultaneously.
Processor pins have significant effective resistance and a high voltage will "drop" as increasing current is drawn and a low voltage will rise as load increases. Pins MAY be specific with a maximum short circuit current but at that point a high pin will be pulled low and a low pin will be pulled high so short circuit current has limited applicability.

Even if you have a say 25 mA per pin rated processor the power available is small. 25 mA · 4V say (1V drop on 5V Vcc) = 100 mW. Most motors will take more than that and only very small motors will run well when powered only by a pin.
Electric motors and inductors will generate significantly high voltages when current is interrupted - voltages of tens of volts can easily result and 100+ volts can happen. Connecting a motor of inductor to a processor pin directly is an invitation to destruction. Murphy will often oblige.

A transistor (bipolar or MOSFET) that will drive typical hobby motors costs 10's of cents (or free from scrapped equipment) and allows the port pin current drive to be buffered and "amplified". Use of a transistor or other buffer is an extremely good idea if you have one or a few processors and do not wish them to die semi-randomly.
MOSFET motor driver - from here - section 8.
Voltages and part numbers are for their example - select to suit.
A NPN biploar could be used with the addition of an input resistor to the transistor base.

Bidirectional driver - if you want the driver to be able to drive a load high and low this circuit will work. from here
The input gate is in this case the internal processor driver. The two MOSFET gates connect directly to the processor pin. Vdd should usually be no higher than processor Vmax_drive_out. Slightly higher can be made to work with suitable design. Much higher voltage loads can be driven with this circuit (or similar) plus one extra transistor.

A buffer such as a ULN2803 (and other family members) will drive 8 channels x 500 mA/channel and several can be paralleled.

A ULN2803 is essentially 8 x "Darlington" transistors with emitters connected to a common ground, 8 x "open collector" (unconnected) collectors, and 8 flyback diodes to deal with over voltage spikes (use optional). (There is a ULN280x family with slightly different input characteristics).
This device provides a reasonably priced means of providing 8 x 500 mA pull down drivers. A load connected from an output to V+ is turned on when the input pin is driven high. Once you've used one a few times you'll find them trivially easy to use and very useful. (There is also a ULN200x family with 7 channels per package).
YouTube "how to" video

Driving a stepper motor

Also here

Driving small DC motors - and quite a lot else.

A zillion examples
Digikey - available in 1's if desired $0.72/1, $0.29 in 1000's.
ULN2803 datasheet

For sale at Sparkfun  - can be had rather cheaper but these are available

The recommended output (source or sink) from an I/O pin is 20 mA. The absolute maximum is 40 mA. Your relay coil is likely to consume more than that, particularly when it initially energizes. This will damage your output pin. Then it will eventually fail.

Nothing seems to be amiss by far.

No, not yet. :)

How can one control such components without risking the Arduino? What are some common means to accomplish this?

Use transistors or MOSFETs.

What other devices can generally harm an Arduino board (or any microcontroller unit) in a similar manner?

Anything that exceeds the maximum voltage or current limits as documented in the datasheet. Coils (eg. in relays and motors) in particular are likely to have a high reverse voltage when they are turned off, which is why you need a snubber diode.

Would it be advisable to proceed?

It would be advisable to take heed of what I wrote above, and to read the many, many articles on the Web about how to drive motors and relays from an Arduino. You are not the first person to attempt this.

Have a look at the simple circuit on this PDF from the Arduino Playground.  It shows a single transistor to drive a small relay.
As Russell says in his answer, a ULN2803 or similar is a chip which will allow you to drive several small relays, which is neater than using several transistors, if that's what you want.
(Also note the diode "D1" in the circuit I linked - you need this, it's to protect the transistor from eventually being damaged by inductive spikes generated when the relay turns off.  Some of the ULN-style chips have this diode built in, which is why you don't always see it in schematics.)

To really protect your arduino it's worth putting a photo-coupler on the pin and driving your circuit that way.  Then no stray inductive charge or short can affect the arduino.
They are also called OptoIsolators or Optocouplers.
http://forum.arduino.cc/index.php?topic=143954.0

You're quite right, optoisolators are a great way to go. Another way to do it that's slightly less isolating but still handy is to use an Operational Amplifier (Op Amp) as a buffer. These are also called 'folloer' Op Amps. Note that you can do this with any off-the-shelf OpAmp, you just lay the circuit out a particular way. https://en.wikipedia.org/wiki/Buffer_amplifier#Op-amp_implementation

Let us look as some basic's, these seem to be the basis of a lot of questions:
A capacitor when power is switched on draws a huge amount of current that tapers off as it gets charged. This curve is also called the RC time constant (this is close but not exact "http://www.electronics-tutorials.ws/rc/rc_1.html" will give a better explanation).
When switching off a capacitor discharges at an exponential rate (RC time constant) depending on the value, charge voltage and the load.  This makes them good for holding power for a short time when the power fails.
An Inductor draws nothing when first switched on but the current increases exponentially until its voltage reaches the supply voltage.
When switched off the inductive field in the inductor collapse causing the polarity to reverse.  The voltage will rise unlimited until typically something externally limits it. The faster it is turned off the quicker the rise time and voltage.  Energy will cease to flow when the inductive charge is dissipated.  Guess where this current goes when the inductive load such as a relay is connected to a port pin?
For this reason you need to put a diode (commonly called a fly wheel diode) across the inductive load.  Google for: "inductor/capacitor charge curve" you will find a lot of nice graphs explaining this. This diode is not necessary if you use an appropriately rated MOSFET (UIS). The UIS (Unclamped Inductive Spike) information is in the MOSFET data sheet.  If you look at the circuit it has the cathode + connected to the most positive side of the power supply.  In this configuration it will not conduct unless the voltage is reversed (when the inductive load is switched off).
Another common misconception is you can load a microprocessor I/O to the maximum. This is bad design. They give you a maximum per pin, per port and for the chip.  At room temperature you will probably get away with it for a while.
Let us assume we have a port with a 40mA load.  The output is 0.005 from the power rail.  Using Ohm’s law we are dissipating 20 milliwatts of power on one pin. At this rate of loading it does not take long to over heat the device because of internal power dissipation.
When the output pin is changing state it draws more current because it has to charge or discharge its internal and the external capacitance, ‘more heat’, more speed ‘more heat’.
If you look some of the specs will give you a maximum temperature, it is for the junction on the die, not the case temperature.  Plastic is a poor conductor so heat sinking the package does not do a lot.  Now consider this along with the ambient temperature.  The ratings are given typically with the device at 25C, guess what happens when it gets warmer.
Have fun,
Gil

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


text:
Code for password-activated LED via Bluetooth serial
I have this pretty simple task to light up an LED for 3 seconds when I send the right password from my Android phone to the Arduino via Bluetooth. I am using an HC-05 Bluetooth Module. My LED is connected to Pin 9 of the Arduino I/O. TX and RX of HC-05 is connected to Pins 1 and 0 of Arduino respectively. Here's the code I am using:
int output = 9;         //I will be using to control a DC motor(LED is just for testing).
int output2 = 10;
char final[4];
char correct[4] = {'Q','W','E','R'};
int pass_true;

void setup() {
  pinMode(output, OUTPUT);
  pinMode(output2, OUTPUT);
  Serial.begin(9600);

}

void loop() {
  while(Serial.available()){
    for(int i=0; i<4; i++){
      final[i] = Serial.read();
    }
    for(int i=0; i<4; i++){
      if(final[i]==correct[i]){
        pass_true = 1;
      }
      else{
    pass_true = 0;
    break;
      }
    }
  }

  if(pass_true==1){
    digitalWrite(output, HIGH);
    Serial.println("ON");
    delay(3000);
    pass_true = 0;
  }
  else{
    digitalWrite(output, LOW);
  }

}

I am using Bluetooth SPP Pro Android App to send the 4-byte pass code ("QWER")
The problem is the LED wont light up. I tried replacing the LED thinking that it may be a dead one but it's not. The "TX" LED on the board blinks everytime I press "SEND" in the Bluetooth App, but still Pin 9 doesn't seem to produce the HIGH output at all. Is there a problem with the code?

Read and digest this: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

Please start by verifying that the connection is even working, before trying to parse a message that "should" come in.

Try using the serialLoopback sketch, how can you be sure it is set to 9600 baud anyway?

Try using the following code you need to use String and concatenate that
    String rcev_data="";
bool chk=false;
\#define output 9

\#define output2 10

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

void loop()
{
  // put your main code here, to run repeatedly:
  while(Serial.available())
  {
    char rxx = Serial.read();
    recv.concat(rxx);
    delay(10);
    if (recv == "QWER")
    {
       chk=1;
       break;
     }
    else
     chk=0;
 }

  if (chk)
  {
    digitalWrite(output,HIGH);
    Serial.println("ON");
    delay(3000);
    chk=0;
  }

  else
  {
    digitalWrite(output,LOW);
  }
  recv="";
}

Instead of
while(Serial.available()){

please try
while(Serial.available() >= 4){

Depending on how your transmitting application is buffering the writes, the loop()'s password check may be triggering on a single byte of input each time.
You may also want to make the code a bit more fault-tolerant.  For example what if there's a bit of noise in the line, or the operator pushes [Enter] first before entering the code.  The input buffer will fill up a few characters, then the password will not match because it spans, say input bytes 3,4,5,6.  Maybe throw away any old input based on elapsed time, etc.


text:
Passing a static array to a function
I have a functon that creates a instance of KeyReport and I want to fill statically the KeyReport.keys array. I'm new in the Arduino world so I'll put a example to explain it better:
void sendKey(byte keys[6], byte modifiers)
{
  KeyReport report = {0};

  report.keys = keys; // This is my main trouble
  report.modifiers = modifiers;
  report.reserved = 1;
  Keyboard.sendReport(&report);
}

void setup(){
delay(3000);
sendKey( {0x17,0,0,0,0,0}, 0x5); // I want to send hardcoded reports like this
}

void loop(){}

report.keys = keys; // This is my main trouble

You can't assign the contents of one array to the contents of another array.  You can only copy the contents manually from one to the other.
The simplest way is with a loop:
for (int i = 0; i < 6; i++) {
    report.keys[i] = keys[i];
}

There is a helper function - memcpy() - which can do it for you if you prefer:
memcpy(report.keys, keys, 6);

It effectively does exactly the same thing - copy 6 bytes starting from the address of keys into the addresses starting at report.keys.
As for the "hard coded" reports I suggest you create some const arrays in the global context - and even use PROGMEM to ensure they consume no RAM. That, of course, requires an entirely different way of passing and accessing the data.  It may be simpler to split the report into 6 individual variables and pass each byte separately:
void sendKey(byte k0, byte k1, byte k2, byte k3,
             byte k4, byte k5, byte modifiers)
{
  KeyReport report = {0};

  report.keys[0] = k0;
  report.keys[1] = k1;
  report.keys[2] = k2;
  report.keys[3] = k3;
  report.keys[4] = k4;
  report.keys[5] = k5;
  report.modifiers = modifiers;
  report.reserved = 1;
  Keyboard.sendReport(&report);
}

sendKey(0x17, 0, 0, 0, 0, 0, 0x05);

Yes, it's a little more long winded in the function, but calling the function is somewhat more simplified over the other options.

+35: Really good answer. Your last method is the best for me.

One last question: Is ok to use a for loop to clear the report.keys array?

Yep, perfectly fine. for (int i = 0; i < 6; i++) { report.keys[i] = 0; }


text:
LED cube and 200 mA limitation
I'm new to electronics and have been getting rather into my Arduino. But I don't just like following an instructable to do something. I like to know the math behind it and how it works inside. Now from my understanding the Arduino (Uno R3 for me), has a 200 mA max current. The LEDs I used have a 20 mA current. Now with 64 LEDs, wouldn't this fry my Arduino? This also applies to my LCD screen with a 160 mA current. Am I missing a key secret to going over amperage?

The current limit you quote is the maximum current that the main chip on the Arduino can tolerate through its 5V or GND pins.
As the chip itself consumes (round numbers demonstrate the theory) say 50mA that leaves 150mA in total that can be sourced or sunk through IO pins.
If you want to supply 20mA per LED (that is actually overkill - you can use considerably less and have very little difference in brightness) that means you can have, illuminated at any one time, (150 / 20 = ) 7.5 LEDs.
To increase the number of LEDs you can drive at once you can:

Reduce the current by increasing the resistor values.
Use multiplexing so that, although it looks like all LEDs are on at once, only a few are actually on at once.
Use external LED driving circuitry (transistors, LED driver shift registers, etc).

All this pertains purely to the current that passes through the main chip itself.  It does not pertain to any current you draw from the 5V or 3.3V pins.  The maximum current through those pins is limited by the voltage regulator they are attached to, and also by the voltage that you are supplying the board with (the higher the voltage, the more voltage has to be dropped, and so the more heat is generated per mA drawn).
The 5V regulator has around 800mA limit when supplied with 6.5V.  If supplied with 12V the limit is considerably less (since it will get too hot and go into thermal shutdown).  You subtract what you are drawing through the chip (maximum 200mA) and that is how much current you have available.
The 3.3V regulator is driven from the 5V regulator, so any current drawn from the 3.3V pin must also be subtracted from what is available on the 5V pin.

I'm assuming you're talking about an 8x8x8 cube.
The 200mA is for all IO. The regular 5v line can supply 500mA. Since you don't have 64 pins available, you are not supplying the leds via the Arduino directly. Probably using some shift register, or led driver chips for the 64 (cathode) columns. For the 8 levels you'd use some PNP transistors or P-channel mosfets.
So the Arduino won't drive any led directly, so it will only use a few tens of milli-amps. Since you'll draw around 1.3A when all leds are lid, you should power the external components directly from the power supply, instead of via the Arduino. Or you'll hit the 500mA limit.
So the Arduino is just pushing the levers, and not doing any of the hard work (crane analogy).


text:
Powering Arduino with 110v and controlling relay
I've found a lot of tutorials about how to use an Arduino to control power supplies to lamps and things like that using a relay. However, I also need to power the Arduino with the same power that is going through the relay.
In other words, I'd like to be able to plug my device into the wall. The device would use the 110VAC to power the Arduino. My device would also have some outlets that I could plug something into. The Arduino would be connected to a relay and would decide when to enable electricity to the outlet. The important part being that I would like everything to be on one power source.
Do I need to have a step down converter to transform the power, in addition to the relay? Is there some sort of break out board that has both of these functionalities in one board? What is the best way to do this?

In these cases where power must come from mains, my preferred solution is to buy a cheap phone charger+usb cable from ebay. They are sealed and safer than do-it-yourself solutions. The power adapter is barely larger than a normal plug for mains.
If you absolutely need to reach the arduino with only one cable, you can still use the solution i gave, only use a power cord to reach the contraption, then use a socket expander for mains and very short usb cable.

I hope I'm not misunderstanding this. I think that would be a great solution to just power the arduino and I do that already. However, I also need to use the power from the mains to also run through the relays so that it can power anything that is plugged into it. One cable going in to power the arduino and one outlet going out that a regular plug can be plugged into.

My proposal is the following.
Use a box for the contraption - it deals with voltage levels that can be fatal, so it should be boxed anyway. Have a power cord going inside the box. Inside the box have a socket splitter (I don't know about where you leave, but at least in several countries in Europe they are pretty common). In one of the 2 sockets plug the phone charger, to power the arduino over usb. Use a relay shield on the Arduino. In the other mains socket, plug a power cord, going out of the box, through the relay. I't not optimized for space, but it should be pretty safe and sturdy.

And relatively cheap. I am not aware of shields that would be both power supplier and relay.

That's perfect!! Thank you so much for the help!


text:
Arduino WIFI compiler error
Just bought an ESP8266 module to try it using my arduino uno R3. I have connected my WIFI module correctly, anyways evenb if i disconnect it, the error occur.
While trying to upload the WIFI (connect with wpa) sketch i get several errors.
First i tried uploading the hole sketch, i got those errors:
/usr/share/arduino/libraries/WiFi/WiFi.cpp: In member function ‘uint8_t* WiFiClass::macAddress(uint8_t*)’:
/usr/share/arduino/libraries/WiFi/WiFi.cpp:112:1: error: unable to find a register to spill in class ‘POINTER_REGS’
/usr/share/arduino/libraries/WiFi/WiFi.cpp:112:1: error: this is the insn:
(insn 35 25 26 2 (set (reg:QI 23 r23)
    (mem/c:QI (plus:HI (reg/f:HI 28 r28)
            (const_int 2 [0x2])) [3 S1 A8])) /usr/share/arduino/libraries/WiFi/WiFi.cpp:110 28 {movqi_insn}
     (nil))
/usr/share/arduino/libraries/WiFi/WiFi.cpp:112: confused by earlier errors, bailing out

After that i tried to only import just the libraries and try to compile it. Even with this method i get errors
Code
#include <WiFiServer.h>
#include <WiFiClient.h>
#include <WiFi.h>

error:
In file included from /usr/share/arduino/libraries/WiFi/WiFiServer.h:8:0,
                 from sketch_oct20b.ino:1:
/usr/share/arduino/hardware/arduino/cores/arduino/Server.h:4:29: error: expected class-name before ‘{’ token
In file included from sketch_oct20b.ino:1:0:
/usr/share/arduino/libraries/WiFi/WiFiServer.h:14:3: error: ‘uint16_t’ does not name a type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:17:22: error: field ‘uint16_t’ has incomplete type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:18:24: error: ‘uint8_t’ has not been declared
/usr/share/arduino/libraries/WiFi/WiFiServer.h:20:11: error: ‘size_t’ does not name a type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:21:11: error: ‘size_t’ does not name a type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:22:3: error: ‘uint8_t’ does not name a type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:24:9: error: ‘Print’ has not been declared
/usr/share/arduino/libraries/WiFi/WiFiServer.h:18:42: error: ‘NULL’ was not declared in this scope

I can just figure out some syntax errors, but my c is not good enough to understand much of it.
Can anyone tell me what am i doing wrong and show me how it will be done?

The WiFi libraries (such as Wifi.h, WifiClient.h, and WiFiServer.h) are used for interfacing with the official Arduino WiFi shield. Interfacing with an ESP8266 module is typically done by issuing AT commands via UART (i.e. Serial.write(), etc.)

Nice one, thank you sir. That means i need an additional FTDI breakout board and a logic level shifter, right?

Logic shifter yes, the UNO is a 5 volt device and the ESP8266 is a 3.3 volt device. FTDI probably not, you can communicate to the ESP8266 via the UART pins (0 and 1), and even if you need to update the firmware ofr the ESP, you can do that by pulling the microcontroller out of the socket and just use the board as a USB to Serial adapter.


text:
Can I place bootloader directly onto Atmega2560 and have USB?
I am working on a prototype device which I am now on my 2nd board iteration and moving away from it being a shield and wired to an arduino mega2560 board.
I have used the freely available Arduino mega 2560 schematic and incorporated this into my project.
I notice that there are 2 µcontrollers on this schematic, (Atmega2560 & Atmega16U2)
I understand that the arduino bootloader resides on the 16u2 and it connect to the usb connector. the 16u2 then programs the 2560 with the code you send it.
On the searching I have done I'm getting myself terribly confused.
Someone suggested to me that I could in fact do away with the Atmega16u2 all together (this would drastically reduce my component count and free up valuable board space)
However, I was intending to flash a boot loader that would make the device appear to a computer (over usb) as a midi controller device.
I am unclear if I can indeed interface a usb port directly to the ATmega2560,  and upload my sketch code AND a midi-over-usb boot loader..
I doubt the advice because the ATmega16U2 (i think) has a built in UART to communicate via usb and that the 2560 does not...
Sorry If this all sounds vague, I'm searched out and confused...
thanks.

USB really needs specialized hardware to handle the low-level signalling and timing requirements.  1.1 can be bit-banged if you have the resources (https://www.obdev.at/products/vusb/index.html for example), but anything better than that pretty much requires the dedicated hardware.  A common UART won't even come close.

I understand that the arduino bootloader resides on the 16u2 and it connect to the usb connector. the 16u2 then programs the 2560 with the code you send it.

That is a misunderstanding.
The bootloader is on the 2560.  The 16U2 contains its own custom firmware which acts as a USB CDC/ACM interface to connect the USB to the 2560 as a TTL UART connection.
The same can be done using any number of other similar devices, such as the FT232R etc.
You cannot directly connect the USB to the 2560 since the 2560 has no concept of what USB is.  The 16U2 has that knowledge, but doesn't have as many IO pins as the 2560, so combining the two gives you a total system that both understands USB and has lots of IO.

thank you for this useful reply. If I am understanding you correctly then, I could use an FT232R to give the 2560 usb communication capability, and also flash the code (in addition to my program code) to enable the device to be seen as a midi controller (HID Device) on connection to a computer?

@BradHolland: No. The FT232R is strictly for serial communications. You will need to use a MCU with native USB support (such as the '16U2 on the Mega 2560).

Someone suggested to me that I could in fact do away with the Atmega16u2 all together (this would drastically reduce my component count and free up valuable board space)

I recommend that you keep the '16U2 and ditch the '2560. Since the '16U2 is both native USB capable and has sufficient I/O for a MIDI controller then you should use that one for your project.
Of course, since there's no Arduino core for the '16U2 you may want to consider either learning AVR programming without Arduino (when will there be a better time to do so?), or switching to the (overpowered) 'U4, which uses the Leonardo core.

thank you. This isn't just a simple midi controller I'm confident the 16u2 wont work for the application. we're already using a lot of i/o including a large array of leds, analog inputs and an oled screen..

Then you'll need to find some sort of protocol you can use to talk between the '16U2 and the '2560.

if I can indeed interface a usb port directly to the ATmega2560

You cannot interface USB directly to the ATMega2560, because that µC has no USB support build into (and VUSB is probably no solution either).
If your program is simple enough, then it could fit onto the ATMega16U2 on its own, eliminating the 2560.


text:
Arduino Pro Mini lower BOD problem
I am planing to build a project where an arduino pro mini 3.3V runs on 2 aa batteries. The standard brown out detection shuts it down at about 2.7/2.8V where it could run on lower voltages too.
So I changed the efuse to get the BOD down to 1.8V. I connected a serial to usb converter and used avrdude:
avrdude -c avrisp -p m328p -P COM5 -b 19200 -U lfuse:w:0xff:m -U hfuse:w:0xda:m -U efuse:w:0x06:m

Then I tried to upload a program using the arduino 1.0.3 IDE but I got this error:
avrdude: stk500_getsync(): not in sync: resp=0x1c

With 1.6.4 I got another error:
    avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x75
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1c

After some googling I tried some lower baud rate (the standard seems to be 57600). With 19200 everything worked with avrdude, so I created a new entry in the boards.txt
    ##############################################################

pro328.name=Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328 BOD 1.8V

pro328.upload.protocol=arduino
pro328.upload.maximum_size=30720
pro328.upload.speed=19200

pro328.bootloader.low_fuses=0xFF
pro328.bootloader.high_fuses=0xDA
pro328.bootloader.extended_fuses=0x06
pro328.bootloader.path=atmega
pro328.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
pro328.bootloader.unlock_bits=0x3F
pro328.bootloader.lock_bits=0x0F

pro328.build.mcu=atmega328p
pro328.build.f_cpu=8000000L
pro328.build.core=arduino
pro328.build.variant=standard

And burned a bootloader using the 1.0.3 IDE again. After that I could upload a blink program. My goal is to upload a mysensors sketch though and that doesn't work. I am getting an error
avrdude: verification error, first mismatch at byte 0x0002
         0x69 != 0x61
avrdude: verification error; content mismatch

Mysensors seems to have general problems with old arduino IDEs so I tried to use the newer 1.6.4 but I can't define my own board there and if I try it without I get hte out of sync error (because it's still using the wrong baudrate I guess).
I also tried using another arduino uno as ISP => same results
How can I fix this? Is there a way to define my own board for 1.6.x?
Whats the standard way of doing this and why does the change of the efuse results in me not beeing able to program the mini any longer?
Thanks for every answer/help!

When you go below (or above) the manufacturer's voltage/clock specifications, expect some problems. One chip may work another will not.  Remember the lower the voltage normally the slower the clock needs to be.  The CPUs are cut from a wafer (size and geometry specific) which may contain many thousand CPU die, they are at different locations on the wafer they will be a little different and they make more then one wafer.
Check the data sheet, it will show what clock speed will work at what voltage.  As the CPU clock changes so will your baud rate so plan on recalculating that if you change the clock. Example:  If you are operating with a 16MHz clock and change it to 8MHz the baud will be exactly 1/2.  If at 9600 it will be 4800 unless you modify the clock dividers.
Your error indicates a potential baud rate problem. One of the funny things that happens when the voltage is above/below the manufacturer's speck not all instructions operate properly over temperature. Clock problems should be expected.


text:
Shift register 1's and 0's array to 4 int's function not working
I'm not sure if i should post this here or on StackOverflow but I am coding for an LED cube controlled with 4 shift registers. I have a function in a .h file that is supposed to take an array of 1s and 0s (to represent each LED) and then use the shiftOut function to shift the data into the shift registers. This is complicated that the shiftOut function has to take a int which it shifts out in binary and only goes 8 bits at a time. This means I have to separate my array into 4 groups of 8 and then convert each group into an int. I have tried to make my function do that but it is compiling fine and then not lighting up any LEDs. I believe the problem has to do with the way I'm separating the array into 4 smaller arrays althoughI can not figure out exactly what is going wrong, here is my code.
Main program:
#include <LEDcube.h>

int data = 2;
int clock = 3;
int latch = 4;

void setup()
{
  pinMode(data, OUTPUT);
  pinMode(clock, OUTPUT);
  pinMode(latch, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  int layer[32] = {0,

                  1,1,1,1,1,
                  0,0,0,0,0,
                  1,1,1,1,1,
                  0,0,0,0,0,
                  1,1,1,1,1,

                  0,0,0,0,0,0};
  write(data, clock, latch, layer);
}

LEDcube.h:
#include "Arduino.h"

int binToNum(int bin[])
{
  int j = 1;
  int num = 0;
  for(int i = 0; i < 8; i++, j = j * 2)
  {
    if(bin[i] == 1)
    {
      num = num + j;
    }
  }
  return num;
}
void write(int data, int clock, int latch, int layer[])
{
  int reg1[8];
  int reg2[8];
  int reg3[8];
  int reg4[8];
  for(int i = 0; 1 < 8; i++)
  {
    reg1[i] = layer[i];
  }
    for(int i = 0; 1 < 8; i++)
  {
    int q = i + 8;
    reg2[i] = layer[q];
  }
  for(int i = 0; 1 < 8; i++)
  {
    int q = i + 16;
    reg3[i] = layer[q];
  }
  for(int i = 0; 1 < 8; i++)
  {
    int q = i + 24;
    reg4[i] = layer[q];
  }
  int regnum1 = binToNum(reg1);
  int regnum2 = binToNum(reg2);
  int regnum3 = binToNum(reg3);
  int regnum4 = binToNum(reg4);
  digitalWrite(latch, LOW);
  shiftOut(data, clock, MSBFIRST, regnum4);
  shiftOut(data, clock, MSBFIRST, regnum3);
  shiftOut(data, clock, MSBFIRST, regnum2);
  shiftOut(data, clock, MSBFIRST, regnum1);
  digitalWrite(latch, HIGH);
}

for(int i = 0; 1 < 8; i++) is this correct? should it be for(int i = 0; i < 8; i++)?

I'm not sure what you mean @PhillyNJ

What are you using for a shift register?

@PhillyNJ means 1<8 instead of i<8 (notice the 1 (one) instead of the i (letter I))

ohhhhhhhhhhhhhhh, that typo might have been the problem

The problem is you need to write your data with all of your bits consolidated into a single integer instead of as an array of integers. For example, if you were to shiftOut(data, clock, MSBFIRST, 1) that would send 00000001, not 1. So for example, if you want to send out 1,0,1,0,1,0,1,0 you need to send shiftOut(data, clock, MSBFIRST, 170), because 170 in binary is 10101010. So you will need to figure out how to represent your data as an integer rather than array of integers of which you are only using the first bit.
EDIT:
I see that you are attempting to do a binary conversion, but your for loop is a little off. Try this instead:
for(int i = 0; i < 8; i++)
{
  if(bin[i] == 1)
  {
    num = num + j;
  }
  j = j * 2;
}

Even if that fixes it, you will probably still need to some major refactoring to get decent speed, currently you are using 128 bytes of memory to represent 4 bytes worth of data. and there are plenty of other little inefficiencies here and there.
EDIT 2:
The simplest version of the above functionality is this:
int data = 2;
int clock = 3;
int latch = 4;

void setup()
{
  pinMode(data, OUTPUT);
  pinMode(clock, OUTPUT);
  pinMode(latch, OUTPUT);
}

void loop()
{
  int data1 = 0b1111100000111110; //Set a variable using a binary constant
  int data2 = 0b0000111110000000;
  digitalWrite(latch, LOW);
  shiftOut(data, clock, MSBFIRST, data1);
  shiftOut(data, clock, MSBFIRST, data2);
  digitalWrite(latch, HIGH);
}

If you are going to be doing more bit level manipulation, you should probably learn various bit wise operators such as <<, >> &, ^, |, ~, &=, and |=. The Arduino documentation goes over them and what they do (scroll down, on the left under Bitwise Operators).

Thats what I was trying to do by converting my array of ones and zeros into an integer ( int regnum1 = binToNum(reg1); ) @Jake C

Thanks for the help although I don't think that the problem is in the binary to integer conversation function as it was works fine with out when called out side of the write function. I think the problem has more to do with separating the 32-bit array into 4 8-bit arrays, I should have made that clearer in the question. You do make a good point with the efficiency though and if you have any suggestions as to how I could improve that would be great.

As noted in Stu's answer, the question's code does not pack bits properly into the bytes that shiftOut() will unpack them from.
If you merely want to make things work, as opposed to packing stuff up one place so it can be unpacked another, just write the bits to your SR yourself.  For example:
for (int i=0; i<32; ++i) {
  digitalWrite(data, layer[i]); // Put a bit on the data pin
  digitalWrite(clock, HIGH); // Pulse the clock
  digitalWrite(clock, LOW);
}
digitalWrite(latch, HIGH); // Pulse the latch
digitalWrite(latch, LOW);

If the clock or latch need low-going instead of high-going pulses, reverse the order of writing HIGH and LOW.


text:
Arduino Uno "MEM CHECK FAIL" error
Just followed a tutorial on how to set up ESP8266 with my Arduino Uno R3. I have a serial connection and get a response of the Arduino but I'm stuck now at chapter "first commands".
I have successfully issued the AT command and also the AT+RST command and got a response. BUT, the response return was "invalid" at its end instead of "ready". Also theres an output "MEM CHECK FAIL!!!"
AT

OK
AT+RST

OK

 ets Jan  8 2013,rst cause:2, boot mode:(3,4)

load 0x40100000, len 1396, room 16
tail 4
chksum 0x89
load 0x3ffe8000, len 776, room 4
tail 4
chksum 0xe8
load 0x3ffe8308, len 540, room 4
tail 8
chksum 0xc0
csum 0xc0

2nd boot version : 1.4(b1)
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

ÃÕMEM CHECK FAIL!!! <<----------------------------- ???
äslrô
Ai-Thinker Technology Co. Ltd.

invalid <<----------------------------------------- should be "ready"

Can anyone explain me what that means? Do I have to (re)flash the firmware? And also - are the instructions all the same? I have bought mine from China but it was sold at the same ESP8266 module on Amazon.

The invalid on the end means that your config on the chip is either corrupted or not set up yet. So that's not part of your memcheck problem

http://www.agcross.com/2015/09/the-esp8266-wifi-chip-part-1-up-and-running/
According to the tutorial it's an undocumented bug with no fix.
If you change the name, baud, and set up the wifi and password you should be good to go


text:
Keyboard.print() skips keys
I'm playing with the Arduino Leonardo Keyboard.print() command, but I'm facing a annoying problem:
When I print a double quote, it will not appear and also will make to disappear the next character (i.e.):
Keyboard.print("echo \"This is a demo\"");

Output:
echo his is a demo

And when I use this line:
Keyboard.print("echo -This is \"a demo-");

Output (note the umlaut over the a instead of getting "a):
echo 'This is ä demo'

I suspect that the problem is that my computer is configured to use Spanish layout.
What source code file can I change to fix this? I can't find the defines used by Keyboard.print()

In your particular case, the double quote is to be entered (using the Spanish keyboard layout) by Shift + the physical key labelled 2. On a US keyboard, Shift + the physical key labelled 2 is "@".
Thus, this simply will get the desired result (the Arduino library assumes a US keyboard layout):
Keyboard.print("echo @This is a demo@");

More general solution
More generally, strings can be encoded as in the following table (the exact mappings depend on the particular keyboard layout - this will work for many European keyboard layouts).
If the physical key (and modifier key, if any) exists on the US keyboard to get the character typed out using the non-US keyboard layout, then this method works fine.
To get   Use   Notes
--------------------------------------------
;        <     Will result in Shift action
:        >     Will result in Shift action
(        *     Will result in Shift action
)        (     Will result in Shift action
/        &     Will result in Shift action
?        _     Will result in Shift action
=        )     Will result in Shift action
&        ^     Will result in Shift action

-        /
+        -
_        ?

"        @     Will result in Shift action

,        ,     The same
.        .     The same
#        #     The same

Even more general solution
Even more generally, some keys are not on the US keyboard (e.g. the 102th key on European keyboards for the original PC keyboards, often with <, >, \, and |), and it is not possible to use Keyboard.print().
Instead, use the low-level HID().SendReport() function - with code 100 (decimal) for the first parameter for the 102th key. See the library source code, Keyboard.cpp (/libraries/Keyboard/src/Keyboard.cpp), for how to use HID().SendReport().
Alternative solution
Some operating systems enable entering characters using the keyboard and a numeric code.
This is at the expense of making it operating-system dependent (but making it independent of the active keyboard layout).
For example, Ctrl + Shift + U on Linux (GUI only, dependent on the window manager(?)). For the particular problem (the Unicode code point for " is 0022), without any functional abstraction to reduce the redundancy:
Keyboard.print("echo ");

Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.press('u');
Keyboard.releaseAll();
Keyboard.print("0022");
Keyboard.press(KEY_RETURN);
Keyboard.releaseAll();

Keyboard.print("This is a demo");

Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.press('u');
Keyboard.releaseAll();
Keyboard.print("0022");
Keyboard.press(KEY_RETURN);
Keyboard.releaseAll();

Unicode code points can be found at unicode-table.com.
Media keys
Even though the media keys are listed in the table (e.g. code 128 for "Volume Up" on page 53), they do not work using the method described in the previous section. But there is a solution.
Platform
This was tested with:

Arduino Leonardo
The Spanish keyboard layout was added to the Linux settings and activated. There were 14 different ones to choose from, but I used the one labelled "Spanish". It was verified that "@" actually resulted in an output of """. It was also verified that the Ctrl + Shift + U method worked.
Linux, Ubuntu 19.10 (Eoan Ermine), but with the buggy GNOME replaced by Cinnamon.
The Arduino Leonardo connected to an extra current port of a D-Link USB hub (necessary, for unknown reasons - probably a local problem)
Arduino IDE v. 1.18.10

I know this because I have implemented it for a macro keyboard where the keyboard layout is (usually) Danish in the operating system (Windows or Linux).

Excellent answer!

(Code 128 for "Volume Up" is on page 56, not 53.)

(For a future update: The first link doesn't actually show the double quote will be entered by Shift + 2. It ought to be replaced by something better. For example, this one.)

(For a future update: Both "#" and "?" will also result in a Shift action (Shift + 3 and "/", respectively). And consider using Markdown tables, if available. 102th → 102nd (?).)

(For a future update: The leading zeros in "0022" may not be necessary. It wasn't necessary in GNOME.)

(For a future update: For the Unicode code input: Instead of Return at the end, an alternative it to keep holding Ctrl  and Shift down (releasing them at the end))

The Arduino assumes a US keyboard layout.  The thing with keyboards is they don't actually send the letters or symbols that are printed on the keys.  Instead the send a scan code that defines where on the keyboard the key is.  It is then up to the computer to convert those scan codes into actual letters and symbols, and that is performed by the keyboard mapping selected in the operating system.
Some special keys are known as dead keys.  These don't actually print a character on their own - instead they are used to modify the next key pressed - for instance the key which occupies the space a " would be on a US keyboard, on a Spanish keyboard, is a dead key which modifies the next key by adding an umlaut to it.
Since the Arduino doesn't know that you have a Spanish mapping, when you send a " it just sends what it believes is the location of that character on a keyboard, and of course it gets that wrong since it assumes the wrong keyboard layout.
So there are two things you can do to "fix" it:

Change your keyboard layout to US, but that will mean your normal keyboard will stop working properly.
Change how the Arduino thinks the keyboard is laid out, but that means lots of work to find the right scan codes.

The Arduino's keyboard layout is stored in the file HID.cpp in the Arduino core (hardware\avr\cores\arduino or somewhere like that - I forget off hand) and is the _asciimap array.  It is a list of the first 128 ASCII characters and the keyboard scancode mappings for them, including modifier keys like Shift.  You will have to find the scan codes for the keys you want to map on your keyboard layout and change the codes in that list.  For instance, the character " is listed as:
0x34|SHIFT,    // "

Which is scan code 0x34 (52 decimal) coupled with the SHIFT modifier.  You will have to discover (maybe Google can help) what the 0x34 should be changed to so that it moves the " to wherever it is on a Spanish keyboard.

+35: Thank you very much! When I find the exact file location I'll tell you it!

In my computer is located in /usr/share/arduino/hardware/arduino/cores/arduino/HID.cpp. I'll try to override these mappings with some custom ones.