text:
Mac Arduino IDE Connection to Min Seg (Mega 2560). No tty
I own a Macbook running OS X 10.10.3 (Yosemite)
I own a Min Seg.
My Min Seg model is built on an Arduino Mega 2560.
Problem
When I connect the board to the Macbook,
using either of the Macbook's two USB 2.0 ports,
using either of two USB A to B cables,
the board lights up, but I am unable to connect
to the tty device using the Arduino IDE.
Tools --> Port offered:
/dev/cu.Bluetooth-Incoming-Port
/dev/cu.Bluetooth-Modem
/dev/cu.usbmodem621 (Arduino Genuino Mega or Mega 2560)

I was expecting to also see:
/dev/tty.usbmodem621 (Arduino Genuino Mega or Mega 2560)
If I unplug the board, the third listed option
from Tools --> Port disappears, as expected.
Verification 1
I opened the System Information utility application.
USB --> USB Bus -->Arduino Mega:

  Product ID:    0x0042
  Vendor  ID:    0x2a03
  Version:       0.01
  Serial Number: 75435353038351316281
  Speed:         Up to 12 Mb/sec
  Manufacturer:  Arduino Srl
  Location ID:   0x06200000 / 3
  Current Available (mA): 500
  Current Required  (mA): 100

Verification 2
I used the Sparkfun Terminal Basics wiki to check for the device.
I used the Terminal utility application.
ls /dev/tty.* offered:
/dev/tty.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/tty.usbmodem621

screen /dev/tty.usbmodem621 9600 offered a successful connection.
[A white screen, which allowed for exit using Control+A followed by Control+/]
Attempted Solutions
I tried several means from here:
I installed the FTDI drivers.
I ran sudo nvram boot-args="kext-dev-mode=1" in the Terminal application.
Is an alternative driver worth attempting, such as that listed here?
I also attempted to connect through Mathworks Simulink.
When setting connection options, the program states
that a cu device is expected, rather than a tty.

Is it normal that the Arduino IDE picks up ONLY the cu devices and that the terminal picks up ONLY the tty devices?

What you are seeing is normal.
In BSD (which is the OS that Mac OS is based on) a serial port has two distinct devices for two distinct roles.
The tty, or TeleTYpe interface is used for incoming connections, be that from a modem, serial terminal, whatever. You would normally run a process called getty on it to present a login prompt.
The cu, or Call Unix interface is used for making outgoing connections to other devices. Traditionally that was mainly other Unix servers through modems. Nowadays it includes many other devices such as an Arduino.
The theory is that when you try and initiate an outgoing connection through the cu interface it first checks that no-one is connected in through the tty interface and if the serial port is available it disables the tty interface so the listening getty process doesn't interfere with your call. Also the tty and cu interfaces deal with the modem control lines differently.
The Arduino IDE is merely honouring that system by only offering you the outgoing device in the port list. As far as the Arduino communication is concerned there should be no difference.

Why does the Arduino Getting Started guide only suggest the tty interface?

@kando Because it is out of date and the person that wrote it didn't understand the difference.

Oh. Fair. They should fix that : j


text:
Connecting Indicator LEDs to Arduino Pro Mini
I'm new to electronics and unsure whether my design below will work as intended. XBee Series 2 and Arduino Pro Mini 5V are used. There are 4 LEDs, each with the following roles:

LED1: Flicker when transferring data to XBee
LED2: Flicker when transferring data to Arduino
LED3: Turns on when XBee is powered on
LED4: Turns on when Arduino is powered on

Also, will it suffice to use 3.3V LEDs for LED1, LED2, LED3 and 5V LEDs for LED4?

They will all fail to work. Consider fooling around with LEDs separate from a MCU first.

@IgnacioVazquez-Abrams Is it because I left out a resistor in series with the LEDs?

That's one of them. The other is that current doesn't flow that way through a diode.

Oops I need to flip them around

The new schematic looks fine now. You can use any led you want, but you have to calculate the correct resistor value for them, so they don't burn out. Or you can be lazy and just use a 1000 Ohm resistor; the led will be less bright, but as it's only used as an indicator that doesn't matter so much.

Note that the LEDs on the UART might not work how you desire them to, and that I have no idea what DIO9 does.

@Gerben I notice that there are no 5V surface mount LEDs (0603 or similar) on Digikey/Mouser, am I checking under the wrong categories?

@IgnacioVazquez-Abrams Looks like I should connect LED3 to pin 1 instead... I was hoping the UART LEDs will flicker like on the Arduino Uno

There's no such thing as a "5V LED". You take the Vf of the LED you have, and then you calculate the resistance required to drop the rest of the voltage with the desired current.

source: Stack Exchange

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

sort: votes


text:
Arduino Nano uploading gives error: avrdude: stk500_recv(): programmer is not responding
I have a Arduino Nano (Sainsmart) that I'm trying to upload a sketch to. Under the Arduino IDE, the device selected was Arduino Nano w/ ATmega328.
However uploading the sketch gives me the error
avrdude: stk500_recv(): programmer is not responding

I tried both USB ports (/dev/tty.usbserial & /dev/cu.usbserial) but the same error persist. The Arduino is connected to a Macbook Air via the USB cable, and the PWR LED indicator light on the Arduino is turned on and the L indicator LED blinks. There was no problem uploading to a Arduino Uno.
Retried after installing the latest FTDI drivers (MAC OSX, x64, v2.2.18, FTDIUSBSerialDriver_10_4_10_5_10_6_10_7.mpkg) from http://www.ftdichip.com/Drivers/VCP.htm. However that did not help.
What could have gone wrong?

This error message basically shows up for any communication problem, so by itself, it is not all that instructive. The Arduino Nano is supposed to have auto-reset, but maybe your clone does not? In that case, you'd have to press the reset key on the board just before starting an upload.

According to the device description Features: Automatic reset during program...

Yes, but according to the comments on the Amazon page, some people who bought this got yet another clone brand, so it seems to me that a healthy dose of skepticism about any claims in the documentation is in order, especially if they can easily be verified with an experiment.

I didn't read the comments but in that case you may be right.

While hitting reset at just the right time can work (it may take several tries), with Nano clones it's almost invariably the change in bootloader serial speed by the official Arduino.cc developers that's causing the problem. This answer is more likely to produce a reliable result: Tools → Processor → ATmega328P (Old Bootloader)

Know this is old but I ran onto it during my search for Nano(V3)'s not uploading so thought might help someone else.  Problem is the bootloader - Arduino IDE BUT I Found an easy solution (right under my nose).
I realized that my nano's had been uploading just fine then I had finally updated the Arduino AVR Boards from 1.6.20 to 1.6.21.  I didn't think there was any problems because it still showed my Nano and ATmega328 etc in the board manager after the change.
But the new boards manager has a new ATmega328 processor choice for the Nano. I changed processor: In the Arduino IDE select TOOLS > PROCESSOR > pulldown menu from ATmega328P to  "ATmega328P (Old Bootloader)".
Since then, I have uploaded many programs to several different Nano's V3 (Prolofic interace Chipset) without issue.

I was having the same problem and got the same error message.  Turns out these boards don't come with a bootloader preinstalled.  If you have some jumper wires and another working arduino you can use this tutorial to install the bootloader and it should work great, mine did at least! :)

Having a similar issue with my Sainsmart Nano.
Under Preferences check "Show verbose output during [x] upload, then when uploading, you should get a red trace like this:
avrdude: Version 5.11, compiled on Sep  2 2011 at 18:52:52
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/Users/johannes/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/tty.usbserial-A403MRTP
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]

You'll notice a little "pause" just before the first line of avrdude: Send: 0 [30]   [20]. Try uploading again and have you finger ready on the physical reset button of your Nano. Just the moment before the first avrdude: ... appears, press the reset button.
When you succeed, you'll see the screen filling with all sort of gibberish, and ending something like this after a few seconds:
[78] . [00] S [53] h [68] o [6f] u [75] l [6c] d [64]   [20] b [62] e [65]   [20] 0 [30] x [78] 4 [34] 9 [39] D [44] 4 [34] . [00] . [01] . [00] . [00] . [00] . [02] . [00] . [03] . [00] . [04] . [00] . [00] . [00] . [00] . [00] . [e6] . [06] . [b5] . [06] n [6e] . [06] w [77] . [06] . [8c] . [06] . [9d] . [06] . [00] . [00] . [00] . [00] . [02] . [0d] . [aa] . [0d] . [95] . [0c] . [c9] . [0c] . [a9] . [0c] . [f2] . [0c] . [00]
avrdude: Recv: . [10]
# | 100% 3.71s

avrdude: verifying ...
avrdude: 8824 bytes of flash verified
avrdude: Send: Q [51]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]

avrdude done.  Thank you.

This is to say that the Arduino (or knock-off) in question does not automatically reset before uploading and you have to manually do this by pressing the button.

Did you remember to tell the IDE that the board type is a Nano?
Tools -> Board => Arduino Nano ...
This gets me every time I swap between my Nano and Uno.

I also had that error message. I think there are many possible causes, so I haste to specify my special case.
I have a hackintosh with OS X Yosemite 10.10.2, Arduino software 1.0.6 and Funduino UNO. Uploading the example for Serial.write() succeeded the first time. Thereafter most uploads failed. Even when the upload succeeded the serial monitor would not always show output.
This seemed to me to be due to miscommunication on the USB port. I had to repeatedly reset the funduino, unplug and replug the USB cable or even restart the system. When replugging the USB cable sometimes my system would freeze.
By googling I found a solution to "Inserting USB device causes Mavericks 10.9.1 to freeze".
Answer no 12 on tonymacx86.com basically instructs you to remove GenericUSBXHCI.kext from /System/Library/Extensions.
I am happy to report that after removing this kext I have no problems uploading the example and monitoring the output. Because I don't need to replug the USB cable I don't know whether this solves my system freeze. I'm not even sure it was a system freeze, because my system may only have become unresponsive to my USB keyboard and mouse.

Had same issue and solution was as follows:

identified my arduino as CH340/ATmega168P (written on PCB)
went to IDE and picked from list not UNO but "Arduino Pro or Pro Mini"
when this option is selected new menu "Processor" selection is available (just under Board selection)
selected my processor ATmega168P there and upload worked like a charm!

The board selection does not depend on the USB interface chip, only on the processor and baud rate.

The Arduino IDE version 1.8.5 gave the same error every time I tried to connect it to my OSEPP Nano.  I tried with multiple nano boards with different versions of the IDE. I had the board set to "Arduino Nano".
The solution was: Instead of Nano choose Arduino/Genuino Uno. This worked for me.

Ok. I had the same programmer is not responding error on Arduino Nano on Atmel MEGA168PA, USB chip: CH340G. Macbook Pro under macOS 10.14.2.
It hand Blink example installed and the port wasn't visible in the list.
I was trying to figured out, whats wrong and connected my Arduino Due through the programming port. After 2 attempts the sketch was uploaded... Then I connected the Nano back, the port was visible this time (actually two of them: /dev/cu.wchusbserial14120 and /dev/cu.usbserial-14120) and guess what, the upload had been successful!
Magic!

