text:
Exit status 1 expected primary-expression before ']' Arduino
Here's the whole error:
 Arduino: 1.6.7 (Windows 7), Board: "Arduino/Genuino Uno"

 *\readMifare\readMifare.ino: In function 'void loop()':

 readMifare:113: error: expected primary-expression before ']' token

    if (uid[] == { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 }) {

            ^

 readMifare:113: error: expected primary-expression before '{' token

    if (uid[] == { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 }) {

                 ^

 readMifare:113: error: expected ')' before '{' token

 readMifare:121: error: expected '}' at end of input

    }

    ^

 exit status 1
 expected primary-expression before ']' token

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

Here's the code
 #include <Wire.h>
 #include <SPI.h>
 #include <Adafruit_PN532.h>

 // If using the breakout with SPI, define the pins for SPI communication.
 #define PN532_SCK  (2)
 #define PN532_MOSI (3)
 #define PN532_SS   (4)
 #define PN532_MISO (5)
 // If using the breakout or shield with I2C, define just the pins connected
 // to the IRQ and reset lines.  Use the values below (2, 3) for the shield!
 #define PN532_IRQ   (2)
 #define PN532_RESET (3)  // Not connected by default on the NFC Shield

 // Uncomment just _one_ line below depending on how your breakout or shield
 // is connected to the Arduino:

 // Use this line for a breakout with a software SPI connection (recommended):
 Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);

 // Use this line for a breakout with a hardware SPI connection.  Note that
 // the PN532 SCK, MOSI, and MISO pins need to be connected to the Arduino's
 // hardware SPI SCK, MOSI, and MISO pins.  On an Arduino Uno these are
 // SCK = 13, MOSI = 11, MISO = 12.  The SS line can be any digital IO pin.
 //Adafruit_PN532 nfc(PN532_SS);

 // Or use this line for a breakout or shield with an I2C connection:
 //Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

 #if defined(ARDUINO_ARCH_SAMD)
 // for Zero, output on USB Serial console, remove line below if using      programming port to program the Zero!
 // also change #define in Adafruit_PN532.cpp library file
 #define Serial SerialUSB
 #endif
 #include <Servo.h>

 Servo servo1;

 void setup(void) {
   #ifndef ESP8266
   while (!Serial); // for Leonardo/Micro/Zero
   #endif
   Serial.begin(115200);
   Serial.println("Hello!");

   nfc.begin();

   uint32_t versiondata = nfc.getFirmwareVersion();
   if (! versiondata) {
     Serial.print("Didn't find PN53x board");
     while (1); // halt
   }
   // Got ok data, print it out!
   Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
   Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
   Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

   // configure board to read RFID tags
   nfc.SAMConfig();

   Serial.println("Waiting for an ISO14443A Card ...");
   servo1.attach(9);
 }

 void loop(void) {
   uint8_t success;
   uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
   uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

   // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
   // 'uid' will be populated with the UID, and uidLength will indicate
   // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
   success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

   if (uid[] = { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 }) {

      int position;
      for(position = 0; position < 180; position += 2){
       servo1.write(position);
       delay(20);
      }

   }

Please note that I'm using an example from the Adafruit official PN532 library examples and trying to edit it.

You probably do not want an '=' in the if statement.  What example had this?

This is what I added, still new though, so what should I input?

To compare you use ==. = is for assignment. Common mistake, even by the professionals.

I wouldn't use strncmp because the UID might have zeroes in it. This looks safer:
   uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
   uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

   const uint8_t wantedUid [] = { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 };

   // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
   // 'uid' will be populated with the UID, and uidLength will indicate
   // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
   success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

   if (success &&
      uidLength == sizeof (wantedUid) &&
      memcmp (uid, wantedUid, sizeof wantedUid) == 0) {
      ...

I threw in a test for the uidLength being the expected size, otherwise you might find a 4-byte card happens to match the first four bytes of the wanted UID.
memcmp compares a block of memory for the number of bytes you specify. It returns zero on a match.

You probably need something like:
uint8_t uidTarget[] = { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 };

...
if (success && !strncmp((const char*) uidTarget,(const char*)uidSource,8)) {

Your '=' tries to do an assignment, and an '==' would check if the pointers to the arrays are identical, rather than the contents of the arrays.  strncmp() tests equality of strings of characters, and the (const char*) casts the uint8_t values as characters.
Nick Gammon's answer is better.

added what you told me to add, error:
readMifare:113: error: invalid conversion from 'uint8_t* {aka unsigned char*}' to 'const char*' [-fpermissive]
if (success && !strncmp(uid,{ 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 },8)) {
readMifare:113: error: cannot convert '' to 'const char*' for argument '2' to 'int strncmp(const char*, const char*, size_t)'
readMifare:121: error: expected '}' at end of input
}
exit status 1
invalid conversion from 'uint8_t* {aka unsigned char*}' to 'const char*' [-fpermissive]

@Dahacker305: remove the const.

"if (success && !strncmp(uid,{ 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 },8))" - no you cannot do that. The ID must be an array variable.


text:
ESP8266 Firmware Upgrade
Can I upgrade my ESP8266 firmware by connecting the pins in Arduino Uno, or do I still need a USB UART to Serial?

Looking at the schematic of arduino UNO here you can see that Pin 0 and Pin 1 are connected to the same line of RX TX of the ATMEGA8U2. So in theory (and assuming the ATMEGA8U2 behaves like any usb to uart IC) if you remove or disable the ATMEGA328P, your arduino should behave like any cheap usb to serial. The way you can "disable" ATMEGA328P is by setting it in constant reset mode as explained here
By manually reseting and setting the esp into flashing mode, you should be able to upload the new firmware to it from arduino IDE for example by selecting the ESP device.
Two notes on this
1 - The TX line of the ATMEGA8U2 is the marked RX on arduino Uno board and RX line of the ATMEGA8U2 is the marked to TX on arduino Uno board. That means your ESP RX should connect to pin 0 on arduino and TX of ESP should connect to pin 1.
2 - You might need voltage level conversion on pin 0 as ESP is a 3.3V device although in schematic there is 1K resistor in that line

source: Stack Exchange

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

sort: votes


text:
ESP8266 GET OR POST Request Timeout Error
i am using ESP8266 module serially with PC and i also tried it using uno
I am stuck at the following point
I am able to made connection to server but when i will send the following command
POST /test.php HTTP/1.1\r\nHost: 192.168.1.36\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 5\r\n\r\nb1=ON\r\n\r\n
every time i get the following server timeout error after 3 sec
+IPD,4,500:HTTP/1.1 408 Request Timeout
Date: Tue, 08 Mar 2016 14:10:07 GMT
Server: Apache/2.4.9 (Win64) PHP/5.5.12
Content-Length: 305
Connection: close
Content-Type: text/html; charset=iso-8859-1

408 Request Timeout

Request Timeout
Server timeout waiting for the HTTP request from the client.

Apache/2.4.9 (Win64) PHP/5.5.12 Server at localhost Port 80

4,CLOSED
And i am getting same issue whether i will use local server or online server

If you post the same string to your server(s) from your PC, bypassing the ESP8266, do you get the same error?

no through PC i m getting the repsonse from server

Try adding Connection: close\r\n to the header. Also remove the \r\n\r\n at the end. Lastly, are you using the correct length in AT+CIPSEND=...?

Try turning off your firewall.

yes i am sending the correct length

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


text:
Send custom HID values instead of keys
I've been building a small macro keypad based on the ATmega32U4. So far, I've been able to send standard key presses to the host. But since I want a program on the host system to react to the key presses, I only send the keys to serial to avoid typing anything. For now, this does work.
I want to send custom HID values to the host which won't result in regular key presses. As I've been reading around different blog and forum posts, most of them are just about building a regular keyboard or gamepad but don't go into how to make use of anything else.
This is what I got so far:
#include <Keypad.h>

const byte rows = 3;
const byte cols = 5;

char keys[rows][cols] = {
  { '1', '2', '3', '4', '5' },
  { 'q', 'w', 'e', 'r', 't' },
  { 'a', 's', 'd', 'f', 'g' }
};

byte rowPins[rows] = { 10, 16, 14 };
byte colPins[cols] = { 9, 8, 7, 6, 5 };

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );

void setup(){
  Serial.begin(9600);
}

void loop(){
  char key = keypad.getKey();

  if (key != NO_KEY){
    Serial.println(key);
  }
}

The only obvious way I see to achieve this is to change the keys array but I don't know to which values.

UPDATE
I changed the code according to the answer by Majenko:
#include <HID-Project.h>
#include <HID-Settings.h>

uint8_t rawhidData[255];

byte rows[] = { 10, 16, 14 };
byte cols[] = { 9, 8, 7, 6, 5 };

const int rowCount = sizeof(rows)/sizeof(rows[0]);
const int colCount = sizeof(cols)/sizeof(cols[0]);

void setup() {
  for (int row = 0; row < rowCount; row++) {
    pinMode(rows[row], OUTPUT);
    digitalWrite(rows[row], HIGH);
  }

  for (int col = 0; col < colCount; col++) {
    pinMode(cols[col], INPUT_PULLUP);
  }

  RawHID.begin(rawhidData, sizeof(rawhidData));
}

void loop() {
  for (int row = 0; row < rowCount; row++) {
    digitalWrite(rows[row], LOW);

    for (int col = 0; col < colCount; col++) {
      if (digitalRead(cols[col]) == LOW) {
        String coordinatesString = String(row+1) + String(col+1);
        uint8_t coordinates = coordinatesString.toInt();

        uint8_t megabuff[sizeof(coordinates)];

        megabuff[0] = coordinates;

        RawHID.write(megabuff, sizeof(megabuff));

        while (digitalRead(cols[col]) == LOW) {
          delay(50);
        }
        break;
      }
    }

    digitalWrite(rows[row], HIGH);
  }
}

I removed the serial output since I don't need that anymore. The code looks crude and needs further refactoring but it does work.

HID is a strange beast to get your head around.
It operates by way of "Report Descriptors". These are "maps" that lay out what the values you send mean. It's these descriptors that make a keyboard a keyboard and a mouse a mouse.
When you use Keyboard.h you attach a Keyboard report descriptor to the USB HID endpoint, and the computer knows to interpret the data coming in as keypresses. When you use Mouse.h you attach a Mouse report descriptor and the computer knows to interpret the data coming in as mouse movements and button presses.
If you want your computer to ignore the data that you send and allow your own program to be able to receive the raw data instead then you need to use a descriptor that the computer doesn't recognise. In such a case it just ignores the data.
There's a "Raw HID" library for Arduino that does that - it uses a "blank" report descriptor that just gives you a plain 64 byte block of data to do what you want with.
There's a good HID library by Nico Hood that implements the raw mode (as well as others).
For receiving the data on your computer you will have to have your program directly interface with the USB HID system. There's plenty of libraries for most languages to do this for you (hidapi in C / C++, hid in Python, hid4java for Java, etc).

Great information. For anyone looking, there is a critical bug in referenced HID library that breaks RawHID.write(); . Be aware of this bug before proceeding down that path. https://github.com/NicoHood/HID/issues/133

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


text:
Simple ESP32 MCP2515 CAN code to VP230
I have a working code that uses MCP2515 CAN module. Wanted to minimize the size of required modules, so I went with VP230 CAN transceiver and I'm having trouble relaying the same data through different libraries. All it has to do is log in with the first ''payload1'' and send voltage instruction with ''setdefaultvolt''. Any help is greatly appreciated.
MCP2515 code:
#include <mcp_can.h>
#include <mcp_can_dfs.h>
#include <SPI.h>
#include <Wire.h>

//pins:
#define CAN_INT 17                                                                         // Set INT to pin 2
MCP_CAN CAN(5);                                                                         // Set CS to pin 4 (D2)

void setup()
{
  Serial.begin(115200);
  delay(100);
  pinMode(17, INPUT);                                                                       //Setting pin 2 for /INT input

START_INIT:
  if(CAN_OK == CAN.begin(MCP_ANY, CAN_125KBPS, MCP_8MHZ))
  {
  }
  else
  {
    delay(100);
    goto START_INIT;
  }
  CAN.setMode(MCP_NORMAL);                                                        //set operation mode to normal so the MCP2515 sends acks to received data.
  unsigned char payload1[8] = {0x16, 0x50, 0x71, 0x07, 0x97, 0x089, 0x00, 0x00};  //login data with serial number
  CAN.sendMsgBuf(0x05004804, 1, 8, payload1);                                     //send login data

  unsigned char setdefaultvolt[5] = {0x29, 0x15, 0x00, 0xFE, 0x10};              //this is the command for setting the default output voltage (Last two bytes, LSB first). 16 80 is the maximum voltage of 57.6 V
  CAN.sendMsgBuf(0x05019C00, 1, 5, setdefaultvolt);                              //send setup data
}

void loop()
{
}

VP230 code:
#include <CAN_config.h>
#include <ESP32CAN.h>

CAN_device_t CAN_cfg;

#include <SPI.h>
#include <Wire.h>

void setup()
{
  Serial.begin(115200);

  CAN_cfg.speed=CAN_SPEED_1000KBPS;
  CAN_cfg.tx_pin_id = GPIO_NUM_19;
  CAN_cfg.rx_pin_id = GPIO_NUM_23;

  CAN_frame_t my_frame;
  CAN_frame_t my_frame2;

  ESP32Can.CANInit();

  my_frame.FIR.B.FF = CAN_frame_ext;
  my_frame.MsgID = 0x05004804;
  my_frame.FIR.B.DLC = 8;

  my_frame.data = {0x16, 0x50, 0x71, 0x07, 0x97, 0x089, 0x00, 0x00};

  ESP32Can.CANWriteFrame(&my_frame);

  my_frame.FIR.B.FF = CAN_frame_ext;
  my_frame.MsgID = 0x05019C00;
  my_frame.FIR.B.DLC = 5;

  my_frame2.data = {0x29, 0x15, 0x00, 0xFE, 0x10};

  ESP32Can.CANWriteFrame(&my_frame2);

}

void loop()
{
}

Just spotted this, but if any one else finds it: You have one CAN speed set to 125kb on MCP2515 the other to 100kb on the VP230.
That's why you won't get anything!
Mark

from datasheet ...CAN controller at speeds up to 1 Mbps.
On the SN65HVD230 and SN65HVD231, pin 8 provides three different modes of operation: high-speed, slope
control, and low-power modes. The high-speed mode of operation is selected by connecting pin 8 to ground,
allowing the transmitter output transistors to switch on and off as fast as possible with no limitation on the rise
and fall slopes.

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


text:
Efficient way to save accelerometer data on sd card
I have analog accelerometer that transfer acceleration on 3 axis with frequency 5 kHz. I want to store that data in SD card for in txt file. My sketch is the following:
void loop()
{

  // Get raw accelerometer data for each axis
  int rawX = analogRead(A0);
  int rawY = analogRead(A1);
  int rawZ = analogRead(A2);

  // Scale accelerometer ADC readings into common units
  // Scale map depends on if using a 5V or 3.3V microcontroller
  float scaledX, scaledY, scaledZ; // Scaled values for each axis
  if (micro_is_5V) // Microcontroller runs off 5V
  {

    scaledX = mapf(rawX, 0, 1023, -scale, scale); // 3.3/5 * 1023 =~ 675
    scaledY = mapf(rawY, 0, 1023, -scale, scale);
    scaledZ = mapf(rawZ, 0, 1023, -scale, scale);

  }
  else // Microcontroller runs off 3.3V
  {
    scaledX = mapf(rawX, 0, 675, -scale, scale);
    scaledY = mapf(rawY, 0, 675, -scale, scale);
    scaledZ = mapf(rawZ, 0, 675, -scale, scale);
  }

   String dataString = "";
   // Concatenate string
   dataString += String(scaledX);
   dataString += "\t\t";
   dataString += String(scaledY);
   dataString += "\t\t";
   dataString += String(scaledZ);
   dataString += "\t\t";
   saveSD();
}

// Same functionality as Arduino's standard map function, except using floats
float mapf(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

void saveSD()
{
  // create file for writing
  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  // if file is available
  if (dataFile) {
    // save the data
    dataFile.println(dataString);
    // close file
    dataFile.close();
  } else {
    // if file is unavailable
    Serial.println("Error opening datalog.txt");
  }
}

So in loop I open file, write to it and after that close it. When my file will be big enough there will be bottle neck.It will take a lot of time to read and write file.
How to deal with saving data to files on SD card?
UPD:
I measured the time of executing code like that:
  ...
  start_open_t=micros(); // time in milli seconds
  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  delta_open_t=micros() - start_open_t ;
  // if file is available for writing
  if (dataFile) {
    // save the data
    start_write_t=micros(); // time in milli seconds
    dataFile.println(dataString);
    delta_write_t=micros() - start_write_t ;
    // close the file
    start_close_t=micros(); // time in milli seconds
    dataFile.close();
    delta_close_t=micros() - start_close_t ;
    ...

And there is the result:
Open time:
7656
Write time:
2176
Close time:
8076

The open time is increasing there is no surprise (with increasing the file size).
Write to file and close time is almost constant.
I thought to open file in setup() and initialize timer. Write to file in loop() and after some time interval to close the file, after that open new file and so on. But as can be seen the print operation dataFile.println(dataString); takes approximately 2 ms that is 500 Hz, and it is too slow. I need to register with 5 kHz.
If I print in serial the data is printed much faster but I can not  connect to usb because arduino is located to far (approx 30 meters).
May be there is the way to connect to serial with wifi or bluetooth or may be there are another methods to store the data fast?

I thought about offering this as a potential duplicate, but I didn't feel that strongly about it, and you got some good advice (not mentioned there) below that I'm going to vote up. Still, you may find it an interesting read.

Thanks for advice, I'll read

You'd edited to include the line: "May be there is the way ... serial with wifi or bluetooth or ... another methods to store the data fast?" It's a valid question (or at least a kernel) but it is a different question that's been shoehorned in there. And that's been done after the original question had already been given a thoughtful answer. IMO, if you want to ask something like that, remove it from this question and start a new one. You'd need to be careful that you're asking something that can be factually answered and not something that is only a matter of opinion.

I can see it is safe to open/close the file every time, especially closing, as if the Arduino loses power, the entire file can be corrupted possibly.
However, I can find of some 'solutions':

Backup battery

Open the file in setup(), and only close the file when the backup battery becomes active (instead of closing the file after every write). This will however need an external battery, and some implementation to check if it is active. Also, during the external battery is active, no data should be written.

Using multiple files

More easier is to use multiple files, and write each time period (less than the  size of the file that cause problems) in a separate file. You can either close the file after each write, or when starting a new period, meaning when the Arduino loses power, you only lose the last time period.

Using binary format

This can be used in combination with solution 1 and 2, and is to not write the files as text files but in binary format, reducing the size considerably.

Thanks for replying. About battery, for now I'm gonna to use crone battery as main power for arduino because is located away from electrical power. About second your suggestion I thought about it, so I need to measure time of loop and time of opening file with different file sizes and find the max size that it can open not to be too slow to catch data from acceleromerter. And your third suggestion is great I should try it!

If your file doesn't need to be humanly readable, that is the easiest solution. I think it can save a factor 4 , and maybe more if you use interpunction and spaces.

Thanks, I can decode the file after that. I have an update, I measured the time of open, write and close operation and it seems that it not the best way to store logs on sd. See updates

Use binary format, that will reduce the write time.


text:
How to connect a 4 channel relay switch directly to a 5V power source?
When connecting a 4 channel relay to a Arduino Pro mini, there is a noticeable power drain from the board when relays are active. This is clearly visible as the 16x2 LCD dims. I remember reading that this could damage the Arduino, is this true?
In any case, since the entire project will be powered by a rechargeable 12V battery, I bought some buck converters to lower the voltage from 12V to 4.66V (this is what I identified the output to be from the Arduino, I even tried increasing it to 4.8V), so I can power the relay switch directly instead of going through the Arduino.
However, the relay does not power on and I have no idea why.
Can someone help me understand? I'm new to this.

Parts

eBoot Mini MP1584EN DC-DC Buck Converter
4 Channel 5V Relay Shield Module
Mini Nano V3.0 ATmega328P Microcontroller Board

Edit
I found this answer but I do not know if it applies and, if it does, what changes I would need to make with my current connections.

Maybe you never connected the grounds? Please show your wiring.

The 5V is from the buck converter to the relay, then the GRND goes back to the battery through the buck converter again.

What about to the Arduino?

@Majenko sorry for the crude drawing, but this is the connections I have.

That's far less crude than many people post...  Those connections look fine to me.

Then I am dumbfounded and I have no idea why it does not power on :/

Those connections will will work if the converter passes the ground through, not all do. Also without a link to technical information on the particular parts All I can do is guess. Another possibility is the relay module is not properly jumpered or it does not have 5V relays as pictured. Specs help eliminate these questions. I assume you have the 12V to the pro mini on the Vin terminal not 5V.

Yes, the Arduino is powered through the Vin connector. I thought of sending the ground back to the Arduino, but was not sure if this would be good since the source did not come from it.

@Majenko I added more details to the question, and an answer, but I'm a programmer, not an electrician; a lot from that answer is not clear to me.

Just a few question: 1) First you say "there is a noticeable power drain from the board when relays are active".  Later you say "the relay does not power on".  This is confusing.  Do the relays activate or not? 2) If using a power supply what is its Amperage rating. If a battery, its mAh rating? 3) According to your diagram, it may be that jumper JD-VCC is necessary.  Is jumper JD-VCC installed?

@st2000 1) when I connect the relay's VCC to the Arduino's 5V output, everything works, but there is a power drain on the LCD screen module (connected to a different 5V output) when activating relays, so I'm going for total isolation instead and it does not work, 2) the battery is rated at 12V and 10Ah 120Wh, 3) the JD-VCC jumper is installed (as I understand, removing the jumper expects the relays to be powered on 3.3V, right?)

