text:
arduino SD card saving to file
Can anyone assist me with read/write to a SD shield. I am using a arduino along with a SD shield (POD  uSD) I am using a ultrasonic sensor to measure a distance, it has a safety factor in it. It also measures the time a measurement was taken, I now need to save the data from the serial monitor to a file and send that file to a SD card. I cannot seem to solve the saving a file part along with the SD shield
I have wrote my code but can seem to implement the shield along with my code, I want to store my data onto a file on the SD card. I've reviewed the example provided in the library's but it won't work for me
My code is;
#define redled 10
#define greenled 11
#define echoPin 12
#define trigPin 13

unsigned long interval=60000; //interval = 60 seconds
unsigned long previoustime=0;
int minutes = 0; //global variables

void setup() {
  Serial.begin (9600); //Set Baud rate to 9600 to match serial monitor
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(greenled, OUTPUT);
  pinMode(redled, OUTPUT);
}

void loop() {
 //-----------------------------------------------------------
  unsigned long currenttime = millis(); //counts time in milliseconds and puts it into current time
  if ((currenttime-previoustime) >= interval) { //When time is greater 60 seconds
    previoustime = currenttime; //Make the previous time equalled to the minute to take away in the next if statement        **Time since start section**
    minutes = minutes + 1; //Add 1 minute
  }
  unsigned long time = (currenttime-previoustime) / 1000; //converts the milliseconds to seconds
  //-----------------------------------------------------------
  long distance = ultra_sensor(); //call function that now returns the distance
  //-----------------------------------------------------------
  if (distance < 4) {            // If distance is less than 4cm
    digitalWrite(redled,HIGH);   // Turn on Red LED
    digitalWrite(greenled,LOW);  // Turn off Green LED
  }
  else {                          //If distance is greater than 4cm
    digitalWrite(redled,LOW);     // Turn off Red LED
    digitalWrite(greenled,HIGH);  // Turn on Green LED
  }
  //-----------------------------------------------------------
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.print("cm");
    Serial.print(" after ");
    Serial.print(minutes);              //Printing distance and time to serial monitor
    Serial.print(" minutes ");
    Serial.print("and ");
    Serial.print(time);
    Serial.println(" seconds");
  }
  //-----------------------------------------------------------
  delay(2000); //Get reading every 2 seconds
}

long ultra_sensor() { //Ultrasonic sensor reading is now a function. More efficient
  digitalWrite(trigPin, LOW);  //Set Trigger to idle
  delayMicroseconds(2); //Wait 2 microseconds
  digitalWrite(trigPin, HIGH); //Set Trigger to high which sends out a wave
  delayMicroseconds(10); //Send the wave for 10 microseconds
  digitalWrite(trigPin, LOW); //Turn the trigger to idle
  long duration = pulseIn(echoPin, HIGH); //make duration the wave that echo recieves back
  long dis = (duration/2) / 29.1; //divide by 2 for going there and back.                         ***Speed of sound***
  return dis; //Send the distance to function call
}

Looks like your sketch (pin usage) is in conflict with the SD shield (SPI pins). Try using other pins.


text:
Arduino String problem
Hello I am using the u8glib library to draw text on the string but it keeps giving me an error with the string
 String name1 = "";
 ...
 void draw(){
  u8g.setFont(u8g_font_micro);
  u8g.drawStr(22, 37, name1);
 }

why dosnt this work?
Here is the error:

C:\Program Files (x86)\Arduino\libraries\U8glib/U8glib.h:200:16: note:
  no known conversion for argument 3 from 'int' to 'const
  __FlashStringHelper*' no matching function for call to 'U8GLIB_PCD8544::drawStr(int, int, String&)'

String is evil and should be avoided at all costs (http://hacking.majenko.co.uk/the-evils-of-arduino-strings)
The author of u8glib knows that and has refused (quite rightly) to implement them.
You should not use String either.  If you really must for some obscure reason then you will have to pass the internal "C string" reference to the drawStr function instead of the whole String object:
u8g.drawStr(22, 37, name1.c_str());

The only reason people use String is because they are too lazy to learn the proper way of handling textual data in C.

The link is broken: "Hmm. We’re having trouble finding that site. We can’t connect to the server at hacking.majenko.co.uk."

Re "String is evil": I have come to the same conclusion, after some pain. It was there all along, but it didn't really show up until now. It was used in formatting of error reporting going to the serial port and as the frequency of (spurious, harmless) errors increased due to some changes to the system, occasional hard freezes was the result. Strangely, it was dependent on the Serial Monitor (or another terminal, like Screen) being open/connected... It being open made the error nearly 100% reproducible.

cont' - That was with an Arduino Leonardo.

If they shouldn't use String, what should they use instead? Perhaps add something to this effect to the answer? And/or a reference to this answer.

Like the documentation says, that method doesn't take a String object. Call the c_str() method of the String object and pass that instead.

what do you mean, what should I put in my arduino code? I looked at the documentation and i cant see a c_str() method

name1.c_str()

source: Stack Exchange

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

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

sort: votes


text:
C Serial Communication Code is unreliable
This going to be a difficult to debug problem but I hope some ppl here have C knowledge and idea what's going on. Given an arduino nano which is controlled by a C program from WRT54G.
Here is the relevant part of the arduino code:
void setup() {
  Serial.begin(9600);
}

 int integerValue=0;

                              // Max value is 65535
char incomingByte;

void loop() {
  if (Serial.available() > 0) {   // something came across serial
    integerValue = 0;         // throw away previous integerValue
    while(1) {            // force into a loop until 'n' is received
      incomingByte = Serial.read();
      if (incomingByte == '\n') break;   // exit the while(1), we're done receiving
      if (incomingByte == -1) continue;  // if no characters are in the buffer read() returns -1
      integerValue *= 10;  // shift left 1 decimal place
      // convert ASCII to integer, add, and shift left 1 decimal place
      integerValue = ((incomingByte - 48) + integerValue);

    }
   Serial.print("Command: ");
   Serial.println(integerValue);

  }
}

Pretty straight forward (it converts serial received ascii chars to numeric format), arduino receives a simple integer and it runs a function. For example 1-> turn on relay1. This work's reliably for sure because I can just do:
echo "1" > /dev/tts/1

from the terminal.
Now here is the relevant part of the C code:
    int serialport_read_until(int fd, char* buf, char until, int buf_max, int timeout)
    {
        char b[1];  // read expects an array, so we give it a 1-byte array
        int i=0;
        do {
            int n = read(fd, b, 1);  // read a char at a time
            if( n==-1) return -1;    // couldn't read
            if( n==0 ) {
                usleep( 1 * 1000 );  // wait 1 msec try again
                timeout--;
                continue;
            }
    #ifdef SERIALPORTDEBUG
            printf("serialport_read_until: i=%d, n=%d b='%c'\n",i,n,b[0]); // debug
    #endif
            buf[i] = b[0];
            i++;
        } while( b[0] != until && i < buf_max && timeout>0 );

        buf[i] = 0;  // null terminate the string
        return 0;
    }

    /* Only use integer commands */
    int serialport_write(int fd, int comm_no)
    {
        char command[6];

        sprintf(command,"%d\n",comm_no);
        printf("Sending Command:%s",command);

        int len = strlen(command);
        int n = write(fd, command, len);
        if( n!=len )
            return -1;
        return 0;
    }

void *ardu_handler(void *fdfd)
{
  int fd = *(int*)fdfd;
  char buf[256];
  char getback[10];

  while (1)
   {
     memset(buf, 0, sizeof(buf));
     serialport_read_until(fd, buf, '\n', 256, 5);
     fprintf(stderr, "Received: %s\n", buf);
   }
}

Then a C thread will be started with the ardu_handler which in this case doesn't do anything else just print's back the response from the ardu.
What's happening is when I send a command I start getting back infinite amount of commands (up until I close the C app and start it again) and to make it worse it is even inconsistent.
For example:
Command: 62143
Command: 7891
Command: 3216
Command: 11287
...
runs forever.

What I asking myself is whether these responses coming out from the arduino or they are just coming out from the bogous C program...
It's not possible to connect to see what's coming out on the serial port unfortunately until this program holds the port open.
Although I run the C code on mips this was doing the same thing back on x86 PC with an arduino uno (sometimes it is stable but then it falls into this unstable state and floods the serial port). It was unreliable and I would like to make it reliable.

Change the type of incomingByte to int. See https://www.arduino.cc/en/Serial/read

Reading on, the 2nd code block contains a buffer overflow where char b[1]; is defined, but you're trying to null-terminate a string. Where is buf_max defined?

I assume the results you posted above are the stderr output, though I can't see the Received:  part of it.

// Max value is 65535 - that isn't true.

I recommend you change the type of incomingByte to int, like was advised in the comments. Also, your null-termination is occurring past the end of buf; change the condition in the while statement to i < buf_max - 1, so that one byte is left for the null. Also use parentheses to separate those conditions, in the unlikely event there's some issue of precedence.

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


text:
Can we use serial communication in arduino only for RX pin
Can we use serial communication in arduino only for RX pin, so that I am free to use pin 1(TX) as digital I/O:
Serial.write('a');
pinMode(1,OUTPUT);
digitalWrite(1,LOW);

HardwareSerial takes over the Tx and Rx pins. However you can use SoftwareSerial.
Arduino forum user whiteglint143 made an adaptation of SoftwareSerial that does read-only.
http://gammon.com.au/Arduino/ReceiveOnlySoftwareSerial.zip
See Receive Only Software Serial  - Arduino Forum

You can regain control over the TX or RX pins by unsetting the TXENn or RXENn bit in the UCSRnB register.

Like this?
const byte LED = 1;

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  UCSR0B &= ~bit (TXEN0);  // disable transmit
  Serial.println ("Testing");
  pinMode (LED, OUTPUT);
  }  // end of setup

void loop ()
  {
  digitalWrite (LED, HIGH);
  delay (500);
  digitalWrite (LED, LOW);
  delay (500);
  }  // end of loop

Gerben's suggestion works, in a sense. The pin flashes, but rather disconcertingly, the Tx LED on the board also flashes, out of sync with pin 1. Clearly the signal is making its way to the ATmega16U2 chip, which then flashes the indicator LED. This may not be desirable if you have something connected to the serial port, as it may be interpreted as low-speed serial communications.

You can regain control over the TX or RX pins by unsetting the TXENn or RXENn bit in the UCSRnB register.

Nice, simple solution! Good idea.

See amended post, using that pin as a digital pin may have side-effects.