Oh that downvoters don't want my experience to be shared.

If this doesn't work you will have to use spi to program the nano.  You'll need to look up the connection and use a uno since it has a serial chip at16u2 with a driver that recognizes all atmel products.  After connections setting uno as a programmer by flashing the uno as isp set the programmer as Arduino as isp and flash the chip.  Double check.  The benefit is it is less error prone than uart and has better timing but is a hassle to wire up.  Good Luck

all_licenses: 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/


text:
Nothng Written to Serial when using sprintf
I'm using sprintf to use a format specifier myTemplate with some strings. The result will then be written to Serial. Although the sketch compiles fine, it does not write any thing to the serial, nothing is seen in the Serial monitor.
Is sprintf being used wrongly here?
char* result;
char* myTemplate;

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

void loop() {
    myTemplate = "Welcome %s. You have slept %s times";
    sprintf(result, myTemplate, "Jane", "many");
    Serial.println(result);
    Serial.println("hello");

}

When I try the follwing sketch and write something to the Serial monitor, I receive gibberish echoed back to me!  Why is this?
Sketch
char received;
char* message = "";

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

void loop() {

    // Echos back
    if(Serial.available() > 0) {
        received = Serial.read();
        Serial.println(message);

        if(received == '\n') {
            message = "";
        }  else {
            message += received;
        }

    }
}

Where do you actually allocate any memory to result?

define 'gibberish'. Can you give some examples of what you are receiving? Have you got the monitor on 9600 as well? You realise you're Serial.printing message before you're allocating your read to it? And that at the end of the read there is possibly a new line which clears your message anyway, so it's never going to be seen

When you use sprintf(), you need to have some space allocated for it to write the result to. At the moment, you're just passing an uninitialised pointer (result), meaning the behaviour of sprintf() is undefined. It might appear to work under some circumstances, but not others (and even if it did seem to work, it could have some nasty side effects on other parts of your code).
The simplest approach is to allocate a static char buffer. You need to be sure it's big enough to contain all of the text you want it to store though (plus an extra null character at the end).
For example:
char* myTemplate = "";
char result[64] = {0};

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

void loop() {
    myTemplate = "Welcome %s. You have slept %s times";

    sprintf(result, myTemplate, "Jane", "many");
    Serial.println(result);
    Serial.println("hello");
}

As a side note, it's usually a good idea to initialise your variables. This is especially true for pointers.

Unfortunately it isn't quite always good to initialize them. Initializing them (or leaving them with the default value) will add prologue code to set/clear them even if the original value is never used; to prevent this declare the variable as being uninitialized, e.g. char *result __attribute__ ((section (".noinit")));. See the "Memory Sections" section of the AVR Libc documentation for details.

Thank you. When I try to empty out message using message="", I get the error in the (updated) question. Whats the proper way to clear a buffer?

@Nyxynyx: Why do you need to clear it?

@IgnacioVazquez-Abrams I updated the code in the question to show why I'm clearing it, thanks!

Oh boy... Unfortunately string handling in C is not quite as simple as you try to make it. Consider using string or String instead.

@IgnacioVazquez-Abrams It does work with String, but I'm reading lots of tips about how String is dynamically allocated and will encounter errors after some time.

Handling C strings is a bit out of scope for this site. Consider reading through C string questions on Stack Overflow for some insight on how they work.


text:
Help a noob, no idea on Programming, only started 2 days ago Help please
As said no programming skills only started 2 days ago when Nano arrived.
Heads in bits. This is how far i got. Any help much appreciated..
int EMagnetPin = 8;
int solenoidPin = 9;
int ReedPin = 13;