That battery sounds more than enough.  It's charged correct? Just checking, your power wires are not long (perhaps less than 15 meters) and of sufficient thickness. For example, 16 gauge could carry 5 Amps.  Which is likely 10 times you needs. You can not go total isolation. If you use 2 different power sources, their grounds need to be connected together.  Regardless, your diagram appears to be fine. I could ask how your LCD is powered and what is it's model number.  Or you could add it to your question.

OK,

You should not ever use inductive load from voltage regulator shared with MCU.
Relays are massive eaters, and the 4.6 volts were actually caused by arduinos NTC kicking in to protect arduinos supply, the relays on your picture are designed for power around 5DC so you should design your circuit in that regards. I am impressed by the fact that little regulator on pro miny even survived it, meaning its likely to be reasonably made board.
The Pro miny voltage regulator is nowhere near as powerful as thatone on Nano or UNO and only barely manages to run anything more then the MCU itself.
Watch your current. I am not sure whats the max current of your buck converter. Amazon specifications usually do not concern themselves with petty things like reality. SO it might not be strong enough to run all 4 relays. Though Colour is matching more often then wrong
Again relays are massive power eaters and the lower voltage, the higher current so you can often lower your consumption by using relays made for higher voltage.
Next batteries don't store that much power, get influenced by external influences and their capacity further decreases as the life goes. you can save a lot of power by using transistors/mosfets where possible.