Great finding. Though calling Serial.println, after disabling TX is kind of silly.

I hoped you wouldn't notice that. :P

authors: Сергій Іванов


text:
Drive 12V Piezo Buzzer (Arduino)
I want to drive this 12V piezo buzzer:
http://www.conrad.com/ce/en/product/130256/Kemo-L001-High-Freqeuncy-Piezo-Speaker-Component-12-24-V
This is the circuit I am using.

The Arduino is powered by a 12V DC adapter trough the DC IN jack.
I have tested the following code:
void setup() {
}

void loop() {
  int pinOut = 9;
  int freq = 10;
  int duration = 100;
  while(1)
  {
    for(int i=0; i<1000 ; i++)
    {
      tone(pinOut, freq*i, duration);
      delay(duration * 1);
      noTone(pinOut);
    }
  }
}

When run I can hear the tones changing but is really really low. I have measured the voltage between buzzer pins and it is 12V (as expected) so the MOSFET seems to be properly working.
This piezo buzzer should be louder (I have tested it with this 12V tone generator http://www.kemo-electronic.de/en/Car/Modules/M048N-Ultrasonic-Generator.php )
I am making any mistake?
Thanks in advance!

Do you have a capacitance meter?

The piezo element acts like a capacitor, not like a more-or-less resistive element as in a conventional speaker. You need to discharge the capacitor during the 'off' time or you just get a click and little sound after that. That's why your resistor helps. Push-pull would be much better, and an H-bridge would give you much more output (maybe too much for the speaker).
Also the IRZ44 is not specified to be driven from 5V (it's specified at 10V Vgs) so you may not get much current. Further, if you're trying to get 10's of kHz, you won't be able to drive the MOSFET gate that fast with a 1K resistor, in fact the Arduino may not be able to source enough current and you may have to use a gate driver.
If you can measure the capacitance and provide the frequency of interest, more specific recommendations would be possible. At 2kHz about 3K would be okay with a 10nF element, but that resistance would decrease with increasing resistance and with increasing capacitance, and at some point the power dissipation in the resistor will become excessive.
Edit: You can do something like the below with a 10nF/20kHz requirement:

simulate this circuit – Schematic created using CircuitLab
You could even duplicate the above circuit and add an inverter in series with one of the halves and get 24Vpp across the piezo, but you might want to use somewhat beefier transistors (Zetex perhaps).

See above edit. You can base a resistor value on the RC product being much less than half a cycle.

I have tested your circuit and the sound level is almost the same as mine (with the resistor in parallel with the piezo). There is any disadvantage of using my solution compared to yours?

Wasted power in the resistor is the disadvantage. Advantage is slightly cheaper, simpler. Your choice.

Based on your circuit, what do I have to change to drive the piezo at 40 kHz. Can you explain me how to calculate it? Thanks!


text:
Send data from computer to phone through bluetooth - Bluetooth SeeedStudio Shield V2.1
So I bought a Bluetooth Shield from SeeedStudio lately (V2 model) and goofed around with it a little bit. I'm using my HTC One M8 to communicate with it just to send some dummy words. Whenever I send something from my phone to the Android, it works great and I'm pleased to see it's fast too.
The code is fairly simple. I just send data from my phone, gets received to my arduino, prints it on the Arduino IDE terminal. Same thing for communication in the other way. Write something in the terminal, send it to the arduino and then, the phone. The last on doesn't work and I've tried a couple of things in the past 36 hours. Now, I'm just banging my head against the wall (literally). Here's my code (I'm sure you've seen it a couple of times before):
#include <SoftwareSerial.h>   //Software Serial Port
#define RxD 6
#define TxD 7

#define DEBUG_ENABLED  1

SoftwareSerial blueToothSerial(RxD,TxD);

void setup()
{
  Serial.begin(9600);
  pinMode(RxD, INPUT);
  pinMode(TxD, OUTPUT);
  setupBlueToothConnection();

}

void loop()
{
  char recvChar;
  while(1){
    if(blueToothSerial.available()){//check if there's any data sent from the remote bluetooth shield
      recvChar = blueToothSerial.read();
      Serial.print(recvChar);
    }
    if(Serial.available()){//check if there's any data sent from the local serial terminal, you can add the other applications here
      recvChar  = Serial.read();
      blueToothSerial.print(recvChar);
    }
  }
}

void setupBlueToothConnection()
{
  blueToothSerial.begin(9600); //Set BluetoothBee BaudRate to default baud rate 38400
  blueToothSerial.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
  blueToothSerial.print("\r\n+STNA=SeeedBTSlave\r\n"); //set the bluetooth name as "SeeedBTSlave"
  blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
  blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here
  delay(2000); // This delay is required.
  blueToothSerial.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable
  Serial.println("The slave bluetooth is inquirable!");
  delay(2000); // This delay is required.
  blueToothSerial.flush();
}

On my phone, I use a simple Bluetooth SSP to pair and communicate. Btw, something odd: I can't change the name of the bluetooth device. When I try to connect it, it shows the same name in the SSP.
Note: When I upload my code, I make sure I reset the arduino everytime. Oh and I changed the jumpers on my board to make sure it was set on the right one.
Note 2: I tried to see if the pins on the Shield (for RdX and TdX) were not starting with 0 by moving the jumpers.
Still, it's pretty odd.
Thanks in advance for any help and don't hesitate to ask me question! It's my first time here!


text:
When should I use a transistor, mosfet, and when should I use a relay?
I am used to relays some, and they are useful, especially for large loads like a incandescent light bulb or other 120V AC device. However, it seems like overkill to use a relay for a bunch of LEDs linked together (parallel) that use 60 mA (too much for the Arduino). Also, it wouldn't work if you wanted to turn it on/off frequently or do PWM. I've heard some about transistors and MOSFETS and know a little about them. When should I use each one and how do I know what type to get? Also, it seems like relays can be more expensive than transistors/MOSFETS.
Edit: How can I use these with my Arduino?

This question appears to be off-topic because it is about electrical engineering in general, not arduino specific. It belongs here https://electronics.stackexchange.com/

@jamolnng I disagree. If a new user posts something like this, they generally don't know how to use any of these. EE generally requires a fair amount of knowledge about the subject before posting. This does bring up an issue though of "should we migrate and close it just because there is overlap?"

True. We really need a defined set rules on what is acceptable, which is what this beta should help us decide. Also you are right about EE because a post like this would most likely get buried there. I keep my opinion that it should be migrated and closed because it doesn't really deal with arduino specifically, but you have a valid argument for keeping it open.

@jamolnng I respect your argument too and I see both sides: I just posted this question to bring up this argument because it hasn't really been answered in meta and I thought it would be a good example to actually post a question so we can see how it plays out.

Related meta discussion.

One could also add optocouplers to this list.

Simplest design requirement I can think of at the moment is: If you want to control mains power, you never use a transistor-only based solution.

@AsheeshR I agree, I would've unaccepted it earlier if it hadn't been so heavily voted to put on hold. I cast the final vote. This was more of a "test" to see if we would get good enough answers but the two there clearly show that this would be fit for EE.

Transistors (such as Bipolar Junction Transistors (BJT)) are solid state switchers, that is, they don't have any moving parts. Metal-Oxide-Semiconductor Field-Effect Transistors (MOSFET) are also transistors, but are voltage controlled, whereas classical BJTs are current-controlled. Relays are more expensive, but they have moving parts.
BJTs and MOSFETs produce a lot of heat (with high currents). They both have three pins (usually) called the base, collector and emitter (in the case of BJT) or gate, source, drain (in the case of MOSFET). More info here
Relays use a magnet to control the position of a metal switch. They generally take more power than an Arduino pin can deliver, and therefore they are often controlled by a transistor. Relays can usually switch more current than either a transistor or a MOSFET.
There are also Solid State Relays (SSR), which have a triac (a device similar to a transistor) in them. These can't switch as much as a normal relay, but they generally have better ratings than MOSFETs and BJT. example

One comment: MOSFETs have very low internal resistance, and so when fully switched on do not generate a lot of heat. They can handle quite a bit of current without needing a heat-sink.

Big differences between relays and transistors are:

relays are all-or-nothing (like switches) whereas transistors can transmit more or less current through the collector based on the current present on their base.
relays provide isolation between the command circuit (the one with the electromagnet) and the controlled circuit (the one on the switch side of the relay)

If you want to play with arduino, you definitely need to know about transistors; using relays is more akin to special applications.


text:
HC-06 data receiving
I've written a script in Python which sends data through the PC's Bluetooth to HC-06 on Arduino.
state is an integer from 0 to 1000 (it is controlled through the potentiometer).
...
gaugeSocket.send(str(state))
...

I can't get the right character-to-integer conversion on Arduino (from HC-06 serial).
Arduino code:
SoftwareSerial mySerial(10, 11); // RX, TX
char buf[2];
int i=0;
int data;
int ledPin = 9;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(57600);
  mySerial.begin(9600);
}

void loop() {
  if (mySerial.available()) {
    for(;i<2;){
      buf = mySerial.read();
      i++;
    }
    i = 0;
    Serial.print(buf);
    data = atoi(buf);
  }
    analogWrite(ledPin, data/10); //To see how code behaves on LED
}

Serial print gives me this (if I turn potentiometer from 0 to 1000):

0ÿ(0ÿ(0ÿ(0ÿ(0ÿ(0ÿ(0ÿ(60(1ÿ(00(16(0ÿ(23(0ÿ(30(0ÿ(3ÿ(60(43(0ÿ(49(0ÿ(53(0ÿ(5ÿ(90(69(0ÿ(88(0ÿ(10(00(10(00(10(

What am I missing? Is it because I'm sending it as a string? Or is my buffer not the correct size?

Here is your main problem:
if (mySerial.available()) {
    for(;i < 2;){
        buf = mySerial.read();
        i++;
    }
....

There you are saying "If there is at least one character available in the buffer then read lots of characters from the buffer".
You can't read characters that aren't there yet.
So your stream of data is interspersed with the integer -1 which means "I don't have any data to read!"
I explain it all here: http://hacking.majenko.co.uk/reading-serial-on-the-arduino
By the way - character -1 looks like this: ÿ
You are sending your data as text.  That means, to send the value 348 you are first sending the byte representation of the ASCII character "3", which is the decimal byte value 51.  Then you send the byte representation of the ASCII character "4", which is the decimal value 52, and finally you send the byte representation of the ASCII character "8", which is the decimal value 56.
You look to see if there is one byte available (if(mySerial.available())) and then read that byte into "buf" and increment "i" (by the way, "i" is never reset to 0 - your whole loop strategy is completely wrong, but that's a completely different issue).  You then read a second character and assign that to buf instead.
So if you have the character "3" in the serial buffer you then place that in "buf".  You then read whatever is next in the buffer, which 9 times out of 10 will be nothing, so read() returns -1.  So you just assign that to "buf" instead, replacing the "3" that was in there before.
But "buf" is a character array, and you are assigning a character to the whole array, which makes absolutely no sense (does the code even compile as you have shown it?).
Basically your whole reading routine is completely wrong and can never work no matter how much tweaking and advising we do.
The link I provided above describes not only how you should do the reading on the Arduino, but also how you should do the sending from the other end.  It is vitally important that you send something that says "This is the end of the number I am sending" so that the Arduino knows where one number ends and the next starts.  Normally that is done, when sending a textual representation of the number like this, by adding a line feed and/or carriage return at the end of your number.  So instead of sending "348" you send "248\n".
The Arduino then checks to see if there is one character available, and then it adds just that one character to the end of the buffer.  If, and only  if, that character is the delimiting character then you can take the buffer and translate it into an actual number and reset your buffer to be empty ready to receive the next number.
The link above has good example code showing you exactly how to do that.

Thanks, that was really helpful. But I still can't get it going. If I'm sending numbers from 0-1000, that means I'm sending 2 bytes. And when I want to read it like if(mySerial.available() >= 2) it's still a mess. Would you please be so kind to help me directly on this one?

Only if you're sending it as bytes. You're sending it as text though so it is between 1 and 4 bytes plus whatever you delimit with.

I think you should check your baud rates. A mismatch in baud rates usually makes that symbol get printed on the screen.

Use itoa instead of str.
str just converts the byte to an ASCII character. So 48 will become '0', 195 will become 'ÿ', and 191 will become '('.


text:
PWM timers, channels and pins
I've got this code from the MultiWii project, which is relevant to the hardware, ATmega32u4, I have. It is part of a function called initOutput().
In the comment it says "connect pin 6", which is the bit of that which specifies pin 6 as I would like to change it to another pin, specifically A0.
// Enhanced PWM mode
TCCR4E |= (1<<ENHC4);

// Prescaler to 16
TCCR4B &= ~(1<<CS41);
TCCR4B |= (1<<CS42) | (1<<CS40);

// Phase and frequency correct mode and top to 1023, but
// with enhanced PWM mode we have 2047.
TCCR4D |= (1<<WGM40);
TC4H = 0x3;
OCR4C = 0xFF;

// Connect pin 6 to timer 4 channel D
TCCR4C |= (1<<COM4D1) | (1<<PWM4D);

It's the (1<<COM4D1) that enables pin 6, or more specifically OC4D for timer output. You cannot use A0 instead, since there is no output compare capability on that pin; only pins 13, 5, 10, 9, 6, and 12 can be connected to timer 4. See the datasheet for details.

thanks for your answer, maybe you can help with my latest question: http://arduino.stackexchange.com/questions/13557/32u4-timer-4-help


text:
Error compiling
I have this code:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

#include <Wire.h>
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>

#include <GSM.h>

#define PINNUMBER ""  // Opt from user
#define GPS_RX_PIN 2
#define GPS_TX_PIN 3
#define WHITE 0x7  //For LCD library

//Objects initialization
GSM gsmAccess;
GSM_SMS sms;

Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

TinyGPSPlus gps;
SoftwareSerial ss(GPS_RX_PIN, GPS_TX_PIN);

// Chars and strings for gps values
char clat[10 + 20 + 1] = "Latitude/Longitude: ";
char clng[10 + 1];
String string1, string2, finalstr;

const int xpin = A0;                  // X-axis of the accelerometer
const int ypin = A1;                  // Y-axis
const int zpin = A2;                  // Z-axis (only on 3-axis models)

float convX = 0.0, convY = 0.0, convZ = 0.0;
int sampleDelay = 20;

char remoteNumber[20] = "306978666866"; // Opt from user

uint8_t i = 0;

void setup()
{
  Serial.begin(9600); //GSM
  ss.begin(4800);     //gps

  analogReference(EXTERNAL); // For external analog reference of ADXL335
  pinMode(xpin, INPUT);
  pinMode(ypin, INPUT);
  pinMode(zpin, INPUT);

  // Set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  lcd.setBacklight(WHITE);
  lcd.setCursor(0, 0);

  // GSM connection state
  boolean notConnected = true;

  while(notConnected)
  {
    if(gsmAccess.begin(PINNUMBER) == GSM_READY)
      notConnected = false;
    else
    {
      lcd.print("Not connected");
      delay(1000);
    }
  }
  lcd.print("GSM initialized");

  delay(2000);
  lcd.print("SELECT=Emergency");
}

void loop()
{
  bool uniFlag = false;
  int x = analogRead(xpin);
  delay(1); // Add a small delay between pin readings. I read that you should
            // do this but haven't tested the importance.

  int y = analogRead(ypin);
  delay(1);

  int z = analogRead(zpin);

  // zero_G is the reading we expect from the sensor when it detects
  // no acceleration. Subtract this value from the sensor reading to
  // get a shifted sensor reading.
  float zero_G = 502.0;

  // 'scale' is the number of units we expect the sensor reading to
  // change when the acceleration along an axis changes by 1G.
  // Divide the shifted sensor reading by scale to get acceleration in Gs.
  //   610 (1g) - 502 (0g) = 108
  float scale = 108;

  //value (g) = (measurement - 502)/ 108
  convX = ((float)x - zero_G)/scale;
  convY = ((float)y - zero_G)/scale;
  convZ = ((float)z - zero_G)/scale;

  delay(sampleDelay);

  if (convX > 2 || convX < -2 || convY > 2 || convY < -2)
    uniFlag = true;

  uint8_t buttons = lcd.readButtons();

  if (buttons) {
    if (buttons & BUTTON_SELECT) {
      uniFlag = true;}
  }

  if (uniFlag == true)
  {
    bool isGpsLocationValid = false;
    do
    {
      while (ss.available()>0)
      {
        char c = byte(ss.read());
        if (gps.encode(c))
        {
          if (gps.location.isValid())
          {
            dtostrf(gps.location.lat(), 10, 6, clat+20);
            dtostrf(gps.location.lng(), 10, 6, clng);
            isGpsLocationValid = true;
            string1 = String(clat);
            string2 = String(clng);
            finalstr = string1 + string2;
          }
        }
      }
    } while (isGpsLocationValid == false);
  }
  sendSMS(finalstr);
}

void sendSMS(String thisString)
{
  sms.beginSMS(remoteNumber);
  sms.print(thisString);
  sms.endSMS();
  lcd.setCursor(0, 0);
  lcd.print("Message sent!");
  delay(10000); //for multiple bumps
}

When I try to compile it I get these errors:
GSM\GSM3SoftSerial.cpp.o: In function `__vector_5':
C:\Program Files (x86)\Arduino\libraries\GSM/GSM3SoftSerial.cpp:525: multiple definition of `__vector_5'
SoftwareSerial\SoftwareSerial.cpp.o:C:\Program Files (x86)\Arduino\libraries\SoftwareSerial/SoftwareSerial.cpp:319: first defined here
GSM\GSM3SoftSerial.cpp.o: In function `__vector_4':
C:\Program Files (x86)\Arduino\libraries\GSM/GSM3SoftSerial.cpp:518: multiple definition of `__vector_4'
SoftwareSerial\SoftwareSerial.cpp.o:C:\Program Files (x86)\Arduino\libraries\SoftwareSerial/SoftwareSerial.cpp:312: first defined here
GSM\GSM3SoftSerial.cpp.o: In function `__vector_3':
C:\Program Files (x86)\Arduino\libraries\GSM/GSM3SoftSerial.cpp:511: multiple definition of `__vector_3'
SoftwareSerial\SoftwareSerial.cpp.o:C:\Program Files (x86)\Arduino\libraries\SoftwareSerial/SoftwareSerial.cpp:305: first defined here

What is going on? Is it that GSM.h declares SoftwareSerial inside? Are there any solutions?
This is the first time I get these kinds of compilation errors and have no idea what is going on or how to fix it.

Welcome to Arduino SE! Is it that GSM.h declares SoftwareSerial inside? You could've tried that before posting. It seems as that's the problem. I'm closing this as a duplicate of the question listed, in the time being as the errors are near identical, but if it's not, feel free to ping me with @ and my username or to flag this. Thanks!

No problem! Glad you got it solved.

the code utilizes interrupt 3/4/5 (check your datasheet to see what they are) that are already being utilized by other parts of your code.

Both SoftwareSerial and GSM are trying to declare the same interrupt vectors. You'll have to drop one of the libraries, find a replacement or change your code to omit one of the libraries. This is the disadvantage of using high level libraries.
Some Arduino's (Arduino Mega) have a microcontroller that supports more than one hardware serial channel, you may want to check that in the datasheet of the ATmega that is on the board.

I have not downloaded the libraries in question, but It would appear that there is a collision between "SoftSerial.h" and the "GSM/GSM3SoftSerial.h" built in to your GSM library.
There is a disscussion of this conflict here:
https://github.com/mainehackerclub/open_vehicle_tracker/issues/28
It seems the answer is to use the "AltSoftSerial" library instead of the stock "SoftSerial" library. The "AltSoftSerial" library can be downloaded here
http://www.pjrc.com/teensy/td_libs_AltSoftSerial.html


text:
Programming an Arduino BT-V06 using an UNO using ICSP
I have an Arduino BT-V06 laying around which I can't program over bluetooth for some reason. To be honest I don't understand the exact problem, but the problem is described in the question https://electronics.stackexchange.com/questions/7843/arduino-bt-upload-problem.
To solve the problem of programming the board I'm trying to program the BT-V06 using an Arduino Uno. I wired it all up using the description at https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader. The UNO seems fine, but the BT-V06 has the BATT-LOW led burning.
I've programmed the Arduino UNO using the Arduino ISP sketch. I've set the Arduino IDE to the COM port of the UNO, the target board to Arduino BT and the programmer to "Arduino as ISP". When trying to program the blink sketch I get the following error:
Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 28,672 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: verification error, first mismatch at byte 0x0002
         0x40 != 0x5c
avrdude: verification error; content mismatch

Could it be that the power requirements are too high to be powered through the UNO?

The sparkfun tutorial doesn't seems to mention the capacitor needed on the reset pin of the Arduino as ISP. On the Arduino Uno, you'll need to connect a 10 uF capacitor between reset and ground (source)

I'll have to buy the capacitor to try it out. Can you explain why it is needed?

When the IDE start to upload the code, it opens a serial connection. By design the Arduino Uno board resets when a new connection is opened. Because of this reset, the PC is communicating with the bootloader code, instead of the ISP sketch. They suggest you can also use a 120 ohm resistor between reset and 5v. Looking at the schematic, you can probably also directly connect it.


text:
Feasability of flashing Arduino UNO r3 with teensy firmware for HID (keyboard) emulation purposes
I've been working on a DIY keyboard project I have all the hardware designed and now its time for the code. For the microcontroller, I'm sort of locked into an Arduino UNO r3 as I already have it lying around. I know it doesn't have HID capabilities baked in, but I can flash different firmware to it. At first I was going to go with a generic HID firmware. This approach was problematic because it would require me to first write/send my Arduino sketch, then touch I wire to various portions of my UNO (it isn't SMD). After this,
I would flash the HID firmware and hope that there were no bugs in my sketch as fixing bugs would have required flashing Arduino firmware and repeating the aforementioned steps. I then had the idea to use Teensy firmware (https://www.pjrc.com/teensy/). This approach seems better, but I have questions regarding its feasibility.

Can I upload Teensy programs/sketches to the Arduino after I've
updated its firmware (if I had a real Teensy I could do this via the teensyduino plugin)?
Similarly, I'd like to write some software that allows me to remap
    the keyboard. Would the Teensy firmware allow this?
Does the Arduino have enough memory to support #2?
Is it possible to reflash BOTH the 8u2 and the 16u2 on my UNO (for details see #2 in update one below)
If 4 is possible is it possible to write code that would read/write the flash on the 8u2 as a filesystem? (for details see #2 in update one below)

Would the teensy firmware be a good option given these constraints? I know I've focused mainly on the Teensy, but if you have a more straightforward approach I'd love to hear it. Also, I know Arduino has a keyboard library(http://arduino.cc/en/Reference/MouseKeyboard) but, it seems rather basic, seems to block other keyboard signals while in use, and isn't easily remappable(see #2). I haven't completely written this off, so if you think this would be the best option please let me know. Thanks for any and all help.
Update
Thanks to one of the questions linked by @Ignacio Vazquez-Abrams(Can the 2nd MCU on the UNO R3 be used for keyboard emulation?) on the original question(weirdly it didn't show up here)  I have learned the following things(not necessarily from the question itself but by links provided in it):

the Atmel 8u2 of the UNO has 8kb of flash while the 16u2 has 16kb (should've known) I still don't know if either of these sizes are enough to hold my Teensy code AND 1+ map files generated by the mapping software I would make. (see #2 above)
the 8u2 seems like the chip that tinkers are generally advised to reprogram as it wouldn't hold the Arduino sketch. If I'm uploading teensy firmware I shouldn't need Arduino sketch capability (Teensy has that built in) So What I might do is use the 16u2 as a place to hold the firmware my code and use the 8u2 as a filesystem to hold any maps I'd like to store. This leads to more questions see the newly added 4 and 5

Reading that question and all the other related questions will allow you to make an informed decision regarding your plan.

No, you can't put the teensy bootloader on the UNO. The teensy has an ATMEGA32U4 and the UNO has an ATmega328.  The 32U4 has USB support in hardware the 328 does not.
The UNO does have a ATMEGA16U2 which does have USB in hardware like the 32U4 but it is programmed as a USB serial converter (to replace the FTDI chip used in earlier arduinos).
It might be possible to install a modified teensy bootloader on the 16U2 but that wouldn't help you because it is not connected to any of the I/O pins on the UNO.
In any case to install new firmware on the 16U2 you would need to buy something that can program the 16U2 via the ICSP and if you are going to buy something you might as well just buy a Leonardo or Teensy since they already support emulating a keyboard.
Now if you really wanted to spend the time it might be possible to write your own bootloader for both the 16U2 and the 328 on the UNO in such a way that they emulate a teensy or Leonardo but it won't be easy, and you would be limited by the smaller memory available in the 16U2.

So your basically recommending Teensy? I may be in luck, someone offered to give me one

I am recommending getting a board that already can do what you want.  Either the Teensy or Leonardo can do it. If you have existing shields the Leonardo may be a better choice since it has the standard Arduino layout.

No shields are needed. Going with the teensy since it is free.

See my answer from http://arduino.stackexchange.com/questions/1840/where-can-i-find-out-how-to-make-a-hex-file-for-arduino-firmware/1845#1845 . The end is same goal. Where I recommend a Leo.

You actually do not need a ICSP programmer for the UNO's 16u2, as it supports DFU. Unlike the 328's bootloader is replaced. But for the cost, I would suggest getting a Programmer.

Teensy uses a proprietary boot loader called half K (as in 500 bytes). Doubt one would get the source or image to burn into the 16u2.
Where you can get 8/16u2 USB to HID code examples here: https://github.com/harlequin-tech/arduino-usb

Thank you while that does look interesting, I've decided to go with the Teensy (actual physical device). This way I have the key64 firmware to piggyback off of and can be sure that I have enough space


text:
Arduino clock needed to print the time a button is pressed while continuing to count the time?
I'm making a clock using an arduino uno and a compatible freetronics screen. So far it can count the time in a 24 hour loop after which it repeats and counts again. The screen had a number of buttons built onto it and I want to get it so that when one of the buttons on the screen is pressed it prints the time that it was pressed on the top line of the screen while continuing to count and print the time on the second line of the screen.
How can I edit my code below to do this when a button is pressed? What sort of command do I need to add?
#include <Wire.h>
#include <LiquidCrystal.h>

#define MILLIS_OVERFLOW 34359738

/**
* Clock Variables
*/
unsigned long currentMillis, previousMillis, elapsedMillis;
int seconds = 0, minutes = 0, hours = 8;

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

void setup()
{
  Serial.begin(9600);
    lcd.begin( 16, 2 );

}

void loop()
{
setClock();

/**
 * After set clock now you have 3 int variables with the current time
 */
 //seconds
 //minutes
 //hours
 lcd.setCursor ( 0, 1);
 lcd.print(hours);
 lcd.print(":");
 lcd.print(minutes);
 lcd.print(":");
 lcd.print(seconds);
 lcd.print(":");
 lcd.print(elapsedMillis);

}

void setClock()
{
currentMillis = millis();
/**
 * The only moment when currentMillis will be smaller than previousMillis
 * will be when millis() oveflows
 */
if (currentMillis < previousMillis){
    elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
} else {
    elapsedMillis += currentMillis - previousMillis;
}

/**
 * If we use equals 1000 its possible that because of the mentioned loop limitation
 * you check the difference when its value is (999) and on the next loop its value is (1001)
 */
if (elapsedMillis > 999){
    seconds++;
    elapsedMillis = elapsedMillis - 1000;
}

if (seconds == 60){
    minutes++;
    seconds = 0;
}
if (minutes == 60){
    hours++;
    minutes = 0;
}
if (hours == 24){
    hours = 0;
}

previousMillis = currentMillis;
}

Any help will be greatly appreciated, thanks

What is your question?

How do I programme it so the button will print the time on the top line of the screen when pressed?

Since you will have to deal with two different times, I suggest
writing a small class for representing those times in broken-down form.
This is a reduced version of the classical strcut tm. Times are made
Printable so you can just print() them to the LCD. I included an
increment() method to add one second to this time.
class BrokenDownTime : public Printable {
    uint8_t hours;
    uint8_t minutes;
    uint8_t seconds;
public:
    void increment();
    size_t printTo(Print &p) const;
};

/* Increment the time by one second. */
void BrokenDownTime::increment()
{
    if (++seconds >= 60) {
        seconds = 0;
        if (++minutes >= 60) {
            minutes = 0;
            if (++hours >= 24)
                hours = 0;
        }
    }
}

/*
 * Print to anything that inherits from the Print class (Serial,
 * LiquidCrystal, etc.). This makes times `Printable'.
 */
size_t BrokenDownTime::printTo(Print &p) const
{
    p.print(hours/10);
    p.print(hours%10);
    p.write(':');
    p.print(minutes/10);
    p.print(minutes%10);
    p.write(':');
    p.print(seconds/10);
    p.print(seconds%10);
    return 8;  // 8 bytes written
}

The main program checks in loop() for the button being pressed. When
this happens, it saves the current time as lastPress. If the button
was ever pressed (variable button_was_pressed), the recorded time is
displayed on the first line:
#include <LiquidCrystal.h>

#define BUTTON_ADC_PIN A0

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
BrokenDownTime now;

/* Detect a press on `left', change the thresholds for other buttons. */
bool buttonPressed()
{
    int reading = analogRead(BUTTON_ADC_PIN);
    return reading > 405 && reading < 605;
}

/* Update `now'. */
void updateTime()
{
    static unsigned long last;
    if (millis() - last >= 1000) {
        now.increment();
        last += 1000;
    }
}

void setup()
{
    lcd.begin(16, 2);
}

void loop()
{
    static BrokenDownTime lastPress;
    static bool button_was_pressed;

    updateTime();

    /* Record the time of the button press. */
    if (buttonPressed()) {
        lastPress = now;
        button_was_pressed = true;
    }

    /* Display the recorded time on the first line. */
    if (button_was_pressed) {
        lcd.setCursor(0, 0);
        lcd.print(lastPress);
    }

    /* Display the current time on the second line. */
    lcd.setCursor(0, 1);
    lcd.print(now);
}

I did not test the program, but I hope you get the idea.

use a second variable called TNow and when the button is pressed pass it the value of currentMillis. parse  and use this as the value to display. or have misunderstood your question? wondering why you aren't using a time library. such as this
if you look on the site here  use the time library you can then use  variable name = now();

I do not understand what you mean by this.

The Time library is probably a good choice if this grows into a “real” clock. For the OP’s toy program, however, it looks a bit overkill: Whenever you ask it to break a time value into hours, minutes and seconds, it also computes the year, month, day-of-week and day-of-month, just in case you may need it later. That's a lot more expensive than incrementing an (hours, minutes, seconds) triplet. And it's times are not Printable, so you still have to write your own print routine.

You probably want to read the button press on LCD using "read_LCD_buttons" function. See an example at: Arduino LCD KeyPad Shield.
So your part of your code would probably be:
#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5
int lcd_key     = 0;

void loop()
{
 setClock();

 /**
 * After set clock now you have 3 int variables with the current time
 */
 //seconds
 //minutes
 //hours
 printValueAtLine(0);

 lcd_key = read_LCD_buttons();  // read the buttons

 switch (lcd_key)
 {
   case btnSELECT:
   {
     printValueAtLine(1);
     break;
   }
   case btnRIGHT:
   {
     // code in case other buttons like  btnRIGHT, etc are pressed
     break;
   }
   case btnNONE:
   {
     //do nothing
     break;
   }
 }
}

void printValueAtLine(int line)
{
 lcd.setCursor (1, line);
 lcd.print(hours);
 lcd.print(":");
 lcd.print(minutes);
 lcd.print(":");
 lcd.print(seconds);
 lcd.print(":");
 lcd.print(elapsedMillis);
}

The code is untested and you may have to make minor corrections to it.
Also, rather than saving values in global variables, you might want to use local ones using libraries suggested by wobbler.


text:
Set start time for arduino uno clock
I'm programming an arduino uno with attached screen to be a clock and have the code below. It counts up from zero the milliseconds, seconds, minutes and hours and when it hits 24 hours it starts again from zero.
Does anyone know how I can set the start time that it automatically starts at when it is reset? It will be a one off thing and I don't want it to interfere with the clock resetting to 0 hours after it hits 24. Thanks
#include <Wire.h>
#include <LiquidCrystal.h>

#define MILLIS_OVERFLOW 34359738

/**
 * Clock Variables
 */
unsigned long currentMillis, previousMillis, elapsedMillis;
int seconds, minutes, hours;

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

void setup()
{
    lcd.begin( 16, 2 );

}

void loop()
{
    setClock();
    /**
     * After set clock now you have 3 int variables with the current time
     */
     //seconds
     //minutes
     //hours
     lcd.setCursor ( 0, 1);
     lcd.print(hours);
     lcd.print(":");
     lcd.print(minutes);
     lcd.print(":");
     lcd.print(seconds);
     lcd.print(":");
     lcd.print(elapsedMillis);

}

void setClock()
{
    currentMillis = millis();
    /**
     * The only moment when currentMillis will be smaller than previousMillis
 * will be when millis() oveflows
 */
if (currentMillis < previousMillis){
    elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
} else {
    elapsedMillis += currentMillis - previousMillis;
}

/**
 * If we use equals 1000 its possible that because of the mentioned loop limitation
 * you check the difference when its value is (999) and on the next loop its value is (1001)
 */
if (elapsedMillis > 999){
    seconds++;
    elapsedMillis = elapsedMillis - 1000;
}

if (seconds == 60){
    minutes++;
    seconds = 0;
}
if (minutes == 60){
    hours++;
    minutes = 0;
}
if (hours == 24){
    hours = 0;
}

previousMillis = currentMillis;
}

Assume you want the clock to start at 08:42:21, change
int seconds, minutes, hours;

to
int seconds = 21, minutes = 42, hours = 8;

Note that you should always also initialize (as in the second case above), and not only declare (as in the first case) all variables before you first read their values. Otherwise, for local variables you cannot be sure what their initial value is. (Global variables are implicitly initialized to zero if not explicitly initialized.)

Your last sentence is incorrect. Global variables, like the ones discussed here, are implicitly initialized to zero if not explicitly initialized. The link you provide to support your assertion is for local variables.


text:
MFRC522 Only working sometimes
   /*
 * --------------------------------------------------------------------------------------------------------------------
 * Example sketch/program showing how to read data from a PICC to serial.
 * --------------------------------------------------------------------------------------------------------------------
 * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
 *
 * Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
 * Reader on the Arduino SPI interface.
 *
 * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
 * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
 * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
 * will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in communication" messages
 * when removing the PICC from reading distance too early.
 *
 * If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple tag reading).
 * So if you stack two or more PICCs on top of each other and present them to the reader, it will first output all
 * details of the first and then the next PICC. Note that this may take some time as all data blocks are dumped, so
 * keep the PICCs at reading distance until complete.
 *
 * @license Released into the public domain.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10       // Configurable, see typical pin layout above

MFRC522 MFRC522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
    Serial.begin(9600);     // Initialize serial communications with the PC
    while (!Serial);        // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();            // Init SPI bus
    MFRC522.PCD_Init();     // Init MFRC522
    MFRC522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
    Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
  Serial.print("...");
}

void loop() {
    // Look for new cards
    if ( ! MFRC522.PICC_IsNewCardPresent()) {
    Serial.print("IsNewCardPresent");
        return;
    }

    // Select one of the cards
    if ( ! MFRC522.PICC_ReadCardSerial()) {
    Serial.print("ReadCardSerial");
        return;
    }

    // Dump debug info about the card; PICC_HaltA() is automatically called
    MFRC522.PICC_DumpToSerial(&(MFRC522.uid));
}

I have recently purchased a RC522 RFID Module for my Arduino UNO. I connected everything, and started the IDE, downloaded the correct library, and ran the DumpInfo example program. The first time that I ran it, all went well, and when I swiped a card in fro, I recieved the correct data dump.
However, I started it up today, and reset everything, ran a new program to clear the Arduino, restarted my PC, and it still did not work. In the serial monitor it says that all is well, no error messages or anything. But, when I put a card in front of it, absolutely nothing happens.
Any help would be great!

Loose connection?

Definitely not, I made sure that all of them were well connected, and that would have returned an error in the Monitor if one wasn't communicating.

Do you see the firmware number and so on when you run the sketch?

Yes. It says
Firmware Version: 0x92 = v2.0
Scan PICC to see UID, type, and data blocks...

And you have made no changes at all to your code since the last time you got results? Are you using the same card as before? Also swiping/waving it within 5cm of the RC522?

No changes to the code whatsoever. I'm using the same cards and going withing 5cm of the reader.

Should I try and use the ICSP connections instead?

You can try, though this is a weird one. By all indications, bi-directional communications have been established since you can read the version. Also this code has worked for you before (more than once?). Maybe you should try powering it with some other source, Also try placing Serial.print statements in each IF block in the loop() to see if those conditions are responsible.

I tried adding the Serial.print lines, and it just spams the Serial Monitor with isnewcardpresent, meaning that it's going through that loop.I tried swiping a card in front during, but it didn't get out of the loop.

I don't really have the ability to power it from any other place, and i'm not sure where you were going with that.

ran a new program to clear the Arduino - can you explain that bit?

Just clicked the new button on the IDE and ran it while it was connected to the Arduino to clear it.

So, I believe that it is some form of state that the RFID Module goes into when I shut down my comptuter, how would I go about reseting the module?

Just clicked the new button on the IDE and ran it while it was connected to the Arduino to clear it. - and after that, did you load the other program? The RFID one? I don't see any point in loading other code "to clear it". You may as well put a Star Wars DVD into your DVD player "to clear it" before watching something else entirely.

Yes, after that, I loaded the other program. Thank you for the Snarky remark. No, the issue isn't the programming, it's that the module is not resetting correctly after I restart my computer or it goes to sleep. As power is cut to the module, and then restored. I know it's not the program because I'm receiving the firmware version back from the module.

The first thing you could try is to increase the baud rate to 115200. I'm using a different library, and in the auth_read_write.ino sketch the Serial.begin() comments says "Read a fast as possible. There is a limit for how long we are allowed to read from the tags".
If changing the baud rate doesn't work, then have a look at this answer: RFID-RC522 not working, red led is on. It has a link to a different library which worked for me.

Check your power supply. I've seen so many weird results from inconsistent/under powered circuits. It's worth a look.
What does your circuit look like?
Are you powering the RFID reader from the Arduino or it's own source?
Are the grounds coupled?

I'm powering it from the Arduino, and it's getting ample power supply, as it is sending and receiving data. The grounds are fine.

If I am right then you have soldered the pins of the module yourself and I recommend you to desolder the pins and soldered them again.
I also used RC522 RFID Module with an Arduino and I faced same type of problem with the module. This way worked for me.


text:
Arduino on attiny85 driving 4-digit 7-segment using two 74HC595N shift register not alternating fast enough
I am using a port of the Arduino libraries on an AtTiny85 (1MHz) to drive a 4-digit 7-segment LED (common cathode, 12-pin). I'm just counting from 0 to 9 and alternating between the first two digits (pin 12 and 9) as a test. I am driving from two 74HC595N shift registers in series, the first of which will trigger S9018 NPN BJT transistors to turn on/off the digit I want and the other to light the segments.
The code seems to work fine, functionally, to alternate the two digits, but they don't alternate fast enough to make the LED show two solid digits, instead you can clearly see them flashing/alternating. Not sure what the bottleneck is but here's the code (please ignore my wiring for the 7 segments)
// CONFIGURATION
// Pins
const int latchPin = 2;
const int clockPin = 4;
const int dataPin = 3;

// Timers
const long output_interval = 10000; // Time to change each output
const int T_digit = 2; //period on one digit (4 digit 7-segment only)
const int duty_digit = 1; // duty cyle of a digit shown

// States
unsigned long outputT_last = 0; // Holds the last time output change was checked
unsigned long outputT_now = 0;
bool fourDigit7Segment_enable = true; // set if we are using 4 digit 7 segment led

// States
byte leds = 0;
byte digits = 0;

int output_count=0;

void setup()
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{
  checkOutput();
}

void updateShiftRegister()
{
  digitalWrite(latchPin, LOW); // Gets latch ready by setting to low since we need a rising edge to trigger
  if(fourDigit7Segment_enable){
    int digitON = (int)(outputT_now - outputT_last);
    digits = 0;
    if(digitON%T_digit < duty_digit){
      //bitwrite led 0
      bitWrite(digits, 0, 1);
    }
    else{
      //bitwrite led 1
      bitWrite(digits, 1, 1);
    }
    //shift out digit control first in LSB
    shiftOut(dataPin, clockPin, MSBFIRST, digits); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
  }
  shiftOut(dataPin, clockPin, MSBFIRST, leds); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
  digitalWrite(latchPin, HIGH); // Trigger with rising edge
}

void clearMemory(){
  leds = 0;
  updateShiftRegister();
}

void checkOutput(){
  outputT_now = millis();
  float timeleft = (int)((outputT_now - outputT_last)/1000);
  if (outputT_now - outputT_last >= output_interval){
    outputT_last = outputT_now; // output_interval set to 10000, because LED counts 0 to 9, and then needs to reset
  }
    // clearMemory(); // Uncomment this if you want 1 LED lit at time, all others turned off
    leds = sevenSegment1D(timeleft);
    updateShiftRegister();
    // output_count++;
  // }
  // Check if we reach the end, then do 1 more iteration for 0x0 (all turned off)
  // if(output_count > 8){
    // output_count=0;
    // clearMemory();
  // }
}

byte sevenSegment1D(int i){
  switch (i) {
      case 0:
        return 0x7E; //01111110
        break;
      case 1:
        return 0x48; //01001000
        break;
      case 2:
        return 0x3D; //00111101
        break;
      case 3:
        return 0x6D; //01101101
        break;
      case 4:
        return 0x4B; //01001011
        break;
      case 5:
        return 0x67; //01100111
        break;
      case 6:
        return 0x77; //01110111
        break;
      case 7:
        return 0x4C; //01001100
        break;
      case 8:
        return 0x7F; //01111111
        break;
      case 9:
        return 0x6F; //01101111
        break;
      default:
        return 0x0; //Arduino doesn't handle bytes in binary
  }
}

I tried to mod a float but it seems to require an int, so that's why I stopped at 2%1. I also converted the code from a single-digit 7-segment LED so please ignore anything that doesn't make sense in lighting up the segments.
I am not sure if the bottleneck is my code, the 1MHz AtTiny85, or the shift register.
EDIT: switched over to micros() instead of using millis() for more resolution. Still not solid.

Did you pick a board entry that specifies 1MHz?

I am unsure how to check this.

Did you try looking at the board entry?

Can't you just lower T_digit? Better would be to use a timer to update the digits every X ms. That way the main loop doesn't interfere with the display update. 1mHz should be fast enough to get at least 60hz update speed.

Turns out there is something wrong with my mod calculation. I did a test with to shift out the first digit, reset, then shift out another with delay(2) and it's solid.

Unless you really, really need something unique about the '85, such as the pll, this design just does not make sense.  Don't use an '85 with an external shift register, rather use a micro with a decent number of pins like an ATmega.  There's also little reason to run your clock so slowly - in theory doing so could save power, but if you have a 7-segment display your need a decent power source anyway.

The original idea was to divide up a specific period into segments where each digit on the 4-digit 7-segment would light up. I would use a mod(%) and divide it up to make the function call more generic for future extensibility (and also make it more asynchronous). What I learned is that it would probably take more work doing the calculations then just calling a function to reset and light up the next digit one after another. Here's the updated code:
// CONFIGURATION
// Pins
const int latchPin = 2;
const int clockPin = 4;
const int dataPin = 3;

// Timers
const int countdown = 60; // amount of time to countdown from in seconds
const long reset_interval = countdown*1000000; // interval before reset in microseconds, i.e. if countdown is set to 60s, every 60 seconds will reset display to countdown start

// States
unsigned long last_display_update_time = 0; // Holds the last time output change was checked
unsigned long curr_time = 0;
bool fourDigit7Segment_enable = true; // set if we are using 4 digit 7 segment led

// States
byte leds = 0;
byte digits = 0;

int output_count=0;

void setup()
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{
  updateResetTimer(); // checks what the countdown is at
  int timeleft = countdown - (curr_time - last_display_update_time)/1000000;
  leds = getSevenSegmentFormation(timeleft/10);
  updateShiftRegister(0);
  leds = getSevenSegmentFormation(timeleft%10);
  updateShiftRegister(1);
}

void updateShiftRegister(int digit)
{
  digitalWrite(latchPin, LOW); // Gets latch ready by setting to low since we need a rising edge to trigger
  if(fourDigit7Segment_enable){
    int digitON = micros();
    digits = 0;
    bitWrite(digits, digit, 1);
    //shift out digit control first in LSB
    shiftOut(dataPin, clockPin, MSBFIRST, digits); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
  }
  shiftOut(dataPin, clockPin, MSBFIRST, leds); // shiftOut will write to dataPin and trigger a rising on clickPin at same time while writing byte value from leds var
  digitalWrite(latchPin, HIGH); // Trigger with rising edge
}

//Turns off all 7 segments of a digit, will need to specify digits 0 to n
void clearMemory(int i){
  leds = 0;
  updateShiftRegister(i);
}

//Updating timer for resetting countdown
//Will take absolute current time and compare it to the last time checked, if it is greater than countdown value, we reset
void updateResetTimer(){
  curr_time = micros();
  if (curr_time - last_display_update_time >= reset_interval){
    last_display_update_time = curr_time; // reset_interval set to 10000000, because LED counts 0 to 9, and then needs to reset // actually set to 60*1000000 to countdown 1 minute
  }
}

byte getSevenSegmentFormation(int i){
  switch (i) {
      case 0:
        return 0x7E; //01111110
        break;
      case 1:
        return 0x48; //01001000
        break;
      case 2:
        return 0x3D; //00111101
        break;
      case 3:
        return 0x6D; //01101101
        break;
      case 4:
        return 0x4B; //01001011
        break;
      case 5:
        return 0x67; //01100111
        break;
      case 6:
        return 0x77; //01110111
        break;
      case 7:
        return 0x4C; //01001100
        break;
      case 8:
        return 0x7F; //01111111
        break;
      case 9:
        return 0x6F; //01101111
        break;
      default:
        return 0x0; //Arduino doesn't handle bytes in binary
  }
}


text:
Integrating 2 push buttons to toggle the LED ON and OFF
Hey guys need your help in verifying out this program about toggling the LED ON and OFF using 2 push buttons.What i actually want is to let my LED stay ON when i press and even leave the push button-1 , and on pressing and leaving the push button-2 i want the led to turn off and no matter how many times i press the push button-1 i want it to turn ON the LED and the push button-2 should only turn off the LED.but with my program i am only able to see the LED to be at HIGH state,It is not shifting to LOW state on clicking push button-2.
This is my sketch :-
    /* LED CONTROLLED WITH 2 PUSH BUTTON PROJECT
       BY ARSH BANSAL

 CIRCUIT :-
 i) LEDPIN CONNECTED PIN 13.
 ii) PUSHBUTTON1 CONNECTED TO PIN 8.
 iii) PUSHBUTTON2 CONNECTED TO PIN 7.
 iv) BOTH THE PUSH BUTTONS CONNECTED PARALLELY, EACH WITH A 1K PULLUP RESISTOR AND BOTH THE PUSH BUTTONS CONNECTED TO 5V SUPPLY.
   */

 int ledpin = 13;
 int pushbutton1 = 8;
 int pushbutton2 = 7;
 boolean lastbuttonstate1 = LOW;
 boolean lastbuttonstate2 = LOW;

 void setup()
 {
   pinMode(ledpin,OUTPUT);
   pinMode(pushbutton1,INPUT);
   pinMode(pushbutton2,INPUT);
 }

 void loop()
 {
   if ( digitalRead(pushbutton1)== HIGH && digitalRead(pushbutton2) == LOW && lastbuttonstate1 == LOW )
    { digitalWrite (ledpin,HIGH) ;}

   else ( digitalRead(pushbutton1) == LOW && digitalRead(pushbutton2)== LOW && lastbuttonstate1 == HIGH)
    ; { digitalWrite (ledpin,HIGH) ; }

    if ( digitalRead(pushbutton1)== LOW && digitalRead(pushbutton2) == HIGH  && lastbuttonstate2 == LOW)
    { digitalWrite (ledpin,LOW) ;}

   else ( digitalRead(pushbutton1) == LOW && digitalRead(pushbutton2)== LOW  && lastbuttonstate2 == HIGH)
    ; { digitalWrite (ledpin,LOW) ; }
    }

You are better off, in this case, remembering the state of the LED not the state of the buttons:

If the LED is OFF and BUTTON1 is PRESSED then turn the LED on.
If the LED is ON and BUTTON2 is PRESSED then turn the LED off.

For example:
void loop() {
    static bool ledState = false; // LED is off by default
    if ((digitalRead(pushbutton1) == LOW) && !ledState) { // 1 pressed & led is off
        digitalWrite(ledpin, HIGH);
        ledState = true;
    }
    if ((digitalRead(pushbutton2) == LOW) && ledState) { // 2 pressed & led is on
        digitalWrite(ledpin, LOW);
        ledState = false;
    }
}

I just understood my mistake i should have used if statement after else to check the respective conditions well thanks for your efforts.


text:
Clearing arduino serial buffer
How to clear the serial buffer of arduino uno?
This is my code to on and off the LED using sms from mobile using gsm module
#include <SoftwareSerial.h>
int Led=7;

SoftwareSerial mySerial(9, 10);

void setup()
{
  pinMode(Led,OUTPUT);
  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}

void loop()
{
  if (mySerial.available()>0)
  {

  }
   switch(mySerial.read())
  {
    case 'a':
           digitalWrite(Led,HIGH);
           delay(10000);
           digitalWrite(Led,LOW);
           delay(100);
           break;

    case 'b' :
           digitalWrite(Led,LOW);
           break;

  }}

problem is whenever i on the module or the connection is restablished it automatically gets even without an sms.I need it to be fully in my control so i need to clear the serial buffer.

If you are receiving unsolicited message (reading junk) then you could extend the bit pattern you are expecting so that there is almost no possibility of you accidentally receiving it.
Rather than 'a' and 'b' as triggers user LED="0" and LED="1".  Doing this makes reading the data much harder, because what you are looking for may start on character 4 of the string you read.  This is what I think you will need to do.

Read each character in turn and store them in a buffer until you have 7.
Is the first character an L.
If it isn't then delete the first character, shuffle the buffer left
one place and load in the next character before returning to step 1.
If it was, check the next character matches the expected.
If it doesn't match delete all character to the left and this one and return to step one.
If you have a matching token then parse it (get the 1 or 0) and do the action.

You can simply clear it by reading it until its empty.
while(Serial.available()){
    Serial.read();
}

There also used to be a
Serial.flush();

to clear the serial. However they changed it to some other functionality. For further details you can look at the arduino reference page on Serial.


text:
RFID detects the first card fine, but hangs on a second
I am writing a program that:

Reads string (one line) from com port
Waits for an RFID card to be present
Reads a block from the card

Here's the code (it uses this MFRC522 library, also the code is based on makecourse.com  RFID tutorial):
#include <SPI.h> //include the SPI bus library
#include <MFRC522.h> //include the RFID reader library

#define SS_PIN 10  //slave select pin
#define RST_PIN 9  //reset pin
MFRC522 mfrc522(SS_PIN, RST_PIN);        // instatiate a MFRC522 reader object.
MFRC522::MIFARE_Key key; //create a MIFARE_Key struct named 'key', which will hold the card information

byte readbackblock[18]; //This array is used for reading out a block. The MIFARE_Read method requires a buffer that is at least 18 bytes to hold the 16 bytes of a block.

String inString = ""; // COM port incoming data buffer

void setup() {
  Serial.begin(9600);        // Initialize serial communications with the PC
  SPI.begin();               // Init SPI bus
  mfrc522.PCD_Init();        // Init MFRC522 card (in case you wonder what PCD means: proximity coupling device)
  Serial.println("Scan a MIFARE Classic card");

  // Prepare the security key for the read and write functions - all six key bytes are set to 0xFF at chip delivery from the factory.
  // Since the cards in the kit are new and the keys were never defined, they are 0xFF
  // if we had a card that was programmed by someone else, we would need to know the key to be able to access it. This key would then need to be stored in 'key' instead.

  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;//keyByte is defined in the "MIFARE_Key" 'struct' definition in the .h file of the library
  }

}

void loop() {
  while (Serial.available() > 0) {
    int inChar = Serial.read();

    if (inChar != '\n') {
      inString += (char)inChar;
    } else {
      // New line

      Serial.println("Start");
      while (!initcard()); // Detecting new card
      Serial.println("CardFound");
      readBlockToCom(2); // Reading a block
      Serial.println("Done");
      inString = "";
    }
  }
}

bool initcard()
{
  // Look for new cards (in case you wonder what PICC means: proximity integrated circuit card)
  if ( ! mfrc522.PICC_IsNewCardPresent()) {//if PICC_IsNewCardPresent returns 1, a new card has been found and we continue
    return false; //if it did not find a new card is returns a '0' and we return to the start of the loop
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {//if PICC_ReadCardSerial returns 1, the "uid" struct (see MFRC522.h lines 238-45)) contains the ID of the read card.
    return false; //if it returns a '0' something went wrong and we return to the start of the loop
  }
  return true;
}

void readBlockToCom(int number)
{
  readBlock(number, readbackblock);//read the block back
  Serial.print("read block: ");
  for (int j = 0 ; j < 16 ; j++) //print the block contents
  {
    Serial.write (readbackblock[j]);//Serial.write() transmits the ASCII numbers as human readable characters to serial monitor
  }
  Serial.println("");
}

int readBlock(int blockNumber, byte arrayAddress[])
{
  int largestModulo4Number=blockNumber/4*4;
  int trailerBlock=largestModulo4Number+3;//determine trailer block for the sector

  /*****************************************authentication of the desired block for access***********************************************************/
  byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
  //byte PCD_Authenticate(byte command, byte blockAddr, MIFARE_Key *key, Uid *uid);
  //this method is used to authenticate a certain block for writing or reading
  //command: See enumerations above -> PICC_CMD_MF_AUTH_KEY_A   = 0x60 (=1100000),      // this command performs authentication with Key A
  //blockAddr is the number of the block from 0 to 15.
  //MIFARE_Key *key is a pointer to the MIFARE_Key struct defined above, this struct needs to be defined for each block. New cards have all A/B= FF FF FF FF FF FF
  //Uid *uid is a pointer to the UID struct that contains the user ID of the card.
  if (status != MFRC522::STATUS_OK) {
         Serial.print("PCD_Authenticate() failed (read): ");
         Serial.println(mfrc522.GetStatusCodeName(status));
         return 3;//return "3" as error message
  }
  //it appears the authentication needs to be made before every block read/write within a specific sector.
  //If a different sector is being authenticated access to the previous one is lost.

  /*****************************************reading a block***********************************************************/

  byte buffersize = 18;//we need to define a variable with the read buffer size, since the MIFARE_Read method below needs a pointer to the variable that contains the size...
  status = mfrc522.MIFARE_Read(blockNumber, arrayAddress, &buffersize);//&buffersize is a pointer to the buffersize variable; MIFARE_Read requires a pointer instead of just a number
  if (status != MFRC522::STATUS_OK) {
          Serial.print("MIFARE_read() failed: ");
          Serial.println(mfrc522.GetStatusCodeName(status));
          return 4;//return "4" as error message
  }
  Serial.println("block was read");
}

The problem I'm having is that

I send first line via com port
Apply a card to RFID-RC522
The program reads the block alright
But then I send the second line
Arduino hangs on card detect

Here's the output I receive:
Scan a MIFARE Classic card
Start
CardFound
block was read
read block: makecourse_____
Done
Start

I tried removing card and applying it again or applying a different card, but it still freezes on card detect, sometimes after some time it works, though.

You should try adding this, at the end of readBlock():
// Halt PICC
mfrc522.PICC_HaltA();
// Stop encryption on PCD
mfrc522.PCD_StopCrypto1();

Added this code after readBlockToCom(2); and it worked. Thank you.


text:
Running Steppers with servo
I'm doing a project which is automatic box carrier. It will hold a box from a location and move it next to it. Kind of cnc work. Locations are fixed it just has to run the orders. I want to send an array of integers and manage them in the switch under main loop. for example
  orders[0]=2;
  orders[1]=2000;

  orders[2]=3;
  orders[3]=60;

  orders[4]=1;
  orders[5]=7000;

  orders[6]=2;
  orders[7]=2000;

  orders[8]=3;
  orders[9]=90;

  orders[10]=1;
  orders[11]=2000;

will be my orders array and here is the code i want to run. When I upload code to arduino steppers and servo doing fine until orders[8]. When came to that order; first servo goes to 30 degrees then goes to 0 and click sound starts. After that steppers are not doing remaining steps.
#include <Servo.h>
Servo myservo;

int distance=0;
int code =0;
int orders[10]={};
int thisStep=0;
int thisVal=1;
int pos = 0;
int currpos=90;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  digitalWrite(2,LOW);
  digitalWrite(3,LOW);
  digitalWrite(4,LOW);
  digitalWrite(5,LOW);
  myservo.attach(9);

  orders[0]=2;
  orders[1]=7000;

  orders[2]=3;
  orders[3]=60;

  orders[4]=1;
  orders[5]=2000;

  orders[6]=2;
  orders[7]=2000;

  orders[8]=3;
  orders[9]=30;

  orders[10]=1;
  orders[11]=2000;

 /* orders[12]=2;
  orders[13]=5000;*/
}

void loop() {

  code = orders[thisStep];
  switch (code){
    case 1:

    go(orders[thisVal]);
    thisStep = thisStep + 2;
  thisVal = thisVal + 2;

    break;
    case 2:
     Serial.println(thisVal);
    goReverse(orders[thisVal]);
    thisStep = thisStep + 2;
    thisVal = thisVal + 2;

    break;

    case 3:
    goServo(orders[thisVal]);
    thisStep = thisStep + 2;
    thisVal = thisVal + 2;
    break;
  }

}
void go(int dist){
  digitalWrite(2,LOW);
  digitalWrite(4,LOW);
  do{
  digitalWrite(3,HIGH);
  digitalWrite(5,HIGH);
  delayMicroseconds(10);
  digitalWrite(3,LOW);
  digitalWrite(5,LOW);
  delayMicroseconds(10);
  distance = distance+1;
  Serial.println(distance);
  }while (dist>distance);
 distance=0;
 delay(500);
}
void goReverse(int dist){
  digitalWrite(2,HIGH);
  digitalWrite(4,HIGH);
  do{
  digitalWrite(3,HIGH);
  digitalWrite(5,HIGH);
  delayMicroseconds(300);
  digitalWrite(3,LOW);
  digitalWrite(5,LOW);
  delayMicroseconds(300);
  distance = distance+1;

  }while (dist>distance);
  distance=0;
  delay(500);
}

void goServo (int degree){
  myservo.attach(9);
  myservo.write(degree);

  delay(300);
   myservo.detach();
  /*if (currpos > degree)
  {
    for (pos = currpos; pos >= degree; pos -= 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
       myservo.write(pos);              // tell servo to go to position in variable 'pos'
       delay(15);
       // waits 15ms for the servo to reach the position
      }
      delay(500);
  }
  else if (currpos < degree)
  {
    for (pos = currpos; pos <= degree; pos += 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
       myservo.write(pos);              // tell servo to go to position in variable 'pos'
       delay(15);
       // waits 15ms for the servo to reach the position
      }

  }
  currpos=degree;

*/

}

Thanks.

Are you sure it's not due to thisStep being larger that the length of the array? Try adding if(thisStep>10)thisStep=0; to the loop.

Your problem here is that you have an array of 10 bytes, which works fine, only that in your loop you don't stop or check that you are within that array.
If this is supposed to run forever, you could add a line like this at the end of your loop:
if (thisStep > sizeof(orders)-1) thisStep = 0;

(-1 because you have an array of 10, which are from 0-9, sizeof will return 10)
this will make it start from the beginning again.


text:
How to generate hardware interrupt in mpu6050 to wakeup arduino from SLEEP_MODE_PWR_DOWN mode?
I am using Arduino UNO and has kept in SLEEP_MODE_PWR_DOWN mode & want it to wakeup using MPU6050 hardware INT pin (which should send a signal when MPU is in motion). I have used the article https://lukelectro.wordpress.com/2016/08/11/how-to-enable-motion-detection-interrupt-on-mpu6050/
    #include <Wire.h>
    //Analog port 4 (A4) = SDA (serial data)
    //Analog port 5 (A5) = SCL (serial clock)
    #define SIGNAL_PATH_RESET  0x68
    #define I2C_SLV0_ADDR      0x37
    #define ACCEL_CONFIG       0x1C
    #define MOT_THR            0x1F  // Motion detection threshold bits [7:0]
    #define MOT_DUR            0x20  // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms
    #define MOT_DETECT_CTRL    0x69
    #define INT_ENABLE         0x38
    #define WHO_AM_I_MPU6050   0x75 // Should return 0x68
    #define INT_STATUS 0x3A
    //when nothing connected to AD0 than address is 0x68
    #define ADO 0
    #if ADO
    #define MPU6050_ADDRESS 0x69  // Device address when ADO = 1
    #else
    #define MPU6050_ADDRESS 0x68  // Device address when ADO = 0
    #endif

    /*    Example for using write byte
          Configure the accelerometer for self-test
          writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, 0xF0); // Enable self test on all three axes and set accelerometer range to +/- 8 g */
    void writeByte(uint8_t address, uint8_t subAddress, uint8_t data)
    {
      Wire.begin();
      Wire.beginTransmission(address);  // Initialize the Tx buffer
      Wire.write(subAddress);           // Put slave register address in Tx buffer
      Wire.write(data);                 // Put data in Tx buffer
      Wire.endTransmission();           // Send the Tx buffer
    //  Serial.println("mnnj");

    }

    //example showing using readbytev   ----    readByte(MPU6050_ADDRESS, GYRO_CONFIG);
    uint8

_t readByte(uint8_t address, uint8_t subAddress)
{
  uint8_t data;                            // `data` will store the register data
  Wire.beginTransmission(address);         // Initialize the Tx buffer
  Wire.write(subAddress);                  // Put slave register address in Tx buffer
  Wire.endTransmission(false);             // Send the Tx buffer, but send a restart to keep connection alive
  Wire.requestFrom(address, (uint8_t) 1);  // Read one byte from slave register address
  data = Wire.read();                      // Fill Rx buffer with result
  return data;                             // Return data read from slave register
}

void setup()
{
   /*
    * #define SIGNAL_PATH_RESET  0x68
      #define I2C_SLV0_ADDR      0x37
      #define ACCEL_CONFIG       0x1C
      #define MOT_THR            0x1F  // Motion detection threshold bits [7:0]
      #define MOT_DUR            0x20  // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms
      #define MOT_DETECT_CTRL    0x69
      #define INT_ENABLE         0x38
      #define WHO_AM_I_MPU6050 0x75 // Should return 0x68
      #define INT_STATUS 0x3A*/
    Serial.begin(9600);
    writeByte( MPU6050_ADDRESS, SIGNAL_PATH_RESET, 0x07);//Reset all internal signal paths in the MPU-6050 by writing 0x07 to register 0x68;
    writeByte( MPU6050_ADDRESS, I2C_SLV0_ADDR, 0x20);//write register 0x37 to select how to use the interrupt pin. For an active high, push-pull signal that stays until register (decimal) 58 is read, write 0x20.
    writeByte( MPU6050_ADDRESS, ACCEL_CONFIG, 0x01);//Write register 28 (==0x1C) to set the Digital High Pass Filter, bits 3:0. For example set it to 0x01 for 5Hz. (These 3 bits are grey in the data sheet, but they are used! Leaving them 0 means the filter always outputs 0.)
    writeByte( MPU6050_ADDRESS, MOT_THR, 0x14);  //Write the desired Motion threshold to register 0x1F (For example, write decimal 20).
    writeByte( MPU6050_ADDRESS, MOT_DUR, 0x01 );  //Set motion detect duration to 1  ms; LSB is 1 ms @ 1 kHz rate
    writeByte( MPU6050_ADDRESS, MOT_DETECT_CTRL, 0x15); //to register 0x69, write the motion detection decrement and a few other settings (for example write 0x15 to set both free-fall and motion decrements to 1 and accelerometer start-up delay to 5ms total by adding 1ms. )
    writeByte( MPU6050_ADDRESS, INT_ENABLE, 0x40 ); //write register 0x38, bit 6 (0x40), to enable motion detection interrupt.     */

    pinMode(13, OUTPUT);      // sets the digital LED pin 13 as output
    pinMode(7, INPUT);        // sets the digital pin 7 as input

}
    uint16_t readdata;
void loop()
{
      Serial.println("scdf");

      if(digitalRead(7)==1)
      {
        while(1)
        {
          digitalWrite(13, 1);
          delay(100);
        }
      }

  //    readdata = readByte(MPU6050_ADDRESS,WHO_AM_I_MPU6050);
  //    Serial.println(readdata);
}

Are you using a library to configure the MPU6050 or interfacing with it manually with the Wire library?

Hi @Majenko..! I had edited the question and add the code..! in this I am simply using the wire library but in this mpu's INT pin is not generating trigger on motion which it should according to the article.

Well, this code worked. In this code, MPU's INT PIN is Active Low so generates Ground on motion which is than connected to INT0 or arduino UNO pin 2 which generates interrupt and wakes UP the MCU
#include <avr/sleep.h>

#include <Wire.h>
 //Analog port 4 (A4) = SDA (serial data)
//Analog port 5 (A5) = SCL (serial clock)
#define SIGNAL_PATH_RESET 0x68
#define I2C_SLV0_ADDR 0x37
#define ACCEL_CONFIG 0x1C
#define MOT_THR 0x1F // Motion detection threshold bits [7:0]
#define MOT_DUR 0x20 // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms
#define MOT_DETECT_CTRL 0x69
#define INT_ENABLE 0x38
#define WHO_AM_I_MPU6050 0x75 // Should return 0x68
#define INT_STATUS 0x3A
//when nothing connected to AD0 than address is 0x68
#define ADO 0
#if ADO
#define MPU6050_ADDRESS 0x69 // Device address when ADO = 1
#else
#define MPU6050_ADDRESS 0x68 // Device address when ADO = 0
#endif

int wakePin = 2; // pin used for waking up
int led = 13;
int flag = 0;

void wakeUpNow() { // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP    (i.e. after getting interrupt)
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up

  delay(500);
  Serial.println("WOKEN UP !!!!!!!!!!");
  delay(500);
  int count = 10;
  while (count != 0) {
    delay(1000);
    count--;
    Serial.println(count);
    delay(1000);
  }
  // precautionary while we do other stuff
  detachInterrupt(0);

}

/*    Example for using write byte
      Configure the accelerometer for self-test
      writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, 0xF0); // Enable self test on all three axes and set accelerometer range to +/- 8 g */
void writeByte(uint8_t address, uint8_t subAddress, uint8_t data) {
  Wire.begin();
  Wire.beginTransmission(address); // Initialize the Tx buffer
  Wire.write(subAddress); // Put slave register address in Tx buffer
  Wire.write(data); // Put data in Tx buffer
  Wire.endTransmission(); // Send the Tx buffer
  //  Serial.println("mnnj");

}

//example showing using readbytev   ----    readByte(MPU6050_ADDRESS, GYRO_CONFIG);
uint8_t readByte(uint8_t address, uint8_t subAddress) {
  uint8_t data; // `data` will store the register data
  Wire.beginTransmission(address); // Initialize the Tx buffer
  Wire.write(subAddress); // Put slave register address in Tx buffer
  Wire.endTransmission(false); // Send the Tx buffer, but send a restart to keep connection alive
  Wire.requestFrom(address, (uint8_t) 1); // Read one byte from slave register address
  data = Wire.read(); // Fill Rx buffer with result
  return data; // Return data read from slave register
}

void setup() {

  /*
   * #define SIGNAL_PATH_RESET  0x68
     #define I2C_SLV0_ADDR      0x37
     #define ACCEL_CONFIG       0x1C
     #define MOT_THR            0x1F  // Motion detection threshold bits [7:0]
     #define MOT_DUR            0x20  // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms
     #define MOT_DETECT_CTRL    0x69
     #define INT_ENABLE         0x38
     #define WHO_AM_I_MPU6050 0x75 // Should return 0x68
     #define INT_STATUS 0x3A*/
  Serial.begin(9600);
  writeByte(MPU6050_ADDRESS, 0x6B, 0x00);
  writeByte(MPU6050_ADDRESS, SIGNAL_PATH_RESET, 0x07); //Reset all internal signal paths in the MPU-6050 by writing 0x07 to register 0x68;
  writeByte(MPU6050_ADDRESS, I2C_SLV0_ADDR, 0x20); //write register 0x37 to select how to use the interrupt pin. For an active high, push-pull signal that stays until register (decimal) 58 is read, write 0x20.
  writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, 0x01); //Write register 28 (==0x1C) to set the Digital High Pass Filter, bits 3:0. For example set it to 0x01 for 5Hz. (These 3 bits are grey in the data sheet, but they are used! Leaving them 0 means the filter always outputs 0.)
  writeByte(MPU6050_ADDRESS, MOT_THR, 10); //Write the desired Motion threshold to register 0x1F (For example, write decimal 20).
  writeByte(MPU6050_ADDRESS, MOT_DUR, 40); //Set motion detect duration to 1  ms; LSB is 1 ms @ 1 kHz rate
  writeByte(MPU6050_ADDRESS, MOT_DETECT_CTRL, 0x15); //to register 0x69, write the motion detection decrement and a few other settings (for example write 0x15 to set both free-fall and motion decrements to 1 and accelerometer start-up delay to 5ms total by adding 1ms. )
  writeByte(MPU6050_ADDRESS, INT_ENABLE, 0x40); //write register 0x38, bit 6 (0x40), to enable motion detection interrupt.
  writeByte(MPU6050_ADDRESS, 0x37, 160); // now INT pin is active low

  pinMode(2, INPUT); // sets the digital pin 7 as input

  pinMode(wakePin, INPUT_PULLUP); // wakePin is pin no. 2
  pinMode(led, OUTPUT); //   led is pin no. 13
  // attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW

}

void sleepNow() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable(); // enables the sleep bit in the mcucr register
  delay(500);
  Serial.println("About to sleep");
  delay(500);
  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
  delay(500);
  Serial.println("Interupt attached");
  delay(500);
  sleep_mode(); // here the device is actually put to sleep...!!

  // THE PROGRAM CONTINUES FROM HERE AFTER INTERRUPT IS CLOSED
  delay(500);
  Serial.println("Continuing main program after interupt");
  delay(500);

  sleep_disable(); // first thing after waking from sleep: disable sl¯eep...
  delay(500);
  Serial.println("Sleep disabled");
  delay(500);
}
uint16_t readdata;
void loop() {
  if (digitalRead(2) == 0) {
    {

      digitalWrite(13, 1);
      delay(100);
      digitalWrite(13, 0);
      delay(100);
    }
  }
  sleepNow(); // sleep function called here
  readdata = readByte(MPU6050_ADDRESS, 0x3A);
  Serial.print(readdata);
  Serial.print(",");
  readdata = readByte(MPU6050_ADDRESS, 0x37);
  Serial.println(readdata);

}

Glad to see you got it working. Thank you for sharing your solution.

I needed to put detachInterrupt() in the wakeUpNow() function.  Otherwise works great.

+1 Worked great for me.  Love how no external libraries were needed.

Did not work for me until finding out, that the MPU (additionally to the MCU) must get the interrupt cleared by reading: readByte(MPU6050_ADDRESS, 0x3A); And this didn't work in the ISR itself, so I set a boolean "interrupted" and outside the ISR reacted on this an called the readByte. Also do it after MPU init.