void setup()
{
  pinMode(EMagnetPin, OUTPUT);     // assign pin type
  pinMode(solenoidPin, OUTPUT);   // assign pin type
  pinMode(ReedPin, INPUT);        // assign pin type
  Serial.begin(9600);             //serial port open

void loop()
{
Serial.print(digitalRead(ReedPin));
if (digital REad(ReeddPin)==0 ) {
digitalWrite(solenoidPin,HIGH);

                  // Once magnet applied to Reed Switch Will activate the below

  digitalWrite(EMagnetPin, low);
  delay(11000);
  digitalWrite(EMagnetPin, HIGH);
  delay(500);
  digitalWrite(EMagnetPin, low);
  delay(500);
  digitalWrite(EMagnetPin, HIGH);
  delay(500);
  digitalWrite(EMagnetPin, low);
  delay(22500);
  digitalWrite(EMagnetPin, HIGH);
  delay(500);
  digitalWrite(EMagnetPin, low);
  delay(500);                          // Stops EMagnet
  digitalWrite(solenoidPin, HIGH);     //Start Solenoid
  delay(500);
  digitalWrite(solenoidPin, low);
  delay(500);
                    // Program Ends

Format your code properly by selecting all the code and press the {} icon on the editor menu. 2) What is exactly your question?

What error are you getting what is the exact thing you need can you explain your project idea also

I formatted your code (select it, Ctrl+K) and would have amended your subject line to be more meaningful but I have no idea what the problem is. What do you want it to do? What does it do?

Use uint8_t instead of int for the variables that will never have a value higher than 255. You'll save memory space by using the smallest variable type possible.

You didn't ask a question. What are you trying to do, and how is your project failing to accomplish that goal?

I presume you got some errors, like this:
/tmp/arduino_modified_sketch_836883/sketch_oct30a.ino: In function 'void setup()':
sketch_oct30a:13:3: error: a function-definition is not allowed here before '{' token
   {
   ^
sketch_oct30a:37:17: error: expected '}' at end of input
       delay(500);
                 ^
exit status 1
a function-definition is not allowed here before '{' token

You have to read those. At the end of a function you need a closing brace. So, setup for example would look like this:
void setup()
{
  pinMode(EMagnetPin, OUTPUT);     // assign pin type
  pinMode(solenoidPin, OUTPUT);   // assign pin type
  pinMode(ReedPin, INPUT);        // assign pin type
  Serial.begin(9600);             //serial port open
}   // <------- ADD THIS

Ditto for the end of the loop function.
The next problem is this line:
    if (digital REad(ReeddPin) == 0 ) {

The function "digitalRead" is spelt like that, not as two words. Also you misspelt "ReedPin" as "ReeddPin".
You have to go carefully through your code, look at the error messages, and fix them one by one. C++ is case-sensitive, you can't just thrown in extra spaces in the middle of words, and you have to be consistent with your variable names (ie. not misspell them).

I suggest you do a C++ tutorial, or find an Arduino tutorial. These are basic coding mistakes made by beginners. With a bit of practice, and some working through examples, you will stop making them.

Note that others already gave good answers; this is just a way to make your code more elegant.
This part:
  digitalWrite(EMagnetPin, low);
  delay(11000);
  digitalWrite(EMagnetPin, HIGH);
  delay(500);
  digitalWrite(EMagnetPin, low);
  delay(500);
  digitalWrite(EMagnetPin, HIGH);
  delay(500);
  digitalWrite(EMagnetPin, low);
  delay(22500);
  digitalWrite(EMagnetPin, HIGH);
  delay(500);
  digitalWrite(EMagnetPin, low);
  delay(500);                          // Stops EMagnet
  digitalWrite(solenoidPin, HIGH);     //Start Solenoid
  delay(500);
  digitalWrite(solenoidPin, low);
  delay(500);

You see there is a lot of duplication (digitalWrite plus delay).
The only things changing are the pin number, the pin state and the delay time (which is mostly 500).
You can create a new function for this, e.g. digitalWriteWithDelay:
void digitalWriteWithDelay(int pinNumber, int pinState, int delayTime = 500)
{
    digitalWrite(pinNumber, pinState);
    delay(delayTime);
}

Now you can rewrite
  digitalWrite(EMagnetPin, low);
  delay(11000);
  digitalWrite(EMagnetPin, HIGH);
  delay(500);

to
digitalWriteWithDelay(EMagneticPin, LOW, 11000);
digitalWriteWithDelay(EMagneticPin, HIGH);

and all subsequent lines similarly. Btw, it's best to use LOW and HIGH (keep the capitalization consequent). As you can see in the last line, 500 need not to be passed as it is the default value.

#include <Arduino.h>
int EMagnetPin = 8;
int solenoidPin = 9;
int ReedPin = 13;

void setup()
{
  pinMode(EMagnetPin, OUTPUT);  // assign pin type
  pinMode(solenoidPin, OUTPUT); // assign pin type
  pinMode(ReedPin, INPUT);      // assign pin type
  Serial.begin(9600);           //serial port open
}

void loop()
{
  Serial.print(digitalRead(ReedPin));
  if (digitalRead(ReedPin) == 0)//it is known as digitalRead
  {
    digitalWrite(solenoidPin, HIGH);

    // Once magnet applied to Reed Switch Will activate the below

    digitalWrite(EMagnetPin, LOW);
    delay(11000);
    digitalWrite(EMagnetPin, HIGH);
    delay(500);
    digitalWrite(EMagnetPin, LOW);
    delay(500);
    digitalWrite(EMagnetPin, HIGH);
    delay(500);
    digitalWrite(EMagnetPin, LOW);
    delay(22500);
    digitalWrite(EMagnetPin, HIGH);
    delay(500);
    digitalWrite(EMagnetPin, LOW);
    delay(500);                      // Stops EMagnet
    digitalWrite(solenoidPin, HIGH); //Start Solenoid
    delay(500);
    digitalWrite(solenoidPin, LOW);
    delay(500);
  }
}// please close all loops
// Program Ends

please remember to close all loops ,enter right spelling
I would suggest you to take a tutorial and also use a program like platformio or Arduino on vscode which will help you to write the code as it has auto code completion so you will always speel the right name for variables and also type the right function names.
Hope this helps.

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


text:
Arduino Readings Update Correctly on Windows but not Linux
I have written a simple script to get angle measurements from a magnetic sensor. The script works very well on Windows. However, when compiling the script on a Linux VirtualBox (Ubuntu 20.04), the sensor repeats the first angle reading and does not change from this, despite the angle changing. There are no errors/warnings given by Windows or Linux at any stage of compiling/uploading.
Uploading the script on Windows and then viewing in Linux serial monitor works. However, uploading it on Linux and then viewing in Windows serial monitor does not work ("Board is not available"), even when connecting the board to Linux and not Windows.
I've compared both systems and everything seems to be the same: the same Arduino Uno R3 board, Arduino IDE 1.8.19 on both systems, Arduino AVR Boards 1.8.3 on both, "Arduino Uno" selected as the board on both, the library is SimpleFOC v2.2.0 on both. The only difference I can see is that the Windows port is COM3, whereas the Linux port is /dev/ttyACM0.
My script is the following and I would appreciate any help or advice to get this working on Linux. Thank you.
#include <SimpleFOC.h>

#define PI 3.1415926535897932384626433832795

// Magnetic sensor instance
MagneticSensorSPI AS5x4x = MagneticSensorSPI(8, 14, 0x3FFF);

void setup() {
  // initialize magnetic sensor hardware
  AS5x4x.init();

  // use monitoring with serial
  Serial.begin(9600);

  Serial.println("Ready.");
  _delay(1000);
}

void loop() {
  Serial.println(AS5x4x.getAngle()); // display angle
}

Compile/upload under linux and then move the board to the windows system and open the serial monitor. And vice versa. Let us know if the behaviour follows from the system that it was compiled/uploaded from or the system that it is attached to. If it follows the system it was built/uploaded from, maybe provide version numbers to everything IDE, libraries, board core, etc.

Windows upload + Linux serial monitor works. Linux upload + Windows serial monitor does not work ("Board is not available"). Using Arduino 1.8.19 on both Windows and Ubuntu; Arduino Uno R3 board. Thanks for any further help/suggestions.

The "everything IDE, libraries, board core, etc"  Realistically, you liable to be the only person that can definitively answer this question. Whether or not you should is a different question. In either case, the information needed to answer it should be in the question when it it is answered. You're almost certainly going to find a difference in what you have installed.  But simply pointing that out alone is not a useful answer. The "board core" I mentioned is the version that lists in your Boards Manager for whatever board you're using.

Ok, I've compared both systems but everything seems to be the same... Arduino IDE 1.8.19 on both systems, Arduino AVR Boards 1.8.3 on both, the library is SimpleFOC v2.2.0 on both. Let me know if you've any other suggestions, thanks again for help.

Please compare the selected Arduino board, too. Did the compile and upload work without error on Linux? Did Linux upload and Linux serial monitor work, before you connect the Arduino to Windows? Please add these important information to your question by [edit]ing it, do not post a comment. I suggest to take the [tour] to learn how this site works. It is not a forum.

Ok, I've edited and updated the original question with these details. Would appreciate any help or suggestions you can provide.

It turns out that the Arduino Library Manager was giving me incorrect information about the library version installed. By removing the library it was using and then installing the correct library that corresponds to the required version number, the code now works well.


text:
I'm having some undefined references and can't figure out why
Try verifying the code to see the errors.  This is on a arduino nano with a 328 processor.  I put the necessary library in the code.
Pastebin for code
 #ifndef Pushbutton_h
#define Pushbutton_h

#include <Arduino.h>

#define PULL_UP_DISABLED    0
#define PULL_UP_ENABLED     1

#define DEFAULT_STATE_LOW   0
#define DEFAULT_STATE_HIGH  1

/*! \brief The pin used for the button on the
 * [Zumo Shield for Arduino](http://www.pololu.com/product/2504).
 *
 * This does not really belong here in this general pushbutton library and will
 * probably be removed in the future. */
#define ZUMO_BUTTON 12

class PushbuttonStateMachine
{
public:
  PushbuttonStateMachine();
  bool getSingleDebouncedRisingEdge(bool value);
private:
  uint8_t state;
  uint16_t prevTimeMillis;
};

class PushbuttonBase
{
public:

  PushbuttonBase();

  // wait for button to be pressed, released, or pressed and released
  void waitForPress();
  void waitForRelease();
  void waitForButton();

  // more complex functions that return true once for each button transition
  // from released to pressed or pressed to released
  bool getSingleDebouncedPress();
  bool getSingleDebouncedRelease();

  // indicates whether button is currently pressed
  bool isPressed();

  // Initializes I/O pin for use as button input.
  // This gets called automatically so normally you will not need to call this,
  // but it might be useful if the pin for the button is in the wrong state.
  virtual void init2() = 0;

protected:

  virtual bool _isPressed() = 0;

private:

  PushbuttonStateMachine pressState;
  PushbuttonStateMachine releaseState;
  bool initialized;

  // TODO: move all this init stuff down into Pushbutton
  inline void init()
  {
    if (!initialized)
    {
      initialized = true;
      init2();
    }
  }
};

/* \class Pushbutton Pushbutton.h
 * \brief Interface with pushbuttons on dedicated pins.
 *
 */
class Pushbutton : public PushbuttonBase
{
public:

  // constructor; takes arguments specifying whether to enable internal pull-up
  // and the default state of the pin that the button is connected to
  Pushbutton(uint8_t pin, uint8_t pullUp = PULL_UP_ENABLED,
      uint8_t defaultState = DEFAULT_STATE_HIGH);

  virtual void init2();

protected:

  virtual bool _isPressed();

private:

   uint8_t _pin;
   bool _pullUp;
   bool _defaultState;
 };

 #endif

// PIN Configurations #define SEARCH_SPEED 255

#define echoPin A0
#define triggerPin 3
#define rightBackMotor 4
#define rightMotorSpeed 10
#define leftMotorSpeed 9
#define leftForwardMotor 7  //if a motor goes backward swap the number on the FwdPin and BckPin
#define rightForwardMotor 8   //if a motor goes backward swap the number on the FwdPin and BckPin
#define leftBackMotor 11
#define LED 13
#define leftSensor A1
#define rightSensor A2
#define IRdriver 6

// Robot Configuration Parameters
// Speed range is -255 -> 255
#define MAX_SPEED 255
#define QTR_Threshold 500
#define ATTACK_DISTANCE 25
#define BACKUP_DISTANCE 4000
#define SEARCH_SPEED 255

// State variables
bool isBackup = false;
int backupTimer = 0;
long distance = 1000;
Pushbutton button(ZUMO_BUTTON);

void setSpeed(int speed, int motor);

void setup() {
   Serial.begin(9600);
   Serial.println("Setup.");

  pinSetup();

   Serial.println("Waiting for button");
}

void loop() {
   digitalWrite(IRdriver, HIGH);

  if (button.isPressed()) {
    // if button is pressed, stop and wait for another press to go again
    button.waitForRelease();
    waitForButtonAndCountDown();
 }

  int leftInput = analogRead(leftSensor);
  int rightInput = analogRead(rightSensor);

  if ( isBackup ) {
    backupTimer = backupTimer + 1;
    setSpeed(-MAX_SPEED, 0);
    setSpeed(-MAX_SPEED + 20, 1);
    if (backupTimer >= BACKUP_DISTANCE ) {
      isBackup = false;
      backupTimer = 0;
    }
  } else {
    if ( leftInput <= 500 || rightInput <= 500 ) { // WHITE LINE ABORT!
      //Serial.println("Abort! - "); Serial.println(leftInput); Serial.println(rightInput);
      isBackup = true;
      setSpeed(-MAX_SPEED, 0);
      setSpeed(-MAX_SPEED, 1);
    } else {
      distance = getDistance();
      if ( distance <= ATTACK_DISTANCE ) { // ATTACK!
        Serial.println("Attack!");
        setSpeed(MAX_SPEED, 0);
        setSpeed(MAX_SPEED, 1);
      } else { // search
        // TODO(erh): implement other searching algorithms
        Serial.println("Search");
        setSpeed(SEARCH_SPEED, 0);
        setSpeed(-SEARCH_SPEED, 1);
      }
    }
  }
}

void pinSetup() {
  // motors!
  pinMode(leftMotorSpeed, OUTPUT);
  pinMode(rightMotorSpeed, OUTPUT);
  pinMode(leftForwardMotor, OUTPUT);
  pinMode(leftBackMotor, OUTPUT);
  pinMode(rightForwardMotor, OUTPUT);
  pinMode(rightBackMotor, OUTPUT);

   // sonar sensor
  pinMode(LED, HIGH);
  pinMode(triggerPin, OUTPUT);
  pinMode(echoPin, INPUT);

  // qtr light sensor
  pinMode(leftSensor, INPUT);
  pinMode(rightSensor, INPUT);
  pinMode(IRdriver, OUTPUT);
}

void setSpeed(int speed, int motor = 0) {
  int speedPin, forwardPin, backPin;
  if ( motor == 0 ) {
    speedPin = leftMotorSpeed;
    forwardPin = leftForwardMotor;
    backPin = leftBackMotor;
  } else if ( motor == 1 ) {
    speedPin = rightMotorSpeed;
    forwardPin = rightForwardMotor;
    backPin = rightBackMotor;
  }

  if ( speed == 0 ) {
    analogWrite(speedPin, 0);
    digitalWrite(forwardPin, LOW);
    digitalWrite(backPin, LOW);
  } else if ( speed > 0 ) {
    digitalWrite(forwardPin, HIGH);
    digitalWrite(backPin, LOW);
    analogWrite(speedPin, speed);
  } else if ( speed < 0 ) {
    digitalWrite(forwardPin, LOW);
    digitalWrite(backPin, HIGH);
    analogWrite(speedPin, abs(speed));
  }
}

long getDistance() {
  long duration, distance;
  digitalWrite(triggerPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(triggerPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  return distance;
}

void waitForButtonAndCountDown() {
  digitalWrite(LED, HIGH);
  button.waitForButton();
  digitalWrite(LED, LOW);

  for (int i = 0; i < 3; i++ ) {
    Serial.println(i);
    delay(1000);
  }

  delay(1000);
  Serial.println("ATTACK!");
  delay(1000);
}

Could you put the error (and code) in this question?

Your code contains only the header declarations (.h file) for those classes. There should also be another file (probably .cpp) that actually implements the code for the classes.
What you pasted looks very similar to the Pushbutton stuff in this project on GitHub.
You can look at their Pushbutton.h and Pushbutton.cpp files to get an idea of what I mean. In fact, you might be able to use those files instead of what you have. I can verify that it does compile, but not whether it works or not.

It is the github stuff but I'm new to arduino. Can I take the .cpp file and copy paste the code in because I'm using school computers without much control.

Ideally you would download the files (e.g. with the "Raw" link when viewing the files) and use them as a library. But yes I think it should also work if you just copy/paste the contents into your project. Just make sure the .h code is above the .cpp code. I had done that and it compiled okay.

Could you possibly upload your code because I tried to copy paste but I keep getting previous definition of 'class PushbuttonStateMachine'

I don't have any code saved. I just copied your Pastebin code, deleted the old header stuff (everything between #ifndef Pushbutton_h and #endif) and pasted in those other two files instead.

The error Undefined reference is a linker error, which means that the Arduino ecosystem is missing some of the pieces for the build. If you have indeed provided PushButton.cpp - whether in a library or not - you need to put a #include of Pushbutton.h inside the .ino file. This tells Arduino that you want to include PushButton's code as well as everything else.
If Pushbutton.cpp is inside the same directory as the .ino file then that will "just work". If it's elsewhere, you need to tell Arduino.


text:
What SMS can send to switch LED?
I have code but I don't know how to send SMS from my Mobile
I mean what the message I can send to switch the Led?
To switch On or Off.
I use SIm900
and use this code
#include <SoftwareSerial.h>

 char inchar; // Will hold the incoming character from the GSM shield
 SoftwareSerial SIM900(7, 8);

 int led = 10;

 void setup()
 {
   Serial.begin(19200);
   // set up the digital pins to control
   pinMode(led, OUTPUT);
   digitalWrite(led, LOW);

   // wake up the GSM shield
   SIM900.begin(19200);
   delay(20000); // give time to log on to network.
   SIM900.print("AT+CMGF=1\r"); // set SMS mode to text
   delay(100);
   SIM900.print("AT+CNMI=2,2,0,0,0\r");
   // blurt out contents of new SMS upon receipt to the GSM shield's serial out
   delay(100);
   Serial.println("Ready...");
 }

 void loop()
 {
   //If a character comes in from the cellular module...
   if(SIM900.available() >0)
   {
     inchar=SIM900.read();
     if (inchar=='#')
     {
       delay(10);

       inchar=SIM900.read();
       if (inchar=='a')
       {
         delay(10);
         inchar=SIM900.read();
         if (inchar=='0')
         {
           digitalWrite(led, LOW);
         }
         else if (inchar=='1')
         {
           digitalWrite(led, HIGH);
         }
         delay(10);
         // SIM900.println("AT+CMGD=1,4"); // delete all SMS
       }
     }
   }
 }

The code appears to be looking for an SMS that says #a0 or #a1. The logic doesn't look very robust, though. It reads a character, then waits 10ms and tries to read another. What does SIM900.read() do if there is no next character? Will it return something? Or wait until there is another? If it waits, the code can get out of sync with incoming, badly-formed commands.


text:
Does SMS format depend on the sender's mobile?
I want to read the SMS using Arduino and GSM module, I want to perform conditional programming based on the received SMS.
What I found really interesting is SMS format is different if I send message from different phones.
Output of my code is
Case 1:(From a smartphone)
Mobile Number is: +91954xxxxxxx
Message Text: 5+22" Hello Arduino
Case 2:(From a normal phone)
Mobile Number is: +91984yyyyyyy
Message Text: Hello Arduino

Does it really depend on the sender's mobile phone? If yes, how to move further to make my code independent on the sender mobile.

My code is
//===final code

char RcvdMsg[200] = "";
int RcvdCheck = 0;
int RcvdConf = 0;
int index = 0;
int RcvdEnd = 0;
char MsgMob[15];
char MsgTxt[50];
int MsgLength = 0;

void Config() // This function is configuring our SIM900 module i.e. sending the initial AT commands
{
   delay(1000);
   Serial.print("ATE0\r");
   Response();
   Serial.print("AT\r");
   Response();
   Serial.print("AT+CMGF=1\r");
   Response();
   Serial.print("AT+CNMI=1,2,0,0,0\r");
   Response();
}

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

void loop()
{
   RecSMS();
}

void Response() // Get the Response of each AT Command
{
   int count = 0;
   Serial.println();
   while(1)
   {
      if(Serial.available())
      {
         char data =Serial.read();
         if(data == 'K'){Serial.println("OK");break;}
         if(data == 'R'){Serial.println("GSM Not Working");break;}
      }
      count++;
      delay(10);
      if(count == 1000){Serial.println("GSM not Found");break;}

   }
}

void RecSMS() // Receiving the SMS and extracting the Sender Mobile number & Message Text
{
   if(Serial.available())
   {
      char data = Serial.read();
      if(data == '+'){RcvdCheck = 1;}
      if((data == 'C') && (RcvdCheck == 1)){RcvdCheck = 2;}
      if((data == 'M') && (RcvdCheck == 2)){RcvdCheck = 3;}
      if((data == 'T') && (RcvdCheck == 3)){RcvdCheck = 4;}
      if(RcvdCheck == 4){RcvdConf = 1; RcvdCheck = 0;}

      if(RcvdConf == 1)
      {
         if(data == '\n'){RcvdEnd++;}
         if(RcvdEnd == 3){RcvdEnd = 0;}
         RcvdMsg[index] = data;

         index++;
         if(RcvdEnd == 2){RcvdConf = 0;MsgLength = index-2;index = 0;}
         if(RcvdConf == 0)
         {
            Serial.print("Mobile Number is: ");
            for(int x = 4;x < 17;x++)
            {
               MsgMob[x-4] = RcvdMsg[x];
               Serial.print(MsgMob[x-4]);
            }
            Serial.println();
            Serial.print("Message Text: ");
            for(int x = 46; x < MsgLength; x++)
            {
               MsgTxt[x-46] = RcvdMsg[x];
               Serial.print(MsgTxt[x-46]);
            }

            Serial.println();

            //****Resetting all the variables*****//

            //RcvdMsg[200]={0};
            RcvdCheck = 0;
            RcvdConf = 0;
            index = 0;
            RcvdEnd = 0;
            MsgMob[15];
            MsgTxt[50];
            MsgLength = 0;

            Serial.flush();

         }
      }
   }
}

If you're not trying to capture the mobile number or whatever SMS text was sent, but only react to specific SMS messages, then don't try to parse the whole message, but design the protocol between any arbitrary phone and your Arduino to be detectable independent of everything else, e.g.:
#L 5 on        ; set an LED state

#M 3 137       ; set a motor speed


text:
how to multi merge code
i do have sketch from various people out there who have build nice code to do what i need done BUT not for my application and well they grant us permission to use and or modify their code so this is what i attempt to do with your help.

I'm afraid there is no general recipe for combining code snippets. Also, you should avoid adding more questions in the comments. Please feel free to ask separate questions if you have concrete things to ask about.

Unfortunately there is no easy way to do this. All you can hope to do if you see multiple sketches, which if combined would achieve your desired goal, is to splice the code into a single sketch (by copying and pasting), and hope that there are no conflicts resulting from the merging of the different sets of code.
For simple things like two sketches using the same pins, you may be able to fix that by changing which pins are used (unless they are special purpose pins such as PWM or hardware interrupts).
For harder to diagnose problems like two libraries not working if used the same sketch, that is almost impossible to resolve unless you know the hardware or library well enough. Best option there is to find another that does the same job, but differently.


text:
Which sensor is best for obstacle detecting with retroreflector?
Distance is about 3m. IR or visible light - does not matter.
It is possible that object/obstacle can be shiny, so for correct detection necessary large amount of reflected light.
Maybe for this task better to use specific retroreflector?
UPDATE:
there will be two sensors with distance about 3-4 cm between.
Object must cross 1st sensor's reflector but do not cross the 2nd one.
The scheme of this sensor should be this:

But the use will be this:

If you use a laser and mirror, you probably only need a simple photo-transistor  (of approximately the same wavelength as the laser). Shiny object have to be precisely aligned to reflect as much light as a mirror does, so it's hard to not be detected.

@Gerben OK, I will update the task. I don't believe that sonar is capable for desired distance and accuracy.

@Gerben There is possibility that the light of the surrounding will affect on result.

Lasers are nice for this, they are bundled quite well. You could use a sonar/ping/ultrasonic sensor for this. But they might interfere with eachother if they're too close. And yes, lasers don't do very well on shiny objects if set up like this.

I think the question is worded to get a specific answer; I do not know if this is the answer you want. I'll give you that answer first:
I'd say an infrared LED, and an infrared detector.
Strobe the LED, then measure the difference between when it's (known to be) on, and when it's (known to be) off, to compensate for ambient light.
However, if I was doing this, I'd consider an ultrasound sensor - no retroreflector needed; instead you get the distance to the (obstacle or reflector).

Reflector does not require any power and can work at quite large distance. I have updated the scheme - it is not possible to use ultrasound sensor

I think you're better off with a set-up like this.
A shiny object might bounce the laser as if it were a mirror.
But we wan't to know if the laser was interrupted.
So. If we place the sensor on the other side, we can accurately say if the light reaches the sensor. Thus if there is an object between (shiny or not).
But what if another light-source shines into my sensor? It'll think that there is no object.
We can encapsulate the sensor, so that only light from the direction of the laser can shine into it. And we can filter out other light "colors".
Also the strength of the laser should be bigger as any other ambien light (not too strong also). You could even choose to make the laser pulse a specific pattern and let the sensor check if it's right.

What is the length of sensor "vision" and how narrow is the sonar? Distance between two sensors should be about 5-6 cm (maximum -10).

@XuMuK what you man by length of sensor "vision" the sensor can see the light source, as long as the light source is bright/strong enough. It's hard to pre-calculate this, just get one of which you think is strong enough to make a difference (against ambient light).

@XuMuK regarding the "narrowness" of a sonar, it'll be different for each part, you should check the datasheet of the specific part. Or choose one which fits your needs.


text:
Graphic fail when rebooting the micro controller and OLED! (NOT when uploading the code??!!)
Im using Spark fun´s Pro micro: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro
And Digole OLED 1.8" hooked up with UART: http://www.digole.com/index.php?productID=859
As the head line reads, got code that work just fine when I upload it to the Pro Micro. But when I restart the pro micro (after successful upload it starts to show these weird characters and tokens. I can still se the "working code" but with a lot of additional crap?!
EDIT: This is installed in a car, and I´ve notice its just screwing around when I turn the car ON.. The cars electric is probably somehow interfering with the data-signal to the oled. Maybe I need a resistor of some kind?
What is this, why is it happening, and what can I do to get rid of the problem?!?
Help´s very appreciated!! Thanks!! /Rasmus

Try adding a 1000ms delay to the start of your code before you do any serial work.

@Majenko, ok will try that today! I´ll be back with the result! Thanks!

Tried with a delay but the problem´s still there.. Thanks anyway for the suggestion @Majenko

It would have been nice to know the rather important fact you just now mention in your edit... running from a car and it only happens when you start the engine...  Starting the engine is very noisy. You need lots of filtering to get rid of the massive spikes, and lots of capacitance to absorb the deep brownouts you get.

@Majenko, Yeah, and not only during startup, of course also during idle and driving. Do you know what I could use?

This may help you: http://electronics.stackexchange.com/a/73921/4245


text:
What are the basic steps to make a printed circuit board?
I created a shield for Arduino on a soldering board. The next step shall be to implement the circuit on a PCB. I'm new to this, so I'd like to know what the basic steps in designing a PCB are.
More specifically,

What software do I use for this? Is free software sufficient, or do I get substantially more value from a commercial package?
Can I have a single PCB printed by a commercial provider, or are there minimum quantities? What is the approximate cost for a shield-sized PCB in a small quantity - is it in the tens, or rather in the hundreds of bucks?

Of course, any pointers to good tutorials on the Web will be appreciated,  too!

Software packages are, amongst others

Fritzing (more target at beginners)
Eagle (free for board of size 100 x 80 mm (4 x 3.2 inches)).
KiCad (open source)

Companies that make you pcb in small quantities are e.g.

OSHPark
seeedstudio
Dirt Cheap Dirty Boards

I personally create my own double layer PCBs at home. I first started with the toner-transfer method, but now use photo lithography. I etch in Hydrochloric acid and hydrogen-peroxide. I can have a finished board in 1-2 hours, instead of having to wait a week or so. Great learning experience.

What software do I use for this? Is free software sufficient, or do I get substantially more value from a commercial package?

There are plenty of good free ones, or free versions of commercial ones. Use the one that best suits your way of working - they are all different, try some out and find out which you like best.  I use a free one for all my work (but then I am a FOSS junkie).

Can I have a single PCB printed by a commercial provider, or are there minimum quantities? What is the approximate cost for a shield-sized PCB in a small quantity - is it in the tens, or rather in the hundreds of bucks?

Generally, no.  It'd be just too costly.  There are small quantity houses around though, and I often use iTead for my prototyping, since they will do batches of just 10 boards at a reasonable cost.
The basic steps in designing a PCB though are:

Design it as a schematic
Lay it out as a PCB design
Get a prototype made
Build it
Correct the mistakes
Go back to 3

If you only want one circuit and it is a pretty simple one you might want to give making the PCB yourself a go - it's quite rewarding and if nothing else gives you good insights into PCB design requirements and how best to lay out a PCB and the tracks for a good reliable etch.  If you have a laser printer the Toner Transfer method of home PCB production is good.

it seems that your toner transfer link above is broken.


text:
Sending sensor readings from Arduino to Raspberry Pi over 433 MHz
I'm building a garden monitor, so I got myself an Arduino Nano, a soil humidity sensor, an air humidity and temperature sensor as well as a luminosity sensor. Since I had not one but two Raspberry Pis laying around I thought I'll handle the receiving end with one of them. I also got a 433 MHz RF kit.
The trail of the information will look like this: Sensor(s) -> Arduino -> 433 MHz Transmitter - - - 433 MHz - - - 433 MHz Receiver -> Raspberry Pi
Now my question is, what libraries should I use? I checked rc-switch (it has libs for both Arduino as well as RPi) and managed to send some codes but it seems that I'll need to write my own protocol to use this to transmit even simple data as it wasn't developed for sending data, rather simple switch on / switch off signals to simulate remotes.
VirtualWire would seem as the ideal candidate but the problem is it doesn't have an RPi equivalent.
Any suggestions?

You could look into the RadioHead library - there might be a port for RPi, though I couldn't find one with a (very) quick google. This library works well, I use it actually with RFM69H 433 MHz radios (from Moteinos), a little more expensive than the simple 433 kits, but also supports encryption which might be important down the line. If you can't find a good library for RPi one solution could be to have a second Arduino acting as a receiver and sending data serially to RPi. This is what I use with a regular desktop PC which is my home server.
I also found a discussion about connecting a RFM69 to the RPi here which might give you more information about the process in general, even if you won't use the same radio.

Presuming you want to get results quickly, I recommend you have a look at openHab This is a Java based home automation framework and server that has plugins for many existing protocols.
Once you get your protocol running it is just a matter of plugging it into openHab for charting and storage. I use for inside home measurements:

Also this post will help you further with connect 433 to RasPi and Arduino.
Specifically for temp and humidity sensors there is the reverse engineered Cresta protocol, that is also used in a lot of commercial sensors. See this Github repo for Arduino code. Also findable for Raspberry Pi.

The sensors I mentioned are for Arduino. So the link would look like this: Sensor(s) -> Arduino -> 433 MHz Transmitter - - - 433 Mhz - - - 433 MHz Receiver -> Raspberry Pi. I edited my question to include this information.

I am fairly new to Arduino but have had a basic experience with python on RPi (Model 2). I am trying to connect ultrasonic sensors (for distance measuring) on Arduino  and then send (RF transmission) the value to Raspberry Pi. I am not able to figure out how to write a code for receiving the transmitted code. I have to receive the code, decode it and then update it in my SQLITE database (on the same RPi).
I have already tried RFSniffer but I am unable to receive value other than "INT". RPi shows nothing if I send any "CHAR" or "STRING".
Please do suggest me how should I proceed.
Thanks in advance
Pradeep Verma


text:
Help Understanding FFT Analysis and analogRead()?
Here's the deal, I'm attempting to learn how to use an FFT (Fast Fourier Transformation) Library for sound analysis (link is here). My issue is that this comes with included C++ code to show users how to use the FFT library. There are three examples, but I'll show this one because it's closest to the application I have planned for it:
/*
fft_adc_serial.pde
guest openmusiclabs.com 7.7.14
example sketch for testing the fft library.
it takes in data on ADC0 (Analog0) and processes them
with the fft. the data is sent out over the serial
port at 115.2kb.
*/

#define LOG_OUT 1 // use the log output function
#define FFT_N 256 // set to 256 point fft

#include <FFT.h> // include the library

void setup() {
  Serial.begin(115200); // use the serial port
  TIMSK0 = 0; // turn off timer0 for lower jitter
  ADCSRA = 0xe5; // set the adc to free running mode
  ADMUX = 0x40; // use adc0
  DIDR0 = 0x01; // turn off the digital input for adc0
}

void loop() {
  while(1) { // reduces jitter
    cli();  // UDRE interrupt slows this way down on arduino1.0
    for (int i = 0 ; i < 512 ; i += 2) { // save 256 samples
      while(!(ADCSRA & 0x10)); // wait for adc to be ready
      ADCSRA = 0xf5; // restart adc
      byte m = ADCL; // fetch adc data
      byte j = ADCH;
      int k = (j << 8) | m; // form into an int
      k -= 0x0200; // form into a signed int
      k <<= 6; // form into a 16b signed int
      fft_input[i] = k; // put real data into even bins
      fft_input[i+1] = 0; // set odd bins to 0
     }
    fft_window(); // window the data for better frequency response
    fft_reorder(); // reorder the data before doing the fft
    fft_run(); // process the data in the fft
    fft_mag_log(); // take the output of the fft
    sei();
    Serial.println("start");
    for (byte i = 0 ; i < FFT_N/2 ; i++) {
      Serial.println(fft_log_out[i]); // send out the data
    }
  }
}

Now, with that said, I have a very general grasp of the idea that those lines referencing some variable called ADMUX and ADCSRA have to do with the analogRead() method and that the ADCH and ADCL refer to another two components that are combined to provide the returned integer that analogRead() spits out. What I don't understand whatsoever are those seemingly random strings of characters that these are being set equal to. For example, what does 0x40 or 0x01 or 0xe5 even refer to in the setup() method (if nothing else maybe somebody could point me in the right direction for this, because that part I really am entirely clueless about). And furthermore, why manipulate these directly in the first place, because if you reference the source code for analogRead() they look awfully similar. Thanks for any help in advance!

All is explained in Chap. 24 http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet_complete.pdf,

The register-level manipulations are trying to optimize the sampling rate to be faster than you get out of analogRead() sampling rate.

The random values in ADMUX differ, depending on the chip, but it can choose the pin, internal sensors, reference voltage, etc... What they really mean depends on the datasheet.

It would have been preferable if the author of that code had used proper bit masks. For example:
  ADCSRA = 0xe5; // set the adc to free running mode

Looking at the datasheet:

Now, 0xe5 is 11100101 in binary.
So that line could have been written:
  ADCSRA = bit (ADEN) | bit (ADSC) | bit (ADATE) | bit (ADPS2) | bit (ADPS0);

The last two (ADPS2 and ADPS0) give the prescaler (of 32):

The other bits are explained in the datasheet:

Bit 7 – ADEN: ADC Enable
Writing this bit to one enables the ADC. By writing it to zero, the ADC is turned off. Turning the ADC off while a
conversion is in progress, will terminate this conversion.
Bit 6 – ADSC: ADC Start Conversion
In Single Conversion mode, write this bit to one to start each conversion. In Free Running mode, write this bit to
one to start the first conversion. The first conversion after ADSC has been written after the ADC has been
enabled, or if ADSC is written at the same time as the ADC is enabled, will take 25 ADC clock cycles instead of
the normal 13. This first conversion performs initialization of the ADC.
ADSC will read as one as long as a conversion is in progress. When the conversion is complete, it returns to
zero. Writing zero to this bit has no effect.
Bit 5 – ADATE: ADC Auto Trigger Enable
When this bit is written to one, Auto Triggering of the ADC is enabled. The ADC will start a conversion on a
positive edge of the selected trigger signal. The trigger source is selected by setting the ADC Trigger Select bits,
ADTS in ADCSRB.

You can work through the other registers in a similar way.

Nick Gammon already gave a very fine answer about the meaning of the
mysterious numbers you were wondering about. Here I am trying to answer
only your last question:

why manipulate these directly in the first place, because if you
  reference the source code for analogRead() they look awfully similar.

One of the reasons is, as Dave X said in a comment, to get a higher
sample rate. Assuming this is an Arduino Uno or similar (ATmega328P @
16 MHz), the Arduino core normally configures the ADC prescaler to 128.
This gives a conversion time of 104 µs (equal to 13 × prescaler ÷
F_CPU), and a maximum sample rate of about 9.6 kHz. This is fine for
telephone quality audio, but insufficient for hi-fi applications. This
example code sets the prescaler to 32 for a conversion time of 26 µs and
a maximum sample rate around 38 kHz. According to Atmel, the ADC should
work fine with this kind of sample rate, except that you should not
expect to get the full resolution.
The main reason, however, is not to get a fast sample rate, but rather
to get a consistent sample rate. The problem with analogRead() is
that it is a blocking function. If you look at its source code you
will see a busy wait like this:
// ADSC is cleared when the conversion finishes
while (bit_is_set(ADCSRA, ADSC));

This means that the CPU is not doing anything useful while waiting for
the ADC to finish the conversion. If you do analogRead() in a loop,
the CPU will wait for the ADC, then the ADC will be idle while the CPU
completes the loop and so on. The conversion period is then the time
required by the ADC plus the time taken by the CPU to loop. And the
CPU time is hard to predict because it can be influenced by interrupts
and by conditional branches inside the loop.
This code, in contrast, configures the ADC to work in free running
mode. In this mode, the ADC starts a new conversion as soon as the
previous one is done. This way you get a steady sample rate while the
ADC and the CPU work in parallel. In the loop you see these lines:
while(!(ADCSRA & 0x10)); // wait for adc to be ready
ADCSRA = 0xf5; // restart adc

The comments are a bit misleading. The first line (which I would rather
write loop_until_bit_is_set(ADCSRA, ADIF);) waits for a flags that is
set when the current conversion is done and the data register updated.
The next line does not restart the ADC (it restarted itself, as it is in
free running mode): it only clears the flag so that it can be
meaningfully tested on the next iteration.
Now, I have a few comments on this code that are not directly related to
your question, but may be useful if you are going to build your program
on this basis.
First, it should be noticed that the whole ADC-reading loop is done with
interrupts disabled. This is not normally needed, as the free running
mode gives you a steady sampling even if the CPU timing is somewhat
jittery. The only valid reason I see for disabling interrupts is if
one of your ISRs takes so long to execute that you may miss one sample.
This could very well be the case with such a high sampling frequency.
But still, there is no point in keeping the interrupts disabled during
the FFT processing. And there is no point in turning off Timer 0 if you
are disabling interrupts anyway.
My second point is about the three lines starting with byte m = ADCL;.
Those are meant to read the ADC data register in the proper order: low
byte first. However, the C compiler is well aware of the proper way to
do read a 16-bit I/O register (see “Accessing 16-bit Registers” in the
datasheet chapter about Timer 1). Thus, these three lines can be
simplified to just int k = ADC;.
My last point is that having the CPU left adjust the result (k <<= 6)
takes some time, as it is implemented as a loop. There is no point in
doing this when the ADC can do it for free: you just have to set the
ADLAR bit when configuring ADMUX in setup(). Then the 5 lines starting
with byte m = ADCL; would be reduced to
int k = ADC - 0x8000;  // ADC reading as a 16 bit signed int

An excellent answer from Edgar Bonet. My reply described how to interpret the bit patterns. This reply goes into a lot more detail about the meaning of them.

authors: إبراهيم السمطي


text:
Circumventing overflow error by pushing data into computer?
It seems in certain applications, for example signal processing, Arduino and other micro-controllers in general run into the overflow error when they're trying to store even moderate amounts of data. It would seem the obvious answer would be to simply take this data, push it onto the computer, and deal with it there instead, where you have much more available computing power. Is this possible with Arduino, or am I missing something that makes it not feasible?

You're missing a reasonable definition of "push".

Sure, if you have a better computer at hand, and a communication channel that can keep up with the data rate, it can indeed be a good idea to hand it off unprocessed.  Or processed just enough to reduce the data rate to what the communication channel can handle.

In theory yes. In practice, depends on your requirements and implementation.

A good example video: https://www.youtube.com/watch?v=ruuxn2u3yao (he's using an Teensy LC rather than an Arduino, but yeah, it's a microcontroller).

One of the "features" of most microcontrollers/microprocessors is that they don't have a whole heap of RAM - this keeps costs down, and lets the manufacturers keep everything on one chip (unlike your PC).
However to "push" data to somewhere that can process it, you need to have a fast communications channel. SPI is quite fast, but you don't generally talk to PCs using SPI. Serial communication is slower, but if it gets converted into a USB interface (such as on a Uno) you can get respectable speeds talking to a PC. Something like 115200 baud is usually reliable, which lets you transmit 11520 bytes per second.
However it depends on what you want to send (ie. how many bytes), how you are going to indicate where one piece of data ends and the next one starts, maybe allow for error detection or correction, and so on.
Say, for example, it takes 5 bytes to send one piece of data (eg. 4 digits plus a delimiter). Now you are down to 11520/5 = 2304 pieces of data per second.
This may or may not be adequate for whatever-it-is you are trying to do.

I'm wondering if the Arduino's with built-in USB (Atmega32u4?) would be faster than "Uart". Polulu claims: Native full-speed USB (12 Mbps), which is quite fast.

Possibly, although I got my Uno to run the ASCII table sketch at 230400 baud. That's only 43.4 µs per byte, and you would probably have trouble acquiring data much faster than that. For example, anything requiring an analog read at default speed takes 104 µs.

Cool, if you do ADC with interrupts, you could send the value while waiting for the other to complete :)

That's right, so you won't take 104 + 43.4 µs. However you still have the limitation of the overall time. You can, though, run the ADC clock faster and still get acceptable results.


text:
Change Token authentication method to MQTT authentication method(username, password, client_id, ssid, passwd)
I have a mq135 sensor abd nodemcu ESP-12E module to calculate air quality and monitor it via Cayenne platform.
How can I edit this below code to add and connect my Nodemcu ESP-12E module to cayenne with MQTT authentication(username, password, client_id, ssid, passwd) method?
We can’t add Nodemcu with token method, we should use MQTT authentication instead to add and connect nodemcu module to cayenne.
 #include “MQ135.h”
 #include “CayenneDefines.h”
 #include “CayenneWiFi.h”
 #include “CayenneWiFiClient.h”
 #define CAYENNE_DEBUG
 #define CAYENNE_PRINT Serial
 #define VIRTUAL_PIN 5
 #define ANALOGPIN A0

char token[] = “”; // Insert your token here
char ssid[] = “”; // Insert your SSID here
char pwd[] = “”; // Insert your SSID password here
MQ135 gasSensor = MQ135(ANALOGPIN);

void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Cayenne.begin(token, ssid, pwd);
}

void loop() {
// put your main code here, to run repeatedly:
Cayenne.run();
// float rzero = gasSensor.getRZero(); //this to get the rzero value, uncomment this to get ppm value
// float ppm = gasSensor.getPPM(); // this to get ppm value, uncomment this to get rzero value
// Serial.println(rzero); // this to display the rzero value continuously, uncomment this to get ppm value
// Serial.println(ppm); // this to display the ppm value continuously, uncomment this to get rzero value
// Cayenne.virtualWrite(VIRTUAL_PIN,ppm); // uncomment after rzero define and get your ppm calculation
}

You could have readily answered this question for yourself merely by looking at the example for the Cayenne-MQTT-ESP8266 library.
The key part being:
// Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
char username[] = "MQTT_USERNAME";
char password[] = "MQTT_PASSWORD";
char clientID[] = "CLIENT_ID";

Cayenne.begin(username, password, clientID, ssid, wifiPassword);

It is not readily possible to know if this is the same Cayenne library you were using before, as you neglected to specify what you were using.  The includes are different, but that could be a version difference, or it could be evidence of an entirely different approach.


text:
ARDUINO expected ';' before 'delay'
I want to shine LED in 64 of 255 duty cycles = level of brightness but it pops up this error (see picture). Can anybody tell me why and help me ? Thank you.
void setup() {
  // put your setup code here, to run once:

}

void loop() {

  analogWrite(11, 64)
  delay{1000};
  analogWrite(11, 0)
  delay(1000);

  // put your main code here, to run repeatedly:

}

The error message (and the title of your post) tells you everything you need to fix your code, really.

You should write ";" end of each lines.
analogWrite(11, 64);
delay(1000);
analogWrite(11, 0);
delay(1000);

This advice helped a lot :) Great, it works already.
Thank you very much Furkan

Did you check connects? You should check that long leg of led is connected with arduino.

It works already, thank you very much. I had also broken LED and with new one it works perfectly :)

Good job. See you...


text:
How might I add a delay, close the servo and go to the start again?
#include <Servo.h>
Servo myServo;

  const int piezo = A0;
  const int button = 2;
  const int yellow = 3;
  const int green = 4;
  const int red = 5;

  int knockVal;
  int buttonVal;

const int quietKnock = 10;
const int loudKnock = 100;

boolean locked = false;
int numberOfKnocks = 0;

void setup()
{
  myServo.attach(9);
  pinMode(yellow, OUTPUT);
  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(button, INPUT);
  Serial.begin(9600);

  digitalWrite(green, HIGH);
  myServo.write(0);
  Serial.println("The box is unlocked!");
}

void loop()
{ //start of loop
  if (locked == false)
  { //start of if1
    buttonVal = digitalRead(button);
    if (buttonVal == HIGH)
    { //Start of if2
      locked = true;
      digitalWrite(green, LOW);
      digitalWrite(red, HIGH);
      myServo.write(90);
      Serial.println("The box is locked!");
      delay (1000);

    }     //end of if2
  }      //end of if1

  if (locked == true)

  { //start of if3

    knockVal = analogRead(piezo);

    if (numberOfKnocks < 3 && knockVal > 0)

    { //start of if4

      if (checkForKnock(knockVal) == true)

      { //start of if5

        numberOfKnocks++;

      }   //send of if5

      Serial.print(3 - numberOfKnocks);
      Serial.println(" more knocks to go");

    }     //end of if4

    if (numberOfKnocks >= 3)

    { //start of if6
      locked = false;

      myServo.write(0);
      delay(20);
      digitalWrite(green, HIGH);
      digitalWrite(red, LOW);
      Serial.println("The box is unlocked!");

    }   //end of if
  }   //end of if3
}           //End of loop

boolean checkForKnock(int value)
{ //start of boolean

  if (value > quietKnock && value < loudKnock)

  { //start of if7

    digitalWrite(yellow, HIGH);
    delay(50);
    digitalWrite(yellow, LOW);
    Serial.print("Valid knock of value ");
    Serial.println(value);
    return true;
  }   //end of if7
  else
  { //start of else
    Serial.print("Bad knock value ");
    Serial.println(value);
    return false;
  }   //end of else
}     // end of boolean

May I know at what point you want to add the delay

You already have delays. Can you specify more completely what you are trying to achieve?

Once the Servo is unlocked I would like to add a delay to lock the servo again and then start the code again. Right now it unlocks but will stay unlocked, if you press the button it will lock for 1 sec then unlock again.

Hey I have answered your question please let me know if it's the thing you wanted in your code or not .

if (buttonVal == HIGH)
{ //Start of if2
  locked = true;
  digitalWrite(green, LOW);
  digitalWrite(red, HIGH);
  myServo.write(90);
  Serial.println("The box is locked!");
  numberOfKnocks = 0;
  delay(1000);
}

I have added numberOfKnocks = 0 at this part of the code so your knock value goes to zero on locking it which will not open the lock again as soon as you lock it. The problem was that you did not change the numberoflnock value which remains same even after locking it so when the code loops back to the unlocking part it automatically unlocks it.
Hope this helps you.


text:
Reading CMPS10 raw values
I've got a cmps10 compass module hooked up to my arduino due through a logic level converter. I am writing code to convert the raw magnetometer readings into a bearing that I can use but have run into a huge problem. My bearings are all funky for some reason. They are totally unrelated to the actual bearing of the robot. I know the sensor is fine because I am able to get the tilt compensated reading from it and it works great. One thing I noticed is that the magnetometer reading on the X-axis is always positive could this be the problem? The X-axis high byte generally between 0x00 and 0x03. My code is below (i2cBus = &Wire)
i2cBus->beginTransmission(I2C_Address);
i2cBus->write(byte(10));
i2cBus->endTransmission();

i2cBus->requestFrom(I2C_Address, 4);
xMagHighByte = i2cBus->read();
xMagLowByte = i2cBus->read();
yMagHighByte = i2cBus->read();
yMagLowByte = i2cBus->read();

xMag = short(xMagHighByte<<8);
xMag |= xMagLowByte;
yMag = short(yMagHighByte<<8);
yMag |= yMagLowByte;

if(yMag!=0){
  magBearing = (atan2(xMag,yMag)*180.0)/3.141592654;
}
else if(xMag>0) magBearing=0.0;
else if(xMag<0) magBearing=180.0;
else magBearing = 1000;
if(magBearing < 0) magBearing+=360;
magBearing=360-magBearing;
return magBearing;

Compass modules are highly susceptible to interference from ferrous deposits underground and metals in or around your robot. To correct for them, you need to shift and scale both axis.
But first, test if the sensor's X axis is working by watching the value while moving a small magnet around the sensor. If should overpower any stationary field and bias in the sensor, if it can't then there may be a problem with the sensor.
To calibrate the compass, first find the min and max value for each axis. Do this by reading all the outputs of an axis when moving the sensor in a complete circle in the environment you will be using it in. Making the robot drive in a circle when first turned on to calibrate itself is not a bad idea. Anyway, the shift is the negative average and the scale is half the difference between maximums. what really matters is that this "distance" is the same on both axis, but normalizing both is easier. For example,
float Scale, Shift, Value;
Scale =  (max-min)/2;
Shift = -(max+min)/2;
Value = float(raw+Shift)/Scale;

Once both axis are corrected the atan2() function can work properly. If you were to plot the x and y points on a graph, they should trace a unit circle at the origin.


text:
Can I short this code?
int r = 12;
int g = 11;
int b = 10;
int sw = 4;
int x;
int c = 0;

void setup() {
    pinMode(r, OUTPUT);
    pinMode(g, OUTPUT);
    pinMode(b, OUTPUT);
    pinMode(sw, INPUT);
    pinMode(13, OUTPUT);
}

void loop() {
    x = digitalRead(sw);
  if(x==HIGH) {
    delay(250);
    c++;
    if(c==1) {
        digitalWrite(r, HIGH);
        digitalWrite(g, LOW);
        digitalWrite(b, LOW);
       {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
      }

    }
    else if(c==2) {
        digitalWrite(r, LOW);
        digitalWrite(g, HIGH);
        digitalWrite(b, LOW);
             {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
      }
    }
        else if(c==3) {
        digitalWrite(r, LOW);
        digitalWrite(g, LOW);
        digitalWrite(b, HIGH);
             {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
      }
    }
        else if(c==4) {
        digitalWrite(r, HIGH);
        digitalWrite(g, HIGH);
        digitalWrite(b, LOW);
             {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
      }
    }
            else if(c==5) {
        digitalWrite(r, LOW);
        digitalWrite(g, HIGH);
        digitalWrite(b, HIGH);
             {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
      }

    }
            else if(c==6) {
        digitalWrite(r, HIGH);
        digitalWrite(g, LOW);
        digitalWrite(b, HIGH);
             {
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
        c=0;
      }

    }

  }
}

What is the purpose of putting the last 3/4 or so of the statements in each if() block into a separate block? Certainly you could considerably shorten your code by putting those statements into a separate function that takes as its argument the number of times to toggle pin 13.

I suggest you use the auto-indent tool in the IDE. Your indentation is all over the place. And as JRobert said, learn about writing functions. Whenever you copy/paste the same code into multiple places like that, you should be writing a function instead. Are you flashing pin 13 the number of times that c is? How about making that into a loop?

int r = 12, g = 11,b = 10, sw = 4, x, c = 0;

void setup() {
    pinMode(r, OUTPUT);
    pinMode(g, OUTPUT);
    pinMode(b, OUTPUT);
    pinMode(sw, INPUT);
    pinMode(13, OUTPUT);
}

void loop() {
  x = digitalRead(sw);
  if(x==HIGH) {
    delay(250);
    c++;
    if(c==1)      setRGBandBlink13(HIGH,LOW,LOW,1);
    else if(c==2) setRGBandBlink13(LOW,HIGH,LOW,2);
    else if(c==3) setRGBandBlink13(LOW,LOW,HIGH,3);
    else if(c==4) setRGBandBlink13(HIGH,HIGH,LOW,4);
    else if(c==5) setRGBandBlink13(LOW,HIGH,HIGH,5);
    else if(c==6){
      setRGBandBlink13(HIGH,LOW,HIGH,6);
      c=0;
    }

  }
}

void setRGBandBlink13(bool newR,bool newG,bool newB,int times){
  setRGB( newR, newG, newB);
  blinkPin13(times);
}

void setRGB(bool newR,bool newG,bool newB){
  digitalWrite(r, newR);
  digitalWrite(g, newG);
  digitalWrite(b, newB);
}

void blinkPin13(int times){
  for(int i=0;i<times;i++){
    digitalWrite(13,HIGH);
    delay (250);
    digitalWrite(13, LOW);
    delay (250);
  }
}

This Sketch is way shorter and way better to maintain.
Note that 1/3 (26 out of 78) of the lines are comments.
Note:
Your RGB is able to display 8 states, but only 7 can be reached.
binc - c - RGB
 000 - 0 -
 001 - 1 - R
 010 - 2 -  G
 011 - 3 - RG
 100 - 4 -   B
 101 - 5 - R B
 110 - 6 -  GB
 111 - 7 - RGB - NEVER REACHED
int r = 12;
int g = 11;
int b = 10;
int sw = 4;
int c = 0;
int maxC = 6;
int minC = 0;

void setup() {
    pinMode(r, OUTPUT);
    pinMode(g, OUTPUT);
    pinMode(b, OUTPUT);
    pinMode(sw, INPUT);
    pinMode(13, OUTPUT);
}

// for  (pulses)-times
// set  (targetPin) HIGH
// wait (msDelay)
// set  (targetPin) LOW
// wait (msDelay)
void pulse( int targetPin, int msDelay, int pulses ){
    // count to pulses
    // for each count, set targetPin HIGH and LOW
    // wait msDelay between each state change
    for ( int i = 0; i <= pulses, i++ ){
        digitalWrite( targetPin, HIGH );
        delay( msDelay );
        digitalWrite( targetPin, LOW );
        delay( msDelay );
    }
}

// int rgbBinary will set RGB according to its binary value.
// R ~= BIT_1
// G ~= BIT_2
// B ~= BIT_4
void setRGB( int rgbBinary ){
    // set each LED OFF
    // This is by far more performant than
    // checking which should keep its state.
    digitalWrite( r, LOW );
    digitalWrite( g, LOW );
    digitalWrite( b, LOW );

    // if rgbBinary contains BIT value 1, set R to HIGH
    if ( rgbBinary & 1 ) {
        digitalWrite( r, HIGH) ;
    }
    // if rgbBinary contains BIT value 2, set R to HIGH
    if ( rgbBinary & 2 ) {
        digitalWrite( g, HIGH );
    }
    // if rgbBinary contains BIT value 4, set R to HIGH
    if ( rgbBinary & 4 ) {
        digitalWrite( b, HIGH );
    }
}

void loop() {
    // INPUT on SW ?
  if ( digitalRead( sw ) == HIGH) {
    // wait 250ms
    delay( 250 );
    // incement c
    c++;
    // increment RGB status
    setRGB( c );
    // pulse OUTPUT 13 (c)-times
    // starting by HIGH
    // delay 250ms between each HIGH/LOW
    pulse( 13, 250, c );
    // reset (c) on maxC
    if ( c == maxC ){
        c = minC;
    }
  }
}

I don't have an appropriate circuit handy for testing, but I've condensed the code a bit and renamed some things to be more readable. Hopefully the result is the same! Importantly, I've changed your c to step and it is now zero-based, so "step 1" is 0 and "step 6" is 5, etc.
const int rPin = 12;
const int gPin = 11;
const int bPin = 10;
const int swPin = 4;
const int pin13 = 13; // Needs a better name!
const int msDelay = 250;

int step = 0;

// By pure luck, your patterns overlap, so they can be condensed like so.
const byte patterns[13] = {
    // 0         1          2          3          4           5
    HIGH, LOW, LOW, HIGH, LOW, LOW, HIGH, HIGH, LOW, HIGH, HIGH, LOW, HIGH
};

void setup()
{
    pinMode(rPin, OUTPUT);
    pinMode(gPin, OUTPUT);
    pinMode(bPin, OUTPUT);
    pinMode(swPin, INPUT);
    pinMode(pin13, OUTPUT);
}

void loop()
{
    if (digitalRead(swPin) == HIGH)
    {
        delay(msDelay);

        // Write red/green/blue pattern
        int index = step * 2;
        digitalWrite(rPin, patterns[index]);
        digitalWrite(gPin, patterns[index + 1]);
        digitalWrite(bPin, patterns[index + 2]);

        // Blink once for each step (0 through 5)
        for (int i = 0; i <= step; ++i)
        {
            digitalWrite(pin13, HIGH);
            delay(msDelay);
            digitalWrite(pin13, LOW);
            delay(msDelay);
        }

        // Increment or reset step
        step = (step < 5) ? step + 1 : 0;
    }
}

Make all those ints in a single line.
int r = 12, g = 11,b = 10, sw = 4, x, c = 0;

While valid C, it is really bad coding style to do that. Declare each variable in its own line.

In this manner, compiler will trim code anyway. Declaring vars in a single row will decrease readability by a lot but won't trim the actual binary in the end. Nothing gained by that.

You could argue that putting everything in one line (int r=12;int g=11; int b=10; int sw=4; int x; int c=0;) would also "shorten" the code. But it barely decreases the amount of functional code. I also highly doubt that @USF meant to shorten this part of the code.


text:
Another problem with code; boolean?
Maybe another problem for trained eyes. I seem to get the alarm to cycle regardless of the state of "trigsensor" and "away" (they should both need to be true in order for the alarm to run after an incorrect code is entered). Thanks for any response to this, as I am still learning C:
//////////////////////////// initialize & includes //////////////////////////
#include <elapsedMillis.h>
#include "SIM900.h"
#include "sms.h"
#include "Keypad.h"
#include <GSM.h>
SMSGSM sms;

int PIR_SensorPin = 2;
int Alarm_OutPin = 11; //green
int Light_OutPin = 12; //red
int alarm_count = 0;
volatile boolean trigsensor = false;
boolean away = false;
const byte interruptPin = 2;
int z = 0;
int i = 0;

//////////////////////////// setup keyPad //////////////////////////
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] =
{
  {
    '1', '2', '3', 'A'
  }
  ,
  {
    '4', '5', '6', 'B'
  }
  ,
  {
    '7', '8', '9', 'C'
  }
  ,
  {
    '*', '0', '#', 'D'
  }
};
byte rowPins[ROWS] = {
  6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {
  3, A0, A1, A4
}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const char PIN[5] = {
  '9', '6', '7', '9', '#'
}; // PIN number
char key_input[5] = {
  0, 0, 0, 0, 0
}; // used for comparison

//////////////////////////////// setup ///////////////////////////////////
void setup() {
  Serial.begin (9600);  // Establish Serial connection;
  pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
  pinMode (Light_OutPin, OUTPUT);   // Set pinMode.
  pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
  digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (Light_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (PIR_SensorPin, LOW);
  Serial.println ("GSM Alarm starting up."); // Serial message that GSM shield is starting up
  if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
    Serial.println ("Status = Network READY");
    digitalWrite (Alarm_OutPin, HIGH);
  }
  delay (10000);
  attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); // PIR as interrupt
  Serial.println ("System Ready");
}

//////////////////////////////// void loop ///////////////////////////////////
void loop() {
  if (trigsensor == true) {
    alarm();
  }
  else {
    readKeypad();
  }
}

//////////////////////////////// void trigger ///////////////////////////////////
void trigger() {
  trigsensor = true;
  //  alarm();
}

//////////////////////////////// void alarm ///////////////////////////////////
void alarm() {
  Serial.print ("away="); Serial.print (away); Serial.print (" ");Serial.print ("trigsensor=");Serial.println (trigsensor);
  Serial.println("at Alarm");
  if (away == true && trigsensor == true) { ////////////////////////////////
    // (sms.SendSMS("**********", "***Motion Detected in Studio!***"));
    Serial.println ("MOTION detected: SMS Sent");
  }
  // else if (trigsensor == true) {  /////////////////////////////////////////////
  for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
    digitalWrite (Light_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
    digitalWrite (Light_OutPin, LOW);
    digitalWrite (Alarm_OutPin, HIGH); delay (1000);
    digitalWrite (Alarm_OutPin, LOW); // End by turning off light
    Serial.println(alarm_count);
  }
  digitalWrite (Alarm_OutPin, HIGH);
  trigsensor = false;
  away = false;
  readKeypad();
}

//////////////////////////////// read Keypad ///////////////////////////////////
void readKeypad() {  //attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); // reattach interrupt
  char key = keypad.getKey();
  if (key != NO_KEY) { // if a keypad input
    key_input[z] = key;
    tone(10, 900, 100);
    Serial.print("Key_input["); Serial.print(z); Serial.print("] = "); Serial.println(key);
    z++;
    if (z >= sizeof(key_input)) {
      z = 0;
    }
    switch (key) {
      case '*': // resets key_inputs to "0"
        z = 0;
        break;
      case '#': // pressed to "enter"
        z = 0;
        for ( i = 0;   i < 4 ;  i++ ) {
          Serial.print(key_input[i]);
        }
        Serial.println ("-------");
        delay(100); // for extra de-bounce
        checkPIN();
        break;
    }
  }
}

//////////////////////////////// check PIN ///////////////////////////////////
void checkPIN() {
  Serial.println ("@ checkPIN ");
  int correct = 0;
  int i;
  for ( i = 0;   i < (sizeof(PIN) - 1) ;  i++ ) {
    if (key_input[i] == PIN[i]) {
      correct++;
    }
  }
  if (correct >= sizeof(PIN) - 1) {
    Serial.print ("# correct = "); Serial.println (correct); Serial.println (sizeof(PIN) - 1);
    correctPIN();
  }
  else {
    incorrectPIN();
  }
}

//////////////////////////////// correct PIN ///////////////////////////////////
void correctPIN() {              // do this if correct PIN entered
  Serial.println ("@ correct PIN ");
  digitalWrite (Alarm_OutPin, HIGH);
  digitalWrite (Alarm_OutPin, LOW);
  detachInterrupt(0);
  trigsensor = false;
}

//////////////////////////////// incorrect PIN /////////////////////////////////
void incorrectPIN() {           // do this if incorrect PIN entered
  Serial.println ("@ incorrect PIN ");
  delay(10000); // a slight delay aded to allow leaving without triggering the alarm
  trigsensor = false;
  away = true; /////////////////////////////////
  digitalWrite (Alarm_OutPin, HIGH);
  attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH);
  alarm();
}

Shouldn't this: if (trigsensor == true) be more along the lines of if (trigsensor == true && away == true) in the loop() function?

Would that really matter, as the problem seems to be the output of the operand, regardless of where it might be placed? I just tried it in the loop function and not any different.

attachInterrupt() doesn't support attaching on HIGH. Oh, and instead of if (trigsensor == true) you could write if ((trigsensor == true) == true), or maybe if (((trigsensor == true) == true) == true) (just kidding, if (trigsensor) is all you need).

Using "HIGH" with attacheInterrupt on a UNO seems to work. Is it a reliability concern?


text:
Servo control using DIP switch
I am pretty new to Arduino and programming too.
I want to sweep a servo using DIP switch. At the moment, I use 4 position DIP switch. To each of the switches, I want to set the number of times the servo has to run. Eg., Pos 1 of DIP switch says, sweep for 5 times. Pos 2 says, sweeps for 10 times etc.
I wrote the following code:
#include <Servo.h>

Servo myservo;
int pos = 0;
int count = 0;   // might need later
int runXTimes = 0;

#define S1 2
#define S2 3
#define S3 4
#define S4 5

int s1state = HIGH;
int s2state = HIGH;
int s3state = HIGH;
int s4state = HIGH;

void setup() {
   myservo.attach(9);
   pinMode(S1, INPUT_PULLUP);
   pinMode(S2, INPUT_PULLUP);
   pinMode(S3, INPUT_PULLUP);
   pinMode(S4, INPUT_PULLUP);
   pinMode(9, OUTPUT);
}

void loop() {

   s1state = digitalRead(S1);
   s2state = digitalRead(S2);
   s3state = digitalRead(S3);
   s4state = digitalRead(S4);

   // Servo control through Switch 1
   if (s1state == LOW) {     // read the input pin
      for (int runXTimes = 0; runXTimes < 5; runXTimes++) {    // Servo to     sweep for 5 times
         for (pos = 0; pos <= 80; pos += 1)  // goes from 0 degrees to 80 degrees in steps of  degree

         {
            myservo.write(pos);              // tell servo to go to position in variable 'pos'
            delay(5);
         }

         for(pos = 80; pos>=0; pos-=1)     // goes from 80 degrees to 0 degrees
         {
            myservo.write(pos);              // tell servo to go to position in variable 'pos'
            delay(5);
         }

      }

   }

   // Servo control through Switch 2. Used servo detach here
   else if (s2state == LOW) {  // read the input pin
      for (int runXTimes = 0; runXTimes < 10; runXTimes++) {  // Servo to sweep for 10 times
         for (pos = 0; pos <= 80; pos += 1)  // goes from 0 degrees to 80 degrees in steps of  degree
         {
            myservo.write(pos);              // tell servo to go to position in variable 'pos'
            delay(5);
         }

         for(pos = 80; pos>=0; pos-=1)     // goes from 80 degrees to 0 degrees
         {
            myservo.write(pos);              // tell servo to go to position in variable 'pos'
            delay(5);
         }

      }
      myservo.detach();
   }

   // Servo control through Switch 3
   else if (s3state == LOW) {  // read the input pin
      for (pos = 0; pos <= 80; pos += 1)  // goes from 0 degrees to 80 degrees in steps of  degree
      {                                  //
         myservo.write(pos);              // tell servo to go to position in variable 'pos'
         delay(5);
      }

      for(pos = 80; pos>=0; pos-=1)     // goes from 80 degrees to 0 degrees
      {
         myservo.write(pos);              // tell servo to go to position in variable 'pos'
         delay(5);
      }
   }

   // Servo control through Switch 4
   else if (s4state == LOW) {  // read the input pin
      for (pos = 0; pos <= 80; pos += 1)  // goes from 0 degrees to 80 degrees  in steps of  degree
      {
         myservo.write(pos);              // tell servo to go to position in variable 'pos'

         delay(5);
      }

      for(pos = 80; pos>=0; pos-=1)     // goes from 80 degrees to 0 degrees
      {
         myservo.write(pos);              // tell servo to go to position in variable 'pos'
         delay(5);
      }

   }
}

The actions that happen with the above code are:
1) Servo control through Switch 1 - If I switch ON (0) and then OFF (1) immediately, the servo sweeps for 5 times. Works more like a button switch. If I switch ON and OFF (immediately) again, I am able to sweep 5 times again. But, if I leave the switch in 1, the sweep does not stop after 5 times.
2) Servo control through Switch 2: If I switch ON, the servo sweeps for 10 times and stops as per my interest. But, if I change the switch to 0 and 1 again, the sequence does not start. In fact, no other switch works. I need to power OFF the Arduino to run the program again.
3) Servo control through Switch 3 (= switch 4): If my switch is 1, the servo sweeps. If my switch is 0, the servo stops.
Could you please suggest:
1) How to write the code so that my servo sweeps only for the set number of times even when the switch is in 1 always or whenever I toggle between 0 and 1?
2) I do not want to use serial communication (or typically a PC). Is it possible to interface a 7-segment  or LCD to display the number of sweeps completed or still left.
Thank you in advance.