It takes considerable additional design steps to make project run on a battery and replacing relays for bigger transformers or mosfets is often part of it.
Set any of the relays on, in arduino code and measure its voltage against ground.
If its 5V then arduino is sending signal fine.
If it is not, then check the resistance between its and arduinos ground. if its just few ohms look for issues on the arduino.
if resistance between grounds is big or even unmeasurable, then connect the arduino ground with relay board ground.
If you can measure 3-5V (Dependant on a pro mini version) between arduinos output and the ground then you don't have enough power on the relay modules supply.
Extra note:Make sure the arduino is not powered from buck converter as volage regulator has minimum voltage diference it can drop and could not be powered via regulator from a supply of less then 6.something Volts
As stated in Jroberts answer once everithing is working, you might want to disconnect the suplly to arduino from 12 volt source to Vin; and connect your arduino to your buck converter set at 5V (4.95ish-5.05ish) to 5V pin adding 10uF capacitor between the 5V and GND on arduino.
The buck converters are more efficient in dropping voltage, then voltage regulators, so that would extend your battery life. (this isnt majourisue as compared to the arduinos consuption is tiny compared t the consumption of the relays

It feels weired when Edgar Bonet stopped edited all mine answers.  I was newer meant to stop him, it was just an observation...

I don't see relay coils powered from the Mini in the question

@juraj: That is reference to the original setup where asker describes to power it via arduino and that the voltage output reduced and LCD dimmed, this according to the asker made asker believe that the voltage he measured was a correct voltage to output from buck converter, supplying too low voltage in his second (new) setup

I'm not a double-E but I'll take a stab at it.
Arduinos' on-board voltage regulators are not particularly efficient; they sink to ground whatever the board doesn't draw, dissipating it as heat. And they usually are not provided with heat sinks, meaning the regulator is heat-limited. You're powering the Arduino with 12v, so whatever current the Arduino does draw, that same current times 7 volts (the voltage drop from 12v to 5v) is waste heat. Driving four relay coils draws (using the specs on the Amazon page) adds 80mA (times 7v) to that heat dissipation.
It looks like at least some Pro Minis (yours?) use a Micrel 2095 voltage regulator which has internal current limiting which may include thermal protection(?) -- shutting off your Arduino when the regulator gets too hot.
Despite that some of the above is speculative on my part, it does suggest an experiment. You've got a regulated 5v source - instead of powering the Arduino at Vin from the 12v source, try powering it's +5v pin with +5, which would significantly reduce the regulator's power dissipation (and therefore, its temperature).

I don't see relay coils powered from the Mini in the question

The product description I referred to in my answer says: "5V 4-Channel Relay interface board, and each one needs 15-20mA Driver Current. " [emphasis mine]

but the coils are powered from the 5 V pin of the relay board and that is not connected to Micro

I think this is not an answer, but rather an extension to one of the points in mine answer or one of the points in askers questions. It would be better as just a coment. I wont downwote as its interesting addition, but neither upwote, as it does not contain the actual answer in additional info.


text:
sim 900 sending wrong sms -" Ü " to mobile phone from arduino
i am having a problem while sending sms from arduino to a specific number. cell phone getting sms but every time it gets same unicode -" Ü " . plz help us
//--------------------------
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3);

void setup()
{
    mySerial.begin(115200);
    mySerial.print("\r");
    delay(1000);
    mySerial.print("AT+CMGF=1\r");
    delay(20000);

    mySerial.print("AT+CMGS=\"+91..........\"\r");

    delay(20000);
    mySerial.print("Hello!\r");   //The text for the message
    delay(10000);
    mySerial.write(0x1A);  //Equivalent to sending Ctrl+Z
}

void loop()
{

}

So you try to send "Hello!", but receive "Ü"?

yahhh...do you know the reason?

Ü in SMS has the same value (0x5E) as ^ in ASCII. Nothing helpful there. The delays seem a bit long to me. Try lowering those.

which delay ? is it after ' mySerial.print("Hello!\r") ' ?

The 20000 and 10000 ones. Waiting 10 or 20 seconds is extremely long.


text:
Arduino uno not writing to file
I'd like the arduino to write to a file whenever an ajax call is made. The ajax works, but it doesn't write to the file. All other code inside the ajax handler does execute.
void handle_ajax() {
    int startUrlIndex = HTTP_req.indexOf("button");
    int endUrlIndex = HTTP_req.indexOf(" HTTP");
    String url = HTTP_req.substring(startUrlIndex, endUrlIndex);
    int startButtonIndex = url.indexOf("device-") + 7;// 7 is length of device-, I really just want the number.
    int endButtonIndex = url.indexOf("&");
    String button = url.substring(startButtonIndex, endButtonIndex);
    int startStateIndex = url.indexOf("state=") + 6; // 6 is length of state=, I really just want the number.
    String state = url.substring(startStateIndex);
    int device = button.toInt();
    int newState = state.toInt();
    dim_light(device, newState * 12);
    write_config("", "text");
}

bool write_config(String line, String text) {
    configFile = SD.open("config.ini", FILE_WRITE);

    if (configFile) {
        configFile.write("Dipshit");
    }

    configFile.close();
    Serial.println("Works.");
    return true;
}

Hi, and welcome to the Arduino StackExchange community. Just a couple of questions to try and clarify the situation: 1. Are you able to write to the SD card outside of your function? I.e., can you write something in setup()? 2. Can you expand your code snippet to include the parts where you configure the SD card?

Where have you defined SD and configFile? The statement configFile.close(); belongs into the {} just after the line with configFile.write("Dipshit");.

I fixed it already, ran out of RAM again.

You have run out of RAM. Consider moving string literals into flash with thr F() macro.

We've done that before, we don't use any strings right now though.


text:
Arduino Digital Pins Control with ESP8266
I am currently working on my FYP. I need to control 15 servos (13 for x2 Robotic Arms + 2 for Camera) and 4 motors of my Robotic kit via webserver. I have the following options:

NodeMCU
Arduino Mega + ESP8266

Now since NodeMUC has only 10 digital pins the only option I am left with is (Arduino Mega+Esp8266).
I have used the following code to control servo on a NodeMCU.
#include <Servo.h>
#include <ESP8266WiFi.h>

Servo servo;

const char* ssid = "ssid";
const char* password = "password";
WiFiServer server(80);
void setup() {
  servo.attach(4); //or any pin

  servo.write(0);

  Serial.begin(115200);
  delay(10);

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

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

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

}

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

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();
  if (request.indexOf("/?30") != -1)  {
    servo.write(30);
  }

//
  if (request.indexOf("/?90") != -1)  {
    servo.write(180);

  }

  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("");

  client.println("

");
  client.println("<button>30</button>");
  client.println("<button>60</button>");
  client.println("<button>90</button>");
  client.println("<button>120</button>");
  client.println("<button>150</button>");
  client.println("<button>180</button>");
//  client.println("<button>Thirty Mins</button>
");
  client.println("");

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

}

My question is that the can the code written for NodeMCU be used with ESP8266 to control Arduino Digital Pins? I want the same code to be used.
PS : I don't want to use SoftwareSerial library and ATC commands.
Or some alternative to NodeMCU with same functionality as NodeMCU but with more GPIO pins.

you could try Standard Firmata sketch in Arduino and FirmataMaster library in ESP8266

thanks!
but can the same code for NodeMCU be used for ESP2866 also.

your sketch looks like you use the Arduino core for esp8266 on the NodeMCU hardware


text:
Should millis() be stored in a variable once each loop, or called for every reference?
When comparing the value of millis() numerous times per loop(), are there reasons for/against storing it in a variable once at the top of loop(), v.s.  calling millis() each time?
The most basic example code "Blink Without Delay" is written as such:
void loop() {
  //...
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // Do stuff
  }
}

I don't really she why the example code above bothers storing millis() in a variable "currentMillis" at all. (I realize that in such a simple program, there would be no noticeable difference.)
I imagine that if I use a variable, the longer the duration of loop(), and the further down my use of the "currentMillis" variable, the more deviated the stored value will be.
I'm wondering the other ramifications of either method as well.
Does calling millis() directly hog resources of any sort? If not, I imagine it would be better to not use a variable, so as to get a more accurate time value and save a bit of memory.

Personally I'd save it in a variable if I had to call it more than once. That's because I don't want to call functions more times than strictly needed (the overhead is higher) and because I want that the loop is executed as if it happened "instantaneously". I mean, if you have if (millis() > interval) do_something; a_function_that_takes_10ms(); if (millis() > interval) do_something_else; I'd like the do_something_else to be executed always after do_something. If I store the millis value, this is correct, otherwise who knows..

As @frarugi87 may be implying above but worth stating explicitly, millis() does overflow (after about 50 days) and calling it repeatedly will on occasion end up with a lower value later in the program.

The primary downside to calling a function each time is that it may take more CPU cycles to complete the overall loop. The difference in CPU cycles, if any, depends on the actual implementation of the function and how the compiler optimises the call. For low-CPU sketches, this difference is probably unnoticeable.
Generally speaking, it is good programming practice to avoid calling a function more times than is necessary. Really the function should be called directly only if you have reasons to believe, based on desired timing and procedure order, that using the same return value in multiple places could create problems. In the example sketch given, there would be almost no functional difference between using a variable or calling the function inline.
Another advantage to using a variable is that you can give it a name that makes the code clearer to understand. In the example given, the relationship between currentMillis and previousMillis is very clear. In the case where a function returns a more complex object, such as a class or structure instance, using a variable (of the appropriate type) can be really useful since this would allow multiple members of the returned data to be accessed without calling the function multiple times. In fact, even in the given example, the function would have to be called twice since currentMillis appears twice in the loop.
As far as memory goes, an unsigned long uses very little.


text:
I2C LCD Serial Interface Board not displaying text (wrong pins?)
I have a 1602 LCD screen that works fine on its own. However I wanted to free some pins by using an I2C / IIC LCD controller I purchased separately.
While the controller seems to be communicating with my Arduino UNO on the right address, I cannot get text to display. By default (no code) it seems the LCD will have 1 line of 16 solid "squares". When using address 27 in my code, the LCD will change to 2 lines of 16 squares (see photo below). The code also calls for the backlight to flash 3 times, which works. However I cannot get anything but 2 lines of squares. (Full code is at the bottom of this question).
I'm using the LiquidCrystal_I2C library by F Malpartida, which seems to be commonly used.
Is there a better library I should be using?
I'm wondering whether it's just the wrong pins being used in the code. All sketches I see online use the following pins:
//                    addr,en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
// Set the LCD I2C address

But all of the 1602 LCDs I see online have the same pins as mine, as you can see in my photo below:

These pins seem to be standard:

To further confuse me, the pins on the LCD board start with 1 on the left, yet the default code's pins seem to start with 0! So I tried changing the code's pins to the numbers on the LCD board. The LCD no longer changes to 2 lines of squares and no longer blinks the backlight. I then tried subtracting 1 from each pin (to start from 0), same result. I then tried used the default pins minus 1, same result. Thus the default pins are somehow more correct?! What am I doing wrong?
Has anyone else gotten one of these I2C controllers to work for them, and if so, how?
Full code:
/* YourDuino.com Example Software Sketch
 16 character 2 line I2C Display
 Backpack Interface labelled "YwRobot Arduino LCM1602 IIC V1"
 terry@yourduino.com */

/*-----( Import needed libraries )-----*/
#include <Wire.h>  // Comes with Arduino IDE
// Get the LCD I2C Library here:
// https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads
#include <LiquidCrystal_I2C.h>

/*-----( Declare objects )-----*/
// set the LCD address to 0x27 for a 20 chars 2 line display
// Set the pins on the I2C chip used for LCD connections:
//                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

void setup()   /*----( SETUP: RUNS ONCE )----*/
{
  Serial.begin(9600);  // Used to type in characters
  lcd.begin(16,2);   // initialize the lcd for 16 chars 2 lines, turn on backlight

// ------- Quick 3 blinks of backlight  -------------
  for(int i = 0; i< 3; i++) {
    lcd.backlight();
    delay(250);
    lcd.noBacklight();
    delay(250);
  }
  lcd.backlight(); // finish with backlight on

//-------- Write characters on the display ------------------
// NOTE: Cursor Position: (CHAR, LINE) start at 0
  lcd.setCursor(0,0); //Start at character 4 on line 0
  lcd.print("Hello, world!");
  delay(1000);
  lcd.setCursor(0,1);
  lcd.print("HI!YourDuino.com");
  delay(8000);

// Wait and then tell user they can start the Serial Monitor and type in characters to
// Display. (Set Serial Monitor option to "No Line Ending")
  lcd.clear();
  lcd.setCursor(0,0); //Start at character 0 on line 0
  lcd.print("Use Serial Mon");
  lcd.setCursor(0,1);
  lcd.print("Type to display");

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{
  {
    // when characters arrive over the serial port...
    if (Serial.available()) {
      // wait a bit for the entire message to arrive
      delay(100);
      // clear the screen
      lcd.clear();
      // read all the available characters
      while (Serial.available() > 0) {
        // display each character to the LCD
        lcd.write(Serial.read());
      }
    }
  }

}/* --(end main loop )-- */

Did you remember to add the pullups?

@Ignacio, Can you elaborate? I'm only using 4 pins total. A4 and A5 for SDA and SCL respectively. 5V+ and GND for the controller.

http://electronics.stackexchange.com/questions/102611/what-happens-if-i-omit-the-pullup-resistors-on-i2c-lines

As far as I know, the pull-up resistors should be integrated with the display. Did you try different addresses? I have a similar one, which works on address 0x3F. Maybe this helps.

Probably not the problem, but have you tried adjusting the contrast using the potentiometer? The numbers in the code refer to which pin on the PCF8574 chip is connected to which pin on the lcd board. P3 on the I2C board is evidently connected to the backlight pin on the LCD. But I think the other pins are wrong somehow. Try using a multimeter to see where the P0-P7 pins of the PCF8574 go to which pins on the lcd header.

The board was sold as "address 27", and 27 is the only address that responds at all. It's actually customizable by soldering the A1 A2 and A3 pins just above the trimming pot seen in the photo.

@IgnacioVazquez-Abrams, although the pullups should be built into the controller, I tried adding them manually to no avail.

@Gerben, I adjusted the trimmer already and it's either full blocks or nothing at all. There are two circular plastic blobs on the bottom of the LCD board. I cannot actually see any ICs. I don't think I have any way to see or measure the pins of the PCF8574 because there are only 8 contacts on the back of the board, but the PCF8574 has 16. I'm ready to blame the controller.

Although it may not be the issue, you should pay attention to the soldered pin headers on the LCD, from the picture they appear to not completely cover the copper around the hole; I would try to improve these solder points first.

The PCF8574 is the chip on the I2C interface board, not on the lcd board. Please re-read my comment, it see if it makes sense now. Otherwise, let me know.

@Gerben, derp. I tested the chip with a multimeter, however I am still completely confused. Pins 9-12 on the chip correspond to D4-D7 on the lCD. Pin 6=E, 5=RW, and 4=RS. I cannot figure out what pin 7 actually is. Using those values gives me no response from the LCD again. Also, am I supposed to subtract 1 from those pins? Because again, all the default codes out there have pin 0=RS. But that can't be, because the first pin on the chip is A0 (address). Basically, changing any single pin will either kill the backlight response or stop the 2nd row from showing the block characters.

The numbers 0-7 in the code refer to the P0-P7 pins on the PCF8574. If you look at the datasheet, P0 is on pin 4, P1 on 5, P2 on 6, P3 on 7, P4 on 9, P5 on 10, P6 on 11, P7 on 12.
So in your case, P0 goes to RS, P1 to RW, P2 to E P3 to backlight, P4-P7 to D4-D7. So your numbers in the code you've given were correct (i.e. LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);).
So that wasn't the problem. Try reseating the headers in the breadboard, as there could be an improper connection. Also resolder the header on the LCD, as they aren't great solder joint (to little solder).

I have the very same problem. I2C scanner found the display. I also traced the connections and got the same pin setup. I can turn on/off the display - it has a cursor but no text. No clue what's going on. Did you solve it eventually?

@tcurdt I've had no success with those particular components. I found that I can buy a 1602 LCD with an I2C controller already attached for nearly the same price, and that worked for me.

Just got into this. Backlight control works, no text output on display.

It's a good idea to check what library and code the seller told to use, most of them provide samples.

I bought the SainSmart 20x04 and I also had to change the address to 0x3F.  My backlight jumper was missing, that little header at the right of the I2C board provides the backlight power.  Some code I found included this:
lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);

First of all, it looks like these wires aren't properly connected:

I haven't disassembled a female jumper before, so that might not be the issue. However, it seems likely that this could be a cause.
Also, you need to adjust the contrast by turning that trimmer (the blue thing that looks kinda like it has a screw in it). LCDs will either display nothing, a washed out version of the text, or blue boxes if the contrast is not set correctly. This is probably the cause.

The jumpers are like that only because I moved the board for the photo. Also I adjusted the trimmer already and it's either full blocks or nothing at all.