This is imagination-based since I can't test it myself at this moment, but feel free to ask if something is not right.
int readswitch()
{
 int S1,S2,S3,S4;
 uint8_t data = 255;
 data |= digitalRead(S4)<<3;
 data |= digitalRead(S3)<<2;
 data |= digitalRead(S2)<<1;
 data |= digitalRead(S1)<<0;

  if (data==0b11111110) return 1; else
  if (data==0b11111101) return 2; else
  if (data==0b11111011) return 3; else
  if (data==0b11110111) return 4; else
  //add another condition here if you want
  return 0;
}

int laststate = 0;
int state = 0;
int rotation;

void setup()
{
  //setup here, including LCD initialization
  //..
  //..
  //..
}

void updateLCD(int x,int y)
{
  lcd.clear();
  //displaying pin status
  lcd.print("dip : ");
  lcd.print(x,DEC);
  lcd.print(" rot : ");
  lcd.print(y,DEC);
}

void loop()
{
  state = readswitch();
  if (state!=laststate)
  {
    if (state == 1)
    {
      rotation = 5;
      for (int i = 0; i< rotation; i++)
        {
         //update lcd
         updateLCD(state,(rotation-i));

         //.. servo rotation
         //..
        }
      //...
    } else

    if (state == 2)
    {
      //do what you want here if switch 2 == LOW
      //...
    } else

    if (state == 3) //switch 1 == LOW
    {
      //do what you want here if switch 3 == LOW
      //...
    } else

    if (state == 4) //switch 1 == LOW
    {
      //do what you want here if switch 4 == LOW
      //...
    }
  }
  laststate = state;

}