Change this code:
LiquidCrystal_I2C lcd(0x26, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

To this:
LiquidCrystal_I2C lcd(0x26, 2, 1, 0, 4, 5, 6, 7, 8, POSITIVE);

(The argument before "POSITIVE" is changed from a 3 to an 8)

Any explanation why? There is no P8 on the PCF8574.


text:
Using SPI Interrupt causes two servos to lose functionality
My Arduino MEGA clone (ATMEGA 2650) reads SPI data as a slave using an interrupt.
There are also two servos that make an arm (shoulder and elbow).

When I comment out the line that attaches the SPI interrupt, the servos
work properly.
When the SPI interrupt is attached, three strange things happen:
1) The PWM of the elbow remains at a fixed duty cycle. The shoulder works fine.
2) The shoulder PWM is somewhat jittery time-wise, I assume though that this is unavoidable with interrupts.
3) Writing an angle to either servo, (appears to) write to both servos! (In the software anyway.) So if I only write to the elbow, the shoulder will have the same value ( printed with shoulder.read() ). And vise-versa.

Again, none of those problems occur when I comment out the SPI interrupt attach.
It doesn't make sense to me though. Why would attaching an interrupt make two servos have the same value? And how can the values of the servos be the same, when only one PWM duty cycle actually changes!?
I wonder if this is a timer issue. Maybe the SPI interrupt interferes with the servo timers or something.
How can I receive SPI messages while also controlling two servos?
#include <Servo.h>
#include <SPI.h>

const float pi = 3.14159;
const float L1 = 27;
const float L2 = 27;
float c2;
float s2;
float psi;
float theta;

float angle_shoulder = 90;
float angle_elbow = 90;

volatile int arm_x;
volatile int arm_y;
volatile int puck_x;
volatile int puck_y;

Servo shoulder;
Servo elbow;

int sweepDir = 0;
int sweep1 = 0;

unsigned char spiBuffer[5];
volatile byte buffPos;
volatile bool process_spiBuffer;

void setup()
{
    Serial.begin(115200); //Initialize serial communication
    Serial.println("### SETUP ###");

    shoulder.attach(25); //5
    elbow.attach(43); //3

    // BEGIN SPI SETUP
    // Turn on SPI in slave mode
    SPCR |= bit(SPE);

    // Send on master in, *slave out*
    pinMode(MISO, OUTPUT);

    // Get ready for an interrupt
    buffPos = 0;   // buffer empty
    process_spiBuffer = false;

    // Turn on interrupts
    SPI.attachInterrupt();

    // END SPI SETUP
} // END SETUP()

void loop()
{
    arm_y = 30;

    if (process_spiBuffer)
    {
        spiBuffer[buffPos] = 0;
        // X is a two-byte value, SPI only sends one byte at a time, so merge the bits upon receipt
        puck_x = (spiBuffer[1] << 8) | spiBuffer[2];
        puck_y = spiBuffer[3];
        //Check if received message is acceptable, else throw warning and reject message
        if (spiBuffer[0] != '<' || spiBuffer[4] != '>' || puck_x < 0 || puck_x > 320 || puck_y < 0 || puck_y > 240)
        {   //Message received was corrupted
            Serial.print("SPI: Bad MSG Data!:\"");
            //Serial.print(spiBuffer);
        }
        else
        {   //Message received "OK"

            Serial.print("SPI MSG Received:\"");
            //Serial.print(spiBuffer);
            Serial.println("\"");

            Serial.print("SPI puck coords:(");
            Serial.print(puck_x);
            Serial.print(",");
            Serial.print(puck_y);
            Serial.println(")");

            // Decide on new paddle position. (x,y) of puck is 90degrees CW from AI (arm) POV, so x and y are swapped. Arm origin (0,0) is at bottom-right corner from the AI POV.
            arm_x = map((240 - puck_y), 1, 320, 5, 49); // map(value, fromLow, fromHigh, toLow, toHigh)

        }
        buffPos = 0;
        process_spiBuffer = false;
    }

    crunchAngles();
    moveArm();

} // END loop()

void crunchAngles()
{
    c2 = (sq(arm_x) + sq(arm_y) - sq(L1) - sq(L2)) / (2 * L1 * L2);
    s2 = sqrt(1 - sq(c2));

    angle_elbow = acos((sq(arm_x) + sq(arm_y) - sq(L1) - sq(L2)) / (2 * L1 * L2)) * (180 / pi); // theta?
    angle_shoulder = asin((arm_y * (L1 + L2 * c2) - arm_x * L2 * s2) / (sq(arm_x) + sq(arm_y))) * (180 / pi); // psi?

}

// Update the servos
void moveArm()
{
    // TODO: Clip servo output with serial warning
    if (angle_shoulder < -10) { angle_shoulder = -10; } // Actual min angle is about -18deg (Model HS-225BB)
    else if (angle_shoulder > 179) { angle_shoulder = 179; } // Actual max angle is about 181deg (Model HS-225BB)

    shoulder.write(180 - angle_shoulder + 2); // Shoulder increments clockwise, so subtract from 180

    if (angle_elbow < 0) { angle_elbow = 0; } // Actual max angle is about -5deg (Model SG90)
    else if (angle_elbow > 170) { angle_elbow = 170; } // Actual max angle is about 190deg (Model SG90)

    elbow.write(angle_elbow + 3); // Elbow increments clowise from

}

ISR(SPI_STC_vect)
{
    byte c = SPDR;

    if (buffPos < sizeof spiBuffer)
    {
        spiBuffer[buffPos++] = c;

        // End of message is ">"
        if (c == '>') // if (c == '\n')
            process_spiBuffer = true;

    }
}

My initial reaction is that it isn't the interrupt per se, but what you do when you detect that flag process_spiBuffer. As a test you could make that flag be set by closing a switch (which you test in loop) and see if the same problem arises. That would rule in or out the interrupts. Meanwhile you could also comment out your debugging displays and see what happens.

One problem is here spiBuffer[buffPos] = 0; - you are writing past the end of the buffer.

@NickGammon - The SPI code is based on your post, which has that same line in it :) http://arduino.stackexchange.com/a/16349/4455 , I do understand that the example code wasn't suited my purpose. For my sketch, it could indeed use some further optimization, however I believe the messages are all received properly (as realized by printing the results). I will test the flag as you said tomorrow. This is for my senior project where a PI sends data to the Arduino, and this communication issue is halting the entire thing, so I will be putting a lot of effort into fixing this.

Yes I see what you mean. But my buffer was 100 bytes. :) You are right though, I should check for sizeof (buf) - 1.

To be honest, I didn't understand the purpose of that line. Why would you set the last to 0? And are you saying it should be spiBuffer[sizeof(buf) - 1] = 0; ?

In the example code you copied from, I was sending an ASCII string, so that final 0x00 was the C-string terminator. That's all. In your case you don't need it.

See my amended answer. It all seems to work now.

You have multiple issues here. For a start, you have a buffer (spiBuffer) of 5 bytes, into which you place <Xxy> (that's 5 bytes) and then finish off with:
    spiBuffer[buffPos] = 0;

That has now overwritten some other memory.

Next, you don't seem to be detecting the "<" symbol and resetting to the start of the buffer, so if you ever get out of sync, you will stay out of sync. I suggest something like making buffPos equal to 0xFF initially. Then in the ISR:
ISR(SPI_STC_vect)
{
    byte c = SPDR;

    // exit if haven't processed last one
    if (process_spiBuffer)
      return;

    if (c == '<')
      buffPos = 0;
    else if (buffPos == 0xFF)
      return;  // ignore until we get a '<'

    if (buffPos < sizeof spiBuffer)
    {
        spiBuffer[buffPos++] = c;

        // End of message is ">"
        if (c == '>')
            process_spiBuffer = true;

    }
}

Now we use 0xFF as a "flag" that we haven't received a "<" yet. When we do, we reset buffPos to zero, ready to process the next 5 bytes. In the main loop, once we are done with processing the buffer we set buffPos to 0xFF again (rather than zero). Also you might have the ISR called before you have processed the previous one, so I put in a test to exit if process_spiBuffer is true when you enter the ISR.

I found your code to work out the arm positions confusing. For debugging this issue I would replace it with simply moving the servo to the position received by SPI, eg.
   // crunchAngles();
   // moveArm();

   elbow.write (puck_x);

Now just debug that rather than getting confused about the difference between interrupt issues and logic issues. I found once I had done that, that my servo responded without any major issues (there was a bit of jittering occasionally).

I found that I got a lot of data errors until I slowed down the sender (a few microseconds delay after each SPI.transfer) because sending SPI at high speed didn't give the receiving sketch time to put the data into the buffer.

The servo library is rather dependent on interrupts (it manually does the PWM duty cycles). I wrote a sketch a while back that controls one server by using the hardware timer (Timer 1) rather than interrupts:
const byte potpin = A0;  // analog pin used to connect the potentiometer

const unsigned long PRESCALER = 8;         // Timer 1 prescaler
const float PULSE_PERIOD = 0.020;          // 20 ms
const float ZERO_POSITION_WIDTH = 0.0005;  // 0.5 ms
const float FULL_POSITION_WIDTH = 0.0024;  // 2.4 ms

// how far apart the pulses are
const unsigned long PULSE_WIDTH_COUNT = F_CPU / PRESCALER * PULSE_PERIOD;
// minimum pulse width (-45 degrees)
const unsigned long ZERO_POSITION_COUNT = F_CPU / PRESCALER * ZERO_POSITION_WIDTH;
// minimum pulse width (+45 degrees)
const unsigned long FULL_POSITION_COUNT = F_CPU / PRESCALER * FULL_POSITION_WIDTH;

void setup()
  {
  TCCR1A = 0;          // disable all PWM on Timer1 whilst we set it up
  ICR1 = PULSE_WIDTH_COUNT - 1;   // frequency is every 20ms (zero-relative)

  // Configure timer 1 for Fast PWM mode using ICR1, with 8x  prescaling
  TCCR1A = bit (WGM11);
  TCCR1B = bit (WGM13) | bit (WGM12) |  bit (CS11);  // fast PWM top at ICR1
  TCCR1A |= bit (COM1A1);  // Clear OC1A/OC1B on Compare Match,
  pinMode (9, OUTPUT);
  }   // end of setup

void loop()
{
  int val = analogRead(potpin);  // reads the value of the potentiometer (value between 0 and 1023)
  OCR1A = ZERO_POSITION_COUNT + (val * (FULL_POSITION_COUNT - ZERO_POSITION_COUNT) / 1024) - 1;
  delay(15);                     // wait for the servo to get there
} // end of loop

That is for the Atmega328P, not the Mega, but you could adapt it easily enough. You could use Timer 2 for the other servo (I think).
Since it doesn't use interrupts, then having interrupts going off in the background won't affect the servo.

Example code
After considerable mucking around, I've got a simpler case working reliably.

Writing an angle to either servo, (appears to) write to both servos! (In the software anyway.) So if I only write to the elbow, the shoulder will have the same value ( printed with shoulder.read()

That's exactly what happened to me! Until ... I realized I should power the servos independently. As soon as I connected both servo's +5V and Gnd to an external power supply (and connected the ground of the power supply to the Mega) it all started working properly. So, lesson #1 is: power your motors properly!
I made up a test "driver" on my Uno using the code below:
#include <SPI.h>

void setup (void)
{
  digitalWrite(SS, HIGH);  // ensure SS stays high
  SPI.begin ();
  SPI.setClockDivider(SPI_CLOCK_DIV32);
}

void loop (void)
{
  int val;

  // enable Slave Select
  digitalWrite(SS, LOW);

  SPI.transfer ('<');
  val = analogRead (0);    // read A0
  SPI.transfer (highByte(val));
  SPI.transfer (lowByte (val));
  val = analogRead (1);    // read A1
  SPI.transfer (highByte(val));
  SPI.transfer (lowByte (val));
  SPI.transfer ('>');

  // disable Slave Select
  digitalWrite(SS, HIGH);

  delay (100);
}

That reads a pot on A0 and A1 and sends the full value (2 bytes) over SPI (which is slightly different to what you are doing).
Then the receiving end (on a Mega2560) has this code:
#include <SPI.h>

const unsigned long PRESCALER = 8;         // Timer prescaler
const float PULSE_PERIOD = 0.020;          // 20 ms
const float ZERO_POSITION_WIDTH = 0.0005;  // 0.5 ms
const float FULL_POSITION_WIDTH = 0.0024;  // 2.4 ms

// how far apart the pulses are
const unsigned long PULSE_WIDTH_COUNT = F_CPU / PRESCALER * PULSE_PERIOD;
// minimum pulse width (-45 degrees)
const unsigned long ZERO_POSITION_COUNT = F_CPU / PRESCALER * ZERO_POSITION_WIDTH;
// minimum pulse width (+45 degrees)
const unsigned long FULL_POSITION_COUNT = F_CPU / PRESCALER * FULL_POSITION_WIDTH;

const byte NO_DATA_YET = 0xFF;

volatile unsigned char spiBuffer[6];  // '<' xH xL yH yL '>'
volatile byte buffPos = NO_DATA_YET;
volatile bool process_spiBuffer = false;

void setup()
  {
  Serial.begin (115200);   // debugging

  // Turn on SPI in slave mode
  SPCR |= bit(SPE);

  // Send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // Turn on interrupts
  SPI.attachInterrupt();

  TCCR1A = 0;          // disable all PWM on Timer1 whilst we set it up
  ICR1 = PULSE_WIDTH_COUNT - 1;   // frequency is every 20ms (zero-relative)

  // Configure timer 1 for Fast PWM mode using ICR1, with 8x prescaling
  TCCR1A = bit (WGM11);
  TCCR1B = bit (WGM13) | bit (WGM12) |  bit (CS11);  // fast PWM top at ICR1
  TCCR1A |= bit (COM1A1);  // Clear OC1A/OC1B on Compare Match,

  #ifdef __AVR_ATmega2560__

    TCCR3A = 0;          // disable all PWM on Timer3 whilst we set it up
    ICR3 = PULSE_WIDTH_COUNT - 1;   // frequency is every 20ms (zero-relative)

    // Configure timer 3 for Fast PWM mode using ICR3, with 8x prescaling
    TCCR3A = bit (WGM31);
    TCCR3B = bit (WGM33) | bit (WGM32) |  bit (CS31);  // fast PWM top at ICR3
    TCCR3A |= bit (COM3A1);  // Clear OC1A/OC1B on Compare Match,

    pinMode (11, OUTPUT);   // OC1A is D11 on Mega2560
    pinMode (5, OUTPUT);    // OC3A is D5  on Mega2560
  #else
    pinMode (9, OUTPUT);    // OC1A is D9  on Uno
  #endif
  }   // end of setup

int xValue,
    yValue;

void loop()
{

  if (process_spiBuffer)
    {
    if (spiBuffer [0] == '<' && spiBuffer [5] == '>')
      {
      xValue = makeWord (spiBuffer[1], spiBuffer[2]);
      yValue = makeWord (spiBuffer[3], spiBuffer[4]);
      }

    // ready for another interrupt
    buffPos = NO_DATA_YET;
    process_spiBuffer = false;

    }

  // adjust PWM amount
  OCR1A = ZERO_POSITION_COUNT + (xValue * (FULL_POSITION_COUNT - ZERO_POSITION_COUNT) / 1024) - 1;

  #ifdef __AVR_ATmega2560__
    OCR3A = ZERO_POSITION_COUNT + (yValue * (FULL_POSITION_COUNT - ZERO_POSITION_COUNT) / 1024) - 1;
  #endif

} // end of loop

ISR(SPI_STC_vect)
{
  byte c = SPDR;   // get byte from SPI hardware

  // exit if haven't processed last one
  if (process_spiBuffer)
    return;

  if (c == '<')
    buffPos = 0;
  else if (buffPos == NO_DATA_YET)
    return;  // ignore until we get a '<'

  if (buffPos < sizeof spiBuffer)
    {
    spiBuffer[buffPos++] = c;

    // End of message is ">"
    if (c == '>')
      process_spiBuffer = true;

   }  // end of room in buffer
} // end of ISR(SPI_STC_vect)

This incorporates my suggested use of the timer hardware to do the servo positioning, rather than the servo library. There are a couple of #ifdefs in there, so you can run it on a Uno as well (it just won't do the second servo).

The servos are already powered independently and sharing a common ground with the whole project. Since the servos have the same values with servo.read(), wouldn't that make it a software issue? A software issue that only occurs when the SPI interrupt is attached.

Like I said under the question, try triggering the "interrupt part" with a switch, and feed in dummy values (which are different). I doubt the interrupt as such is causing the issue, it will be the code that runs afterwards.

Plus, I stick to what I said about the servo library using interrupts itself. If you switch to hardware PWM then it can't be the interrupts. But some debugging displays should sort all that out.

Since the servos have the same values with servo.read(), wouldn't that make it a software issue? - I don't see servo.read() in your code. I still think you are confusing the interrupt itself to the code that is executed after the interrupt is detected. That is where I would be looking.


text:
Using only Rx pin to receive data from HC 05 and attiny85 (Arduino IDE)
I was building a Bluetooth car with attiny85 (Arduino IDE) and HC05 bluetooth module. I need 4 IO pins to control the car. Since attiny have only 5vIO's, I am left with only 1 pin to connect to HC05. I would only be receiving data from HC05. So, I want to use that leftover pin as RxD to receive data.

#include //the software serial library
#define RxD 4

SoftwareSerial blueToothSerial(RxD);

But when I do this It gives the following error

No matching function for call to 'SoftwareSerial::SoftwareSerial(int)'
Though it works fine, when I also define a TxD pin. But I want to use only one pin (RxD). Please help.

I suggest you get rid of SoftwareSerial and use instead this Simple
ATtiny USI UART. This is a driver
for a receive-only UART that uses the USI port of the ATtiny85. It is
superior to a software-only UART as it makes good use of the hardware,
leaving more time for the CPU to do more useful things (or sleep and
save battery). Also, unlike SoftwareSerial, it does not need to block
interrupts for long periods, which is a good thing.

The constructor for the SoftwareSerial object expects to be given both a TX and and RX pin (and, optionally, a boolean value representing whether or not it should use inverse logic.) From SoftwareSerial.h, see:
SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);

If you want to use the library in the way you've written, you'll need to either modify the existing constructor or write a new one into the library.
As a quick test, I've added the following lines to each of the listed source files:
SoftwareSerial.h
SoftwareSerial(uint8_t receivePin, bool inverse_logic = false);

SoftwareSerial.cpp
SoftwareSerial::SoftwareSerial(uint8_t receivePin, bool inverse_logic /* = false */) :
_rx_delay_centering(0),
_rx_delay_intrabit(0),
_rx_delay_stopbit(0),
_tx_delay(0),
_buffer_overflow(false),
_inverse_logic(inverse_logic)
{
  setRX(receivePin);
}

Now there's a constructor that allows for a single RX pin argument like you've outlined in your initial example. The problem is that this is likely to break anytime the Arduino codebase gets updated and your changes get blown away.
Best practice may dictate writing your own driver to use the serial functionality of your ATTiny without the possibility of accidentally using the TX functions, but if this is a one-off then maybe Bence Kaulics' suggestion of just feeding it a nonsense pin would be the least time-consuming.


text:
How do you send data via I2C without the wire library?
I have the following digital potentiometer: DS1803-100 which, according to the datasheet, can be controlled using a two-wire serial interface. I have managed to get it working using Wire, however I can't seem to get it working using only digitalWrite (link to code). Can somebody tell me why? For reference, 0x50 is the address + r/!w bit, 0xA9 is the command (write to pot 0 in my case) and the next 0xA9 is the value to write. I know there's something wrong with the code, however I cannot figure out what. Thank you in advance!
EDIT: Here is the code
int PIN_SCK = 12;
int PIN_SDA = 11;

const int delayvalue = 10;

void setup(){
    digitalWrite(PIN_SCK, 1); // I can first declare the state
    digitalWrite(PIN_SDA, 1);
    pinMode(PIN_SCK, OUTPUT); // then turn them on
    pinMode(PIN_SDA, OUTPUT);

    delay(1000);

    digitalWrite(PIN_SDA, 0); // start bit

    shift_out(PIN_SDA, PIN_SCK, 0x50);
    shift_out(PIN_SDA, PIN_SCK, 0xA9);
    shift_out(PIN_SDA, PIN_SCK, 0xA9);

    digitalWrite(PIN_SDA, 1); // stop bit

}

void loop(){

}
// uint8_t is the same as 8 bits aka one byte
void shift_out(uint8_t datapin, uint8_t clockpin, uint8_t val){
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        digitalWrite(datapin, !!(val & (1 << (7 - i))));
        delay(1);
        digitalWrite(clockpin, 0);
        delay(delayvalue);
        digitalWrite(clockpin, 1);
        delay(delayvalue);
    }

    digitalWrite(datapin, 0); // to enable stop bit
    delay(100); // wait fro aknowledgement

}