For more information about LCD, you can refer to this documentation

If you put the sweep-code in the setup function, it would execute once (because setup() is only called once) and you would see what you expected.
But, as it is in the loop() function, it executes each time the loop() function executes - that is the point of the loop() function. As another alternative, you could put an infinite- or forever loop
for(;;)
   ;    // program hangs here forever

at the end of the loop() function to prevent it returning and getting called again. Either way, you would see a single pass over the steps you coded.

Your switch 2 code includes a myservo.detach() at the end which prevents any further server code from operating.
If you want the switch 1 code to execute only once, you could add a myservo.detach() to the block.
You also seem to want to recycle for the appropriate number of times if you clear the switch.  For this, you may want to myservo.attach(9) when all the switches are open.
Alternately,  you could avoide the detach() and attach() by adding a one-shot flag to the conditionals, set it inside the conditional, and clear it when the switches are clear.
For example:
   if (!s1state & !s2state & !s3state & !s4state) armed = 1;
   ...

   if (armed & s1state == LOW) {     // read the stored input pin value
       armed = 0;
       ...


text:
Mega2560 R3 pin functions
When I read about mega2560 I saw it has 54 digital that can be used as input or output.
later on I saw the some of them are used for things like communication.
So I would like to know if the communication pin can still be used as output ? (to power leds)

Yes. Any pin can be used as a digital input/output. However, you cannot use certain communications when using those pins.
The types of communication and their effects on the pins:

SPI: This protocol is used for certain communications with certain breakout boards and shields. For example, the ethernet shield uses SPI to connect. On the Mega(2560), it is pins 50-53.
I2C: This protocol is also for connecting to external items. It is much slower than SPI, but uses only two pins. On the Mega, it uses pins 20/21.
UART/Serial: UART is a communication method that uses two wires and transmits bytes of data. It is often used to connect to things that don't need extreme amounts of data passed, but need a stable two way connection.

On all standard boards, the main UART is on pins 0 and 1. This is usually connected to a UART to USB chip which is sent to the computer. Note: you should still be able to upload sketches if they act as an output and random on/off won't hurt the device.
The Mega(2560) also has UART on pins 14/15, 16/17, and 18/19.

Yes, you can.
You are referring to SPI, I2C, and the 4 serial interfaces. If you want to use those you have to use the predefined pins for that. If you are not using those you can use them as normal GPIO.
If you want Serial communication for debugging, you shouldn't use digital pins 0 and 1.
If you need even more pins, you can even use the analog pins and digital input/output pins.