What code would that be? Feel free to post the code here.

All right, edited the code in.

Well, short answer: It was the acknowledge bit, I forgot to send a clock pulse in order to receive it (duh! my device generates the clock for the attached potentiometer, I was waiting for the device to "send" me a bit, I needed to "request" the bit on a rising edge of the clock).
Long answer: the code looks like this now:
int PIN_SCK = 12;
int PIN_SDA = 11;

const int delayvalue = 10;

void setup(){
    digitalWrite(PIN_SCK, 1); // I can first declare the state
    digitalWrite(PIN_SDA, 1);
    pinMode(PIN_SCK, OUTPUT); // then turn them on
    pinMode(PIN_SDA, OUTPUT);

    delay(1000);

    digitalWrite(PIN_SDA, 0); // start bit
    delay(10);
    digitalWrite(PIN_SCK, 0);
    delay(10);

    shift_out(PIN_SDA, PIN_SCK, 0x50);
    shift_out(PIN_SDA, PIN_SCK, 0xA9);
    shift_out(PIN_SDA, PIN_SCK, 0xA9);

    digitalWrite(PIN_SDA, 1); // stop bit

}

void loop(){

}
// uint8_t is the same as 8 bits aka one byte
void shift_out(uint8_t datapin, uint8_t clockpin, uint8_t val){
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        digitalWrite(datapin, !!(val & (1 << (7 - i))));
        delay(1);
        digitalWrite(clockpin, 1);
        delay(delayvalue);
        digitalWrite(clockpin, 0);
        delay(delayvalue);
    }

    digitalWrite(datapin, 0); // to enable stop bit
    delay(10);

    // Here I handle the AKNOWLEDGE signal which happens after
    // each byte sent. Be it address, command or value
    digitalWrite(clockpin, 1);
    delay(10);
    digitalWrite(clockpin, 0);
    delay(10);

}

So basically I followed and reproduced the signals in this timing diagram faithfully with one small exception: I did not generate a rising edge when I expected the acknowledge bit (basically the diagram but with SCK being 0 right below the acknowledge bits).
Hope this helps somebody!

I2C is a lot more complex than just shifting bytes out.
See: I2C - Two-Wire Peripheral Interface - for Arduino
Your code does not seem to take any of that into account.
Why do you not want to use the Wire library? The hardware on the chip (what chip do you have?) supports it. Why ignore that and try to do it yourself?

I have no problem using the wire library, however I was wondering why that code didn't work in the first place, since in my mind it should have worked. And yeah, I already ended up using Wire on my Arduino Pro Mini. Thanks for the info! :)

I am really curious on what I did wrong in my code. Did I not take into account the acknowledge bit, I just waited 100 ms for the slave to send this bit and than carried on, or what did I do?

Well I managed to make it work, I'll post the answer a bit later.


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:
Is it possible for Arduino to send a message to the internet without using a GSM shield?
I need an Arduino to send a message, to be displayed on the web, after pressing a push button, which is connected to an Arduino [or shield], without using a GSM shield.
I need to send a message just by using HTML/PHP code included in the Arduino IDE. This displayed message should contain two buttons. One button is used to turn a LED ON/OFF and the other to open a streaming video.
Can anyone help me with the Arduino code and explain how I should do that? Is there any third party device, apart from a GSM shield, that can help me to send that message?

Start with either the Ethernet shield or the WiFi shield.

I'm trying to understand what you really want, do you want your arduino to provide some sort of webpage containing two buttons. one to turn on a LED and the other one is used to open a streaming video? Is that what you want? Also, I feel myself confused about the buttons, which ones are the physical buttons and which ones are meant to be on the webpage?

yes, thats what i want exactly. i want arduino to provide a message after  pressing a button and the message must display on web shows 2buttons. one phyiscally connected to arduino and used to turn on/off led and the other button on the webpage to open a stream vedio/audio. Now do you understand what i want. and if yes, can you help me with arduino code?

note: i deal with Ethernet shield. and i need html and php code for control LED and open a stream video. additionally, without using a GSM sheild to let arduino send the message.

Yes I can help you, but have you tried something? What you need is to set up a Web Server on your arduino. You may look at this tutorial: https://www.arduino.cc/en/Tutorial/WebServer

Also, I don't understand why you involve the GSM shield? It has nothing to do with what you want to achieve.

You only need an Ethernet shield + buttons + LEDs ..

previously, i have applied this code from this site. but this need to enter my computer ip address into address bar then the webpage is display. now the situation is different. because  what i want is when i press on a push button, then the web page should display. can you help me with code, please?

and i need also php code that make me open a stream video/audio  live, can you help me, please?

Well, I guess you need some sort of program on your computer listening on Serial port, when you press a button, send a command via Serial port to that program and it will open that webpage. if you are interested I will show you an example ;)

IP with homing pigeons? https://en.wikipedia.org/wiki/IP_over_Avian_Carriers

Use this example to open a webpage using a push button, you need Python installed on your Windows.
Step 01:
Upload this sketch to your arduino:
const int buttonPin = 2; // the number of the pushbutton pin
int buttonState = 0;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
  Serial.println("OpenWebPage");
  }
}

The Circuit:

pushbutton attached to pin 2 from +5V
10K resistor attached to pin 2 from ground

Step 02:
Open a text editor and paste this code to a new file:
import serial
from subprocess import call

ser = serial.Serial(
    port='COM5', # Change this to your COM port number
    baudrate=9600,
    parity=serial.PARITY_ODD,
    stopbits=serial.STOPBITS_TWO,
    bytesize=serial.SEVENBITS
)

if (ser.isOpen()):
    print "Serial Port is Open..."
    print "Waiting for a command ..."
    while 1:
        cmd = ser.readline()
        if cmd.strip() == "OpenWebPage":
            print "Received command from Arduino..."
            print "Opening webpage..."
            call(["explorer", "http://www.google.com"]) #change it the address you want

Save the file to your desktop, name it : SerialListener.py
Step 03

Now open a Command Prompt window.
Navigate to your desktop folder and execute this command: python SerialListener.py.
You should see Serial Port is Open... Waiting for a command ...
Press the push button, and a webpage should open in your default browser.


text:
Need help converting a processing sketch for a robot arm with servo shield
I'm currently building a robotic arm. I'm using an Adafruit servo shield, 7 servos, Arduino uno, and a 5V 10A power supply.

I found a program that controls the arm with mouse movement using a processing sketch, Fixbot.
However I'm using the Adafruit servo shield, and I've got no clue how to convert the program. I've found the center points for the servos, so I've managed to make the robot stand upright using my own code.
If someone could give me some pointers as to how to convert from the on-board PWM outputs to the servo shield outputs for the linked program, and how to set servo max/min, I would highly appreciate it.

This site uses a question/answer format. A "question" along the lines of "please give me some pointers as to how to do X" is rather broad.

What aspect needs converting? More importantly, what does it need converting to? The Arduiino code for the Fixbot is wonderfully straightforward; it reads a run of integers (by parsing a string, blah blah) and then writes those integers to the servos. Where is the problem occurring?

I use a generic servo shield, and the servo PWM outputs (3 pin inline connector) on the shield are labeled accordingly (0 - 15). Your Adafruit servo shield should be the same, see below.

The link that you provide also has the Arduino version, see below. You should use that, instead of the Processing version.
The Arduino library Servo.h, handles all of the "Servo PWM to Arduino pin conversions" that you ask for. So, looking at the Fixbot code, it would seem that all you would need to do is change the five pins (servo PWM outputs) to which the servos are attached in setup(), according to which servo PWM outputs you attach each servo to.
#include <Servo.h>

String command;

Servo seg0;
Servo seg1;
Servo seg2;
Servo seg3;
Servo seg4;

void setup() {
  Serial.begin(115200);
  seg0.attach(8);            /* <--- Change Me !!! */
  seg1.attach(9);            /* <--- Change Me !!! */
  seg2.attach(10);           /* <--- Change Me !!! */
  seg3.attach(11);           /* <--- Change Me !!! */
  seg4.attach(12);           /* <--- Change Me !!! */
}

void loop() {
  if(Serial.available() > 0) {
    char inChar = Serial.read();
    command += inChar;
    if(inChar == '\n') {
      // clear command
      performCmd(command);
      command = "";
    }
    Serial.flush();
  }
}

void performCmd(String cmd) {
  int comma1 = cmd.indexOf(',');
  int comma2 = cmd.indexOf(',', comma1+1);
  int comma3 = cmd.indexOf(',', comma2+1);
  int comma4 = cmd.indexOf(',', comma3+1);

  int cmd0 = stringToInt(cmd.substring(0, comma1));
  int cmd1 = stringToInt(cmd.substring(comma1+1, comma2));
  int cmd2 = stringToInt(cmd.substring(comma2+1, comma3));
  int cmd3 = stringToInt(cmd.substring(comma3+1, comma4));
  int cmd4 = stringToInt(cmd.substring(comma4+1, cmd.length()));

  seg0.write(cmd0);
  seg1.write(cmd1);
  seg2.write(cmd2);
  seg3.write(cmd3);
  seg4.write(cmd4);

}

int stringToInt(String str) {
  String tmp = String(str);
  return str.toInt();
}

Regarding your question about the maximum and minimums, again, these will be handled by the Servo.h library.

TL;DR
Change the five servo attach lines in the setup() routine, to reflect which servo ports your servos are connected to.

Power Requirements
As an aside, remember that you will need to supply external power (+5V) to the Adafruit Servo board, via the blue screw terminal block, in order to have sufficient power (current) to actuate the servos. In the photo above the screw terminal block is not shown, but would be mounted half way up on the left hand side of the PCB (where it says 5-6V Servo). It can be seen in this photo, at the top:

If you do not supply external power, then the Arduino board, by itself will not be able to supply enough power. Even though the code may be running, the lack of power may make it appear that there is no output, as the servos remain immobile, due to the lack of current.


text:
Using Arduino with Assembly on MacOS
I'm trying to use an Arduino UNO board with Assembly on MacOS, but I couldn't find any documentation about it.
How can I compile and upload Assembly files to the Arduino with MacOS?

You can add source code to the sketch in the Arduino IDE. When adding a new source code file make sure the extension is uppercase .S
Files with .S extension will be compiled as Assembly.
There is an Arduino IDE for the mac but if you want to use an external editor you have many options.
The simplest is to switch on File>Preferences>External Editor in the Arduino IDE. This makes the IDE work in "read-only/auto-reload" mode allowing edit in a different code editor but compile and upload (without reopening the code) in the Arduino IDE.
There are also the File>Preferences Verbose Compile and Verbose Upload options in the Arduino IDE. These options will show you the commands used to compile, link and upload. You will see that the IDE runs other programs, outside of the IDE, such as avrdude and g++. Therefore a small script file can be created to call the same commands from a different IDE if the external editor doesn't have a facility to run external commands.
The verbose output will show where the tools and sources for build and upload are located. Normally for Uno (avr) they are below [IDE Folder]\hardware\arduino.

Yes, I know how to use Assembly, because I'm using it in a module on my course. :) It's based on Linux and I've been using the labs to work on it, but it'd be easier on my Macbook. Is there a way to compile/upload it via emacs?

Okay I have edited my answer, I hope it helps. Maybe a good idea to edit your question with the additional clarity.


text:
Arduino DUE deadlock problem, watchdog not working
I am using Arduino DUE in my project. The project is massive (about 7000 lines of code in total, with massive schematic), so I decided not to post the whole code and schematic, except explain the hardware and configuration I am working with:

Arduino DUE;
12V switching power supply;
LTC1660 DAC (used withstandard SPI library);
Nextion HMI (Used with standard library #include Nextion.h        //INCLUDE NEXTION LIBRARY);
DS3231 RTC module on I2C bus (Library used: Wire #include <DS3231.h>)
24LC256 EEPROM on same I2C bus (Library used: Ext EEPROM #include <extEEPROM.h>)

The base line, is that on power-on the controller just freezes besides, it can't be the problem with power as I get this problem using both 12 V from switching PSU and 5 V USB cable. I can not really analyse the problem, as the deadlock occurs even before the program start to execute content of void setup(). My best guess is that the deadlock occurs due to infinite loops in the Arduino's twi.cpp where infinite loop can occur if the controller receives no acknowledge
bit. But then again I can not be sure here. However when I push restart button on the Arduino or enable Serial monitor in Arduino IDE when the circuit is powered on , it starts to work, and it works just as expected.
After reading the datasheet for the DUE's μC, I've found that it have the watchdog option embedded:

After a Processor Reset, the value of WDV is 0xFFF, corresponding to
  the maximum value of the counter with the external reset generation
  enabled (field WDRSTEN at 1 after a Backup Reset). This means that a
  default Watchdog is running at reset, i.e., at power-up. The user must
  either disable it (by setting the WDDIS bit in WDT_MR) if he does
  not expect to use it or must reprogram it to meet the maximum Watchdog
  period the application requires. The Watchdog Mode Register (WDT_MR)
  can be written only once. Only a processor reset resets it. Writing
  the WDT_MR register reloads the timer with the newly programmed mode
  parameters.

I've started to explore it, and as I got it, the watchdog is ON by default, and its timer period is 16 seconds by default, so as it is not normally used in DUE, I assumed, that somewhere it is just disabled, and in main.cpp I found the following:
int main( void )
{
   // Initialize watchdog
   watchdogSetup();
   init();
   initVariant();

where watchdogSetup() led to:
void watchdogDisable(void)
{
   WDT_Disable (WDT);
}
void watchdogReset(void)
{
   WDT_Restart (WDT);
}
extern "C"
void _watchdogDefaultSetup (void)
{
   WDT_Disable (WDT);
}
void watchdogSetup (void) __attribute__ ((weak, alias("_watchdogDefaultSetup")));

As I got it, due to this, the watchdog was disabled for DUE by default, and commenting out watchdogSetup(); in int main() would allow the watchdog to work (as watchdog is on at power on by default, according to datasheet).
I've also added the WDT_Restart (WDT); to void loop() of the program in order to kick watchdog every program cycle.
Well, for some reason, that did not help me, and I'm still receiving the deadlock when I power on the controller, even through the watchdog is technically not disabled, after 16 seconds it still do not restart the system. And, pressing the reset button or the Serial monitor in Arduino IDE makes the system run as expected. Am I missing something out? Your help and suggestions are appreciated, shall any additional info be needed, just let me know, I need to get this project running so badly.
By the way, my void setup() function is quite long, and if I set the watchdog to 1 second, using
void watchdogEnable (uint32_t timeout) instead of commenting out watchdogSetup() in main.cpp, and use reset button after power on, I can see the watchdog working as it can't get to void loop() in time in order to reset watchdog (as void setup() takes about 3 seconds due to delays).

Do you know what the purpose of the weak attribute is?

You don't need to comment out the Arduino core source code. Just add the watchdogSetup function to your own code. Try creating a simple sketch first to make sure you get the WDT to work properly before adding it to your existing code

@Majenko, no I dont know what the meaning of the attribute is, can you explain ?

@Gerben, you see, the problem is that the deadlock occure even before the content if void setup() is executed.

@SlavaKrasnikov - I believe you have misidentified the cause. The watchdog (in the state set by the default s/w init code) is disabled (as highlighted by Majenko). Don't complicate your problem by enabling the watchdog! Your original code, with default watchdog configuration, executes the same instructions whether it is starting from a power-on reset, or pressing the rest button, yet the latter "works", which confirms default watchdog config works OK. Previously I saw similar behaviour due to various h/w design issues, but testing your h/w would need more help than fits into a comment. :-(

@SamGibson , I do understand that the problem with the controller freezing might be caused by the external hardware that is connected to my controller, but I was just thinking that the watchdog is kinda "magic pill" against controller deadlock related problems. The fact that the controller freeze on power-on is not as upsetting to me as the fact that the watchdog can not get the controller out of the deadlock by resetting it.

@Slava - "controller freeze on power-on is not as upsetting to me [...]" - Experience tells me this absolutely would be upsetting to me; finding & fixing root cause is vital to preventing recurrence. "watchdog can not get the controller out of the deadlock by resetting it" - I don't understand all your earlier story about this, but I'm not surprised. IMHO you have overestimated what typical internal MCU watchdog is designed to protect against, and what h/w failures it can cope with. You might be able to workaround your (unknown) problem using an external delayed POR circuit. Good luck!

Found people suffering with the same problem on Arduino's official forum. It turned out that the problem arises from the schematic of Arduino Due, that fails to hold 'reset' pin high for long enough period of time on power-on. There are multiple solutions involving adding some capacitance between reset pin and ground pin, but this might damage circuit in long run (at power-off), so I managed to find other way around it: there is an ATmega16U2 used as USE-to-TLL serial chip that have access to reset pin of AT91SAM3X8E.

Found people suffering with the same problem on Arduino's official forum. It turned out that the problem arises from the schematic of Arduino Due, that fails to hold 'reset' pin high for long enough period of time on power-on.
There are multiple solutions involving adding some capacitance between reset pin and ground pin, but this might damage circuit in long run (at power-off), so I managed to find other way around it: there is an ATmega16U2 used as USE-to-TLL serial chip that have access to reset pin of AT91SAM3X8E.
The ATmega16u2 can be reprogrammed so that on power-on it provide short "HIGH" period to AT91SAM3X8E reset pin. The program for ATmega16U2 can be found here:
https://forum.arduino.cc/index.php?action=dlattach;topic=167492.0;attach=52901
The updating precision is given here:
https://www.arduino.cc/en/Hacking/Upgrading16U2Due
I've performed the given precision using Arduino UNO as programmer and can confirm that it worked properly.The problem's gone now.


text:
Problem controlling a Stepper motor with AccelStepper in arduino uno
I have an Arduino connected to a stepper motor with an Easy Driver. I want for the stepper motor turn to a coordinate point. I wrote a simple program in Visual Studio that sends a coordinate point to the Arduino. I tried to write this below to plot the coordinate point, but when I send a number to the Arduino, the stepper motor will only turn one step. I don't know how fix this.
Can anyone fix this problem please?
#include <AccelStepper.h>

AccelStepper stepper(1, 9, 8);

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(10000);
  stepper.setAcceleration(5000);
}

void loop()
{
  char c;

  if(Serial.available())
  {
    int steps = Serial.read();
    stepper.moveTo(steps);
  }
  stepper.run();
}


text:
How to fix this code so instead of having to hold button to change led, you can press?
const int buttonPin = 1; // the pin number of the pushbutton input pin
const int ledPins[] = {2, 3, 4, 5, 10, 11, 12, 13};    // variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int buttonPressCount = 0;
int numberOfLED = 8;

void setup() {    // initialize the LED pin as an output:
  for (int i = 0; i < numberOfLED; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
  pinMode(buttonPin, INPUT);
}

void loop() {    // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);    // check if the pushbutton is pressed.    // if it is, the buttonState is HIGH:
  if (buttonState  == HIGH) {
    for (int i = 0; i < numberOfLED; i++) {
      if (buttonPressCount % numberOfLED == i)
        digitalWrite(ledPins[i], HIGH);  // turn LED on
      else
        digitalWrite(ledPins[i], LOW);   // turn LED off
    }
  }
  buttonPressCount++;
  delay(300);
}

instead of changing every time the buttonState == HIGH, change it when the button state was LOW the previous time but HIGH now:
buttonState = digitalRead(buttonPin);
if (oldButtonState != buttonState && buttonState == HIGH) {
    //...
}
oldButtonState = buttonState;

However keep in mind contact bounce. Which can result in multiple transitions being detected. Most solutions for that set a minimal delay between handling transitions, dropping all others detected.