text:
Arduino IR not returning data
THIS QUESTION ISN'T IN USE ANYMORE

Solved by using an other remote that is supported by the libary

====NEW CODE====
    #include <IRremote.h>

    int RECV_PIN = 11;
    int relay1 = 2;
    int relay2 = 3;
    int relay3 = 4;

    int on = 1;
    int on1 = 1;
    int on2 = 1;

    IRrecv irrecv(RECV_PIN);
    decode_results results;

    void setup()
    {
      digitalWrite(relay3, HIGH);
      pinMode(relay3, OUTPUT);
      digitalWrite(relay2, HIGH);
      pinMode(relay2, OUTPUT);
      digitalWrite(relay1, HIGH);
      pinMode(relay1, OUTPUT);
      pinMode(13, OUTPUT);
      irrecv.blink13(true);
      irrecv.enableIRIn();
    }

    unsigned long last = millis();

    void loop() {
      if (irrecv.decode(&results)){
        if (results.value == 0x36167A85) {
          if (millis() - last > 250) {
            on = !on;
            digitalWrite(relay1, on ? HIGH : LOW);
          }
          last = millis();
        } else if (results.value == 0x36161AE5) {
          if (millis() - last > 250) {
            on1 = !on1;
            digitalWrite(relay2, on1 ? HIGH : LOW);
          }
             last = millis();
        } else if (results.value == 0x3616FA05) {
         if (millis() - last > 250) {
            on2 = !on2;
            digitalWrite(relay3, on2 ? HIGH : LOW);
          }
            last = millis();
        }
        irrecv.resume();
      }
    }

================
I'm working on this bit of arduino code for a while now but i can't get it to work. My circuit is wired up correctly, but it isn't returning any data in the serial prompt. Here is my code:
#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

int main = 0;
int left = 0;
int right = 0;

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

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    switch (results.value) {
      case 0x2E3A06C0:
        main = 1;
        Serial.println("MAIN: on");
        break;
      case 0x8C2921D6:
        left = 1;
        Serial.println("LEFT: on");
        break;
      case 0x226270DA:
        right = 1;
        Serial.println("RIGHT: on");
        break;
      case 0x4AC6E6A:
        main = 0;
        Serial.println("MAIN: off");
        break;
      case 0xDD5E26EF:
        left = 0;
        Serial.println("LEFT: off");
        break;
      case 0x3E5BEF99:
        right = 0;
        Serial.println("RIGHT: off");
        break;
    }
    irrecv.resume();
  }

  delay(100);
}

I'm using the libary Arduino-IRremote. When I try the demo "IRrecvDemo", it works fine. I have the hex codes from this demo. So can someone help me get this code working? It would be nice!

I'd start by troubleshooting at a hardware level first, e.g. checking with a logic analyser or oscilloscope if any 5V pulses are detected on pin 11.

I have checked it with an oscilloscope and it is working fine, but I still have the problem that it isn't returning any data into my serial prompt. Please help!

My suspicion is that the IR library was unable to decode your IR signal. What kind of remote control are you using, and is it supported? Your code looks fine on face value (compared to the IR library example), so that's the only thing I can think of.

Try also the receive example from https://www.pjrc.com/teensy/td_libs_IRremote.html

This is working and it is returning data "UNKONWN: (hex code here)", when i try my code it isn´t returning data

That essentially means that the protocol on your remote (you didn't say what type it is), is not supported. "results.value" will be 0 in this case.

@Reezy I'm using an old remote for a helicopter, Maby I should try it with an other remote, thanks for your help Reezy !

Try to put Quotation mark like this:
switch (results.value) {
  case "0x2E3A06C0":
    main = 1;
    Serial.println("MAIN: on");
    break;
  case "0x8C2921D6":
    left = 1;
    Serial.println("LEFT: on");
    break;
  case "0x226270DA":
    right = 1;
    Serial.println("RIGHT: on");
    break;
  case "0x4AC6E6A":
    main = 0;
    Serial.println("MAIN: off");
    break;

If this doesn't work too, maybe you've got a hardware problem

Well, found the problem but I don't know why. It was your variable declarations. The following code with "main, right, and left" integer variables commented out ran, the original didn't:
 #include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;
//int main = 0;
//int left = 0;
//int right = 0;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
        switch (results.value) {
      case 0xB9F56762:
        Serial.println("MARNIX IS RIGHT");
        break;
        case 0x8C2921D6:
//        left = 1;
        Serial.println("LEFT: on");
        break;
      case 0x226270DA:
//        right = 1;
        Serial.println("RIGHT: on");
        break;
    }
    irrecv.resume();

  }
   delay(100);
}

I have it already working, but thanks!

the answer is now inside the main post

Did you try removing the 0x indicator? If I remember correctly the incoming signals are raw, e.g. 2E3A06C0, even though the script requires the 0x indicator on the send routines.
Alternatively, you'd need to rewrite, but you could try this IR Library and code, which I found has much better documentation and data analysis options on the receiving side: https://github.com/cyborg5/IRLib/

I need the 0x because it is hex, I tried the other lib but it is stil not working....

You're right. I tried to run your code without the 0x and it trips a type incompatibility error.

THIS QUESTION ISN'T IN USE ANYMORE

Solved by using an other remote that is supported by the libary
  and tweaking the code.

====NEW CODE====
    #include <IRremote.h>

    int RECV_PIN = 11;
    int relay1 = 2;
    int relay2 = 3;
    int relay3 = 4;

    int on = 1;
    int on1 = 1;
    int on2 = 1;

    IRrecv irrecv(RECV_PIN);
    decode_results results;

    void setup()
    {
      digitalWrite(relay3, HIGH);
      pinMode(relay3, OUTPUT);
      digitalWrite(relay2, HIGH);
      pinMode(relay2, OUTPUT);
      digitalWrite(relay1, HIGH);
      pinMode(relay1, OUTPUT);
      pinMode(13, OUTPUT);
      irrecv.blink13(true);
      irrecv.enableIRIn();
    }

    unsigned long last = millis();

    void loop() {
      if (irrecv.decode(&results)){
        if (results.value == 0x36167A85) {
          if (millis() - last > 250) {
            on = !on;
            digitalWrite(relay1, on ? HIGH : LOW);
          }
          last = millis();
        } else if (results.value == 0x36161AE5) {
          if (millis() - last > 250) {
            on1 = !on1;
            digitalWrite(relay2, on1 ? HIGH : LOW);
          }
             last = millis();
        } else if (results.value == 0x3616FA05) {
         if (millis() - last > 250) {
            on2 = !on2;
            digitalWrite(relay3, on2 ? HIGH : LOW);
          }
            last = millis();
        }
        irrecv.resume();
      }
    }

================


text:
How to run 5 wires hibrid stepper motor with arduino uno?
I have a question. How to run stepper motor (Nema 17) that has 5 wires with arduino and stepper driver.
Here is the driver, stepper and Arduino when stepper has 4 wires.
http://jdreyer.com/projects/Arduino/ArduinoEasyDriverStepperMotorv1_Resize.png
I need help identifying the wires on my hibrid stepper motor. I will provide picture of dissasembled motor.
Questions are:

Wires identification?
How to connect it to ArduinoEasyDriver?
Code example desired.

UPDATE

I am now thinking of making it bipolar (4 wires), because now in 5
  wires configuration motor is unipolar. I did some research and this
  motor is HIBRID. It can be driven as unipolar or bipolar. I will try
  to troubleshoot the wiring and find the common wire. Ill keep you
  informed.

The stepper has 8 coils? So it already has "4 wires" and one for ground I guess. You shouldn't be all to distracted by the amount of wires, check it first (if one is ground).

It has 8 coils. I will check the wires.

Could you look at this page: http://ebldc.com/?p=253 and read "The Five Wire Stepper" section? If you can confirm your stepper motor is wired like the picture in the example, and none of the wires are connected to the stepper motor's metal case, then I can help you.

1) it is probably something like A1, A2, Common, B1, B2.  You could confirm this with an ohmmeter. Common to any of the others would be a certain resistance X, while between any of the others (A1-A2, B1-B2, A1-B1, A1-B2, B1 A2) would be 2X.
2) You can't.  It is a unipolar stepper.
The EasyDriver faq number 5.1 at http://www.schmalzhaus.com/EasyDriver/ says:  "... The only kind you can't use is 5-wire stepper motors. (They need uni-polar drivers.)"
The difficulty with the 5-wire steppers is that they short the middle of the two coils together, which makes it hard to drive the coils independently.
Since you have the motor open, you might be able to do some surgery and disconnect the centers of the coils from each other, but you'll probably be better off getting a 4, 6 or 8 wire stepper instead.

Im up for the surgery. Guide me in how. :)

One of the 5 beads should have 4 wires going to it.  You would need to unsolder them.  If you leave all four of them free, you have an 8-wire stepper.  If you hook the right pairs together you get a four wire stepper. If you put pigtails on the pairs, you would have a 6-wire stepper.   Guidance on the right pairing might be to connect the pair that are connected to the two left terminals as one the middle terminal, and then the pair that are connected to the right two terminals as the other middle.  Look at the 4,6,8 wire coils on https://www.pololu.com/product/1182/faqs .

I'd guess that it is the upper-left solder joint in your picture that needs to be separated.

Ok I will try something today. I will keep you informed.

Do be aware that the patient could die.  Good luck.

I have 3 of them. All patients volunteered for experiment. :D

On stepper motors there are a few types of wiring, but essentially there are two coils inside the stepper motor. To figure out where the wiring is you need a way to test if the coils are being connected. On your setup I would suggest to connect two of the wires together at a time and spin the shaft. If the shaft offers resistance then you have found the two wires for one coil.
For your stepper motor it looks like it may have three coils, but out of the 6 wires you may also only come up with 4 wires; which would equal 2 coils.
As far as connecting it to an easy driver, the easy driver only takes two coils. you would need to find a driver that can take three coils, or just connect two coils out of the three and hope for the best.

Instead of doing surgery on your unipolar stepper, you can use it like a unipolar stepper. Some transistors to hook the motor to power (just get a darlington array chip), and four output pins on the arduino. Works fine.

Can you provide some schematics? Or wiring?

@PaulMurrayCbr That's exactly what I'm using and it works great. Texas Instruments makes one: ULN2003A but I cheated and got a board from ebay: http://www.ebay.ca/itm/1PCS-ULN2003-Stepper-Motor-Driver-Board-for-Arduino-AVR-AR-M-/181586125620?hash=item2a47606334:g:gqUAAOSwMKpUZsTN

Finding the ground pin
We should start off by finding the Ground/GND pin.
Do you have an Ohm-meter? I believe one of the pins should be GND/ground, and should have low resistance when referenced to the other pins.
Wiring the stepper
Steppers have a coil and thus are an inductive load, you should really check your wiring with sources, to be sure they're valid.
(At this point I can't give you a 100% accurate wiring diagram, but it should be easy to find, as wiring steppers is quite common.)
You could use a pre-assembled stepper-driver. Having such a thing is usefull when you want to design the circuitry yourself.
Driving the steppers
You should generate a signal like this: https://en.wikipedia.org/wiki/Stepper_motor#Phase_current_waveforms
(The source/link describes the different forms of stepping. Like "Wave drive (one phase on)" in which each coil is activated/deactivated in a rotary fashion, making the core turn around.)
Extra
Adafruit always has extremely well documented tutorials for beginners:
https://learn.adafruit.com/all-about-stepper-motors/types-of-steppers
The wiki of RepRap should be a good source, since steppers are the hearth of 3D printers (RepRap is a 3D printer brand):
http://reprap.org/wiki/Stepper_wiring

I will try to find the ground with ohm-meter. Resistance should be different comparing to other combinations. Thank you for your suggestion. Ill keep you informed.

source: Stack Exchange

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

sort: votes


text:
Read a String from serial to debug the AT commands sent to my GPS shield
I want to extract an AT command's response (via serial port) to find out if the GPS shield is working as it should be.
I used:
  if(Serial.available()>1){
     String response = Serial.read();
     Serial.println(response);
  }

Normally the response to AT is OK but it keeps telling me that it cannot convert int to String .... can someone help?

if (Serial.available() > 1) is wrong. Always use if (Serial.available()) in such cases. Also it seems you are communicating with the GPS shield using Hardware Serial. However, the Arduino also uses the same serial port for communicating with the PC via the USB connection. So what you have basically is:

Arduino TX, PC RX and GPS RX are all connected
Arduino RX, PC TX and GPS TX are all connected

So anything the Arduino writes to the Serial port using Serial.println() is received by both the PC and the GPS shield. And the other hand, responses from the GPS shield and commands sent from the serial monitor all arrive at the same Arduino pin. So when you use Serial.read(), assuming you used the serial monitor to send the command, you will end up receiving your own command (like some sort of echo), and according to your program, you use Serial.println() to send the command again which is received by both PC and GPS shield, with the GPS shield responding to the same command again. All undesirable.
TLDR; use SoftwareSerial instead for the GPS shield. Connect the GPS shield TX to pin 2 and its RX to pin 3 and use this code:
    #include <SoftwareSerial.h>

    SoftwareSerial gps(2,3);   // pin 2 = RX, pin 3 = TX

    void setup(){
        Serial.begin(57600);
        gps.begin(57600);    // change to your baud rate, if not auto-baud
    }

    void loop(){
        while (Serial.available())     //used to send commands from PC
            gps.write(Serial.read());   // to gps
        while (gps.available())        // used to read responses from gps
            Serial.write(gps.read());  // to PC
    }

So the Arduino forwards everything it receives from the PC monitor (commands) to the shield and sends everything it receives from the shield (responses) to the PC to be displayed in the serial monitor.

Serial.read() returns a byte (a single character), you've told the compiler that response is a string. It doesn't know how to deal with the difference…
What you want to do it to read the response in a loop until you've got it all.
Here's an example.

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


text:
String array glitch
For a project, I was asked to design a presentation on Arduino. I now have run into the problem of my code suddenly stopping. It worked fine one day, I entered a new item in the array, it stopped working. It looked like I was being returned all newlines insteaed of debug info. Can anyone help?
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

int slide = 0;
const int slideNum = 13;
const String data[] = {
  "What is Arduino?\nArduino is a board\nthat can be used to\neasily program",
  "that can be used to\neasily program\ncomplex behaviors.",
  "Purpose\nMoney\nEase of Use",
  "How are they\ncontrolled?\nIDE, C++, Library\n",
  "Commonly Used\nCommands\ndiditalWrite();\ndidgitalRead();",
  "Commands\ndiditalWrite();\ndidgitalRead();\npinMode();",
  "diditalWrite();\ndidgitalRead();\npinMode();\nanalogWrite();",
  "didgitalRead();\npinMode();\nanalogWrite();\nanalogRead();",
  "Arduino Types\nUno\nMega 2560\nLeonardo",
  "Uno\nMega 2560\nLeonardo\nNano",
  "Mega 2560\nLeonardo\nNano\nMini",
  "Leonardo\nNano\nMini\nEthernet",
  "Nano\nMini\nEthernet\nBluetooth",
  "THE END"};

//Addr: 0x3F, 20 chars & 4 lines
LiquidCrystal_I2C lcd(0x27,20,4);

void setup()
{
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Send Newlne to start");
  Serial.begin(9600);
}
void loop()
{
  while (Serial.available() <= 0){
  }
  Serial.println("Current: " + String(slide));
  while (Serial.available() != 0){
    Serial.read();
  }
  next();
  if (slide == slideNum){
    for(;;){
    }
  }
}

void next(){
  String local = data[slide];
  String current[4];
  for (int i = 0; i != 4; i++){
    current[i] = local.substring(0, local.indexOf("\n"));
    local.replace(local.substring(0, local.indexOf("\n")), "");
    current[i].trim();
    local.trim();
    Serial.print("i=" + String(i) + ", current=" + current[i]);
    Serial.println(", local="+local);
  }
  lcd.clear();
  for (int i = 0; i != 4; i++){
    Serial.println(current[i]);
    lcd.setCursor(0,i);
    lcd.print(current[i]);
  }
  //lcd.print(data[slide]);
  slide += 1;
  Serial.println("New: " + String(slide));
}

Ouch, your poor poor heap...

Change const String to const char *.

@TisteAndii Provide that as an answer, it does work.

I edited the question to format the code; the HTML tags you put around the code didn't work.  The text in questions and answers on SE sites use Markdown Syntax, a sort of bastardized HTML.  ¶ You should fix those silly misspellings (extra d, or d instead of g, in "diditalWrite" and "didgitalRead" [sic]

You should really use PROGMEM to force the strings to remain in Flash. Oh, and never use String for anything, ever.

@JamesWaldby-jwpat7 Oops.

Since you haven't provided all of your code, I can't say for sure exactly what caused your problem except that Arduino String operations employ dynamic allocation a lot. This will cause heap fragmentation, which is especially bad on a chip like the ATmega328 with little RAM and subsequently cause weird issues like you're getting. I would guess that initializing the String members of the array takes up a lot of heap space while fragmenting it and when you added one more string, you ended up with a stack-meets-heap situation at some point in loop().
You're a lot better off with an array of compact strings using an array of pointers to char i.e. const char * array[] = ... since the strings are literals and so already known at compile time.

Thanks! Honestly, I copied all of my code, don't know why it didn't paste.


text:
Arduino Variable Data Type?
Is there a variable data type available for Arduino? I have a class that should have a member that will differ in data type, in the past I have used the "variable" keyword in c++ but when I tried to use it the compiler yelled at me. I searched online and found a couple of articles that mentioned that if you are using an alternate GUI (I am using eclipse mars) that you can enable the feature but I can not find the correct settings as the examples I had found were for Juno and below.
Here is an example of what I am trying to accomplish
class DisplayItem{

   public:
   variant *displayVar;

   void Display(){
      Serial.println(displayVar);
   }
}

int intDisplay;
String strDisplay;

DisplayItem item();
item.displayVar = &intDisplay;
item.Display();
item.displayVar = &strDisplay;
item.Display();

I realize I could create a overloaded function to display different data types but it would be allot easier if I could simply assign a reference to a variant datatype and reuse the variable.

Edit
So after looking through the answers I think I have this figured out. I needed to keep track of which variable was being set, I put together a quick example in hopes it will help someone else out with the same question.
class DisplayItem{

   private:
   int iVarType;

   union{
      int *i;
      float *f;
   } displayVar;

   public:
   void SetVar(int *var){
      displayVar.i = var;
      iVarType = 0;
   }

   void SetVar(float *var){
      displayVar.f = var;
      iVarType = 1;
   }

   void Display(){
      if (iVarType == 0){
         Serial.println(displayVar.i);
      }else if (iVarType == 1){
         Serial.println(displayVar.f);
      }
   }
}

int intDisplay = 1;
float floatDisplay = 0.123;

DisplayItem item();
item.SetVar(&intDisplay);
item.Display();
item.SetVar(&floatDisplay);
item.Display();

Will Display:
1
0.123

For the situation illustrated in the question – displaying data – polymorphic functions already exist, and might as well be used in this case.  Specifically, use the Streaming.h contributed library.  It adds some “syntactic sugar” to Arduino C.  At compile time it converts C++-like << Serial stream operators to Serial.print statements, without increasing code size.  You can install it via Streaming5.zip from arduiniana.org .
In other cases, a union data structure allows treating an area of memory different ways.  Wikipedia's Union type article explains the general idea.  See eg tutorialspoint.com/cprogramming for union syntax and usage.  For some reason, arduino.cc's Language Reference page hasn't got union on its list of language features.  However, mcgurrin.com has a page called There is Power in a Union that codes a simple Arduino C example two ways (where bearing is an int):
higherByte = compass.read();
lowerByte = compass.read();
bearing = ((higherByte<<8)+lowerByte)/10

-vs-
union Data {
  byte b[2];
  int value;
};
...
union Data data;
data.b[0] = compass.read();
data.b[1] = compass.read();
bearing = data.value/10;

Would you then use sizeof(data.b[0]) to determine if the variable has been used or is there a better way?

sizeof data.b[0] (the parentheses aren't needed if the argument is a variable rather than a type) is a constant, so has no bearing on whether a section of memory has been set to a value.  Use a separate flag variable or some program flow analysis to keep track of whether a cell is occupied.  Note, union is most useful in certain type conversions (eg changing endianness among integer types or getting the exponent field of a float) or when marshalling data for export, eg filling a buffer with a variety of data items before using a write to send the buffer on its way.

No, there is no such thing.  The whole concept of "type" only exists during compilation, not at run-time.
However, you can "emulate" it using "setters" and keeping your own internal state information:
class Thing {
    private:
        String *strvar;
        int intvar;
        int type;

    public:
        void set(int val) {
            intvar = val;
            type = 1;
        }
        void set(String &str) {
            strval = &str;
            type = 2;
        }
        void Display() {
            if (type == 1) {
                Serial.print("Value: ");
                Serial.println(intval);
            } else if (type == 2) {
                Serial.print("String: ");
                Serial.println(strval);
            } else {
                Serial.println("Something went wrong");
            }
        }
};

Thing t;
String s = "This is a string";
int i = 23;
t.set(s);
t.Display();
t.set(i);
t.Display();

The multiple functions named the same but with different parameters are overloaded. The best match is picked at compile time.

I have in my question about using overloaded functions, I was hoping that there was a variable datatype as I have seen it in other c++ platforms. But if this is the only way to accomplish this I guess I don't have much choice.

It's down to the IDE preprocessing your code with its own keywords. The closest is a void * pointer which can point to the memory of any data type, however it doesn't have any concept of what that datatype is - it's just memory.

Actually modern C++ provides run-time type information for classes. See Wiki for some examples. Unfortunately this is often disabled when compiling for small scale embedded systems to reduce memory foot-print. Last, in @Majenko 's example the value could be stored in a union. See Cosa/Types.h univ16_t and univ32_t for examples of universal type.

You mean dynamic_cast? Only useful when you're working with polymorphism.


text:
Counting minutes in arduino
I have a dipswitch of 4 steps to get a binary number that will turn out to decimal from 0 to 15, So I need to get that number and make it the ammount of minutes to make something and also be aware of some input while the time runs out.
So I was thinking of having a variable being equal to millis() and then dividing it by 60,000 which is a minute in millis and If I get an integer that must mean a minute has passed, the problem is that I don't know how to check if the result is an integer or a float.
any advice?

To my understanding you want to make some sort of device that will count X min. To get X you configure the 4 dip switches to get the time (0000 - 1111 or 0 - 15). The easiest way is to configure 4 pins to INPUT_PULLUP then you wire your switch to those pins and to ground. If the pin is grounded (switch in the on state) it will register a 0 and if the pin is NOT grounded (switch in the off state) it will register a 1.
note: if all switch are "off" you will get a max value of 15 based on my example.
long startTime;
void setup(){
    pinMode(7, INPUT_PULLUP); //8bit
    pinMode(6, INPUT_PULLUP); //4bit
    pinMode(5, INPUT_PULLUP); //2bit
    pinMode(4, INPUT_PULLUP); //1bit

    startTime = millis();
}

void loop(){
    long inputTime = 0;

    if(digitalRead(7))
        inputTime += 8;

    if(digitalRead(6))
        inputTime += 4;

    if(digitalRead(5))
        inputTime += 2;

    if(digitalRead(4))
        inputTime += 1;

    inputTime = 60000*inputTime;

    if(millis() - startTime <= inputTime){
        //X min has passed -- Do something here if you like

        startTime = millis(); //reset the timer
    }else{
        //Time not yet reached -- Do something here if you like
    }
}

Your method is completely wrong.
You need a variable that contains the value of millis() at the start of your period, whenever that may be (when the switches change? when a button is pressed? since the Arduino was powered up?) and compare that value to the current value of millis().  When the difference between them is greater than or equal to 60000 * 15 then 15 minutes have passed.
Look at BlinkWithoutDelay in the Examples menu in the IDE - it showcases the technique for you.

well, the input from the dipSwitch is received in the void setup, as soon as you turn on the arduino. I've tried to use the blink without delay but I'm not sure how to count the minutes, i've even tried changing the interval to the input of the dipSwitch but it's only driving me crazier


text:
How to use Due PB0-PB7 pins as an external interrupt
In my board I need to use PB0-PB7 ports as an external interrupt sources.
Is it possible?
I spent a lot of time to understand that. Seems the easiest way is to update variant.cpp file by adding these pins.
Unfortunately this is not the solution I'm looking for (actually this can be a solution if I'm able to add pins from the sketch, but it is not possible to update cons dynamic array after declaration ).
Another way is to create my own interrupt handler. But I didn't find how should I do that.


text:
Here is my code and i keep getting this error expected primary-expression before'}' token
#include <QTRSensors.h>
#define NUM_SENSORS 8
#define TIMEOUT 2500
#define EMITTER_PIN QTR_NO_EMITTER_PIN
QTRSensorsRC qtrrc((unsigned char[]) {10,7,6, 5, 4, 2,16,14},
NUM_SENSORS, TIMEOUT, EMITTER_PIN);

unsigned int sensorValues[NUM_SENSORS];
int dirB = 12;
int speedB = 3;
int brakeB = 8;
int dirA = 13;
int speedA = 11;
int brakeA = 9;
int e=4;
int MzSensor=17;
int xp=4;

void setup() {
delay(500);
int i;
pinMode(13,OUTPUT);
digitalWrite(13,HIGH);
for (i = 0; i < 200; i++)
{
  qtrrc.calibrate();
}
digitalWrite(13,LOW);
Serial.begin(9600);
delay(100);
Serial.println("Robot");
for (i = 0; i < NUM_SENSORS; i++)
{
  Serial.print(qtrrc.calibratedMinimumOn[i]);
  Serial.print(' ');
}
Serial.println();
{
  Serial.print(qtrrc.calibratedMaximumOn[i]);
  Serial.print(' ');
}
Serial.println();
Serial.println();
delay(100);
}
void loop() {
Serial.print('ogeday');
unsigned int position = qtrrc.readLine(sensorValues);
unsigned char i;
for (i = 0; i <NUM_SENSORS; i++)
{
  Serial.print(sensorValues[i] * 10 / 1001);
  Serial.print(' ');
}
Serial.print("   ");
Serial.println(position);
delay(200);
if (digitalRead(MzSensor)==0) {
  while(digitalRead(MzSensor)==0) {
    digitalWrite (dirA, HIGH);
    analogWrite(speedA, 76);
    digitalWrite(dirB, HIGH);
    analogWrite(speedB, 76);
    xp == 5;
    Serial.println("durdu");
    delay(100);
  }
  delay(800);
  Serial.println("CIKTI");
}
else
if (position >= 3250 &&position <= 3750)
{
  if(sensorValues [1] < 500 )
  {
    e=7;
    xp=3;
  }
  if(sensorValues [8] < 500 )
  {
    e=1;
    xp=3;
  }
  if (sensorValues[3] < 500 || sensorValues[4] < 500 || sensorValues [5] <
  Serial.println("ILERI"),
  digitalWrite(dirA, HIGH),
  digitalWrite(brakeA, LOW),
  analogWrite(speedA, 72),
  digitalWrite(dirB, HIGH),
  digitalWrite(brakeB, LOW),
  analogWrite(speedB, 72),
  e=4,
  xp=3,

  delay (1),

}

 else if (position > 4050 || sensorValues [8] <500)
  {
    Serial.println("EN SAG");
    digitalWrite(dirA, LOW);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 19);
    digitalWrite(dirB, HIGH);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 45);
    e=1;
    xp=3;
  }
  else if (position <- 4050 &&position >- 3900)
  {
    Serial.println("SAG");
    digitalWrite(dirA, HIGH);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 51);
    digitalWrite(dirB, HIGH);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 60);
    e=1;
    xp=3;
  }
  else if (position >= 2950 &&position <= 3100)
  {
    Serial.println("SOL");
    digitalWrite(dirA, HIGH);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 60);
    digitalWrite(dirB, HIGH);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 51);
    e=7;
    xp=3;
  }
  else if (position < 2950 || sensorValues [1] < 300 )
  {
    Serial.println("EN SOL");
    digitalWrite(dirA, HIGH);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 45);
    digitalWrite(dirB, 45);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 19);
    e=7;
    xp=3;
  }
  else if (e==7) {
    Serial.println("Cizgi SOLLL");
    if (xp!=1){
      digitalWrite(dirA, LOW);
      digitalWrite(brakeA, LOW);
      analogWrite(speedA, 30);
      digitalWrite(dirB, LOW);
      digitalWrite(brakeB, LOW);
      analogWrite(sppedB, 30);
      xp=1;
      delay(1);
    }
    digitalWrite(dirA, HIGH);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 66);
    digitalWrite(dirB, LOW);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 48);
    e=7;
  }
  else if (e==1) {
    Serial.pirntln("{Cizgi SAGGG");
    if(xp!=1) {
      digitalWrite(dirA, LOW);
      digitalWrite(brakeA, LOW);
      analogWrite(speedA, 30);
      digitalWrite(dirB, LOW);
      digitalWrite(brakeB, LOW);
      xp=1;
      delay(1);
    }
    digitalWrite(dirA, LOW);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 48);
    digitalWrite(dirB, HIGH);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 66);
    e=1;
  }
  else if (e==4) {
    Serial.println("ILERI GIDIYOR");
    digitalWrite(dirA, HIGH);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 30);
    digitalWrite(dirB, HIGH);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 30);
    e=4;
  }
  //delay(300)
}

On what line? And where can we download the needed include files?

Delete extra left paren in QTRSensorsRC qtrrc((unsigned char[]) {10,7,6, 5, 4, 2,16,14},

Change delay (1), to delay (1);

In this part:
if (sensorValues[3] < 500 || sensorValues[4] < 500 || sensorValues [5] <
Serial.println("ILERI"),
digitalWrite(dirA, HIGH),
digitalWrite(brakeA, LOW),
analogWrite(speedA, 72),
digitalWrite(dirB, HIGH),
digitalWrite(brakeB, LOW),
analogWrite(speedB, 72),
e=4,
xp=3,

delay (1),

There's a lot of ',' instead of ';'. Change then to ';'.
Also, the 'if' is incomplete. Check the 'if' statement.

if (sensorValues[3] < 500 || sensorValues[4] < 500 || sensorValues [5] <
  Serial.println("ILERI"),

if() condition is not complete
; not ,

A little advice. Use functions so that your code is easy to read and easy to debug (looking for errors).
Something like :
void func(String text, boolean mDirA, boolean mBrakeA, int mSpeedA,
    boolean mDirB, boolean mBrakeB, int mSpeedB){

    Serial.println(text);
    digitalWrite(dirA, mDirA);
    digitalWrite(brakeA, mBrakeA);
    analogWrite(speedA, mSpeedA);
    digitalWrite(dirB, mDirB);
    digitalWrite(brakeB, mBrakeB);
    analogWrite(speedB, mSpeedB);

}


text:
How to read a higher voltage digital input?
Lets suppose I have a circuit with a car battery, a switch and a led. The led will turn on when the switch is closed, and turn off if it's not. I want to remove the led from the circuit and put an Arduino in that place to "read" when the circuit is closed or open.
I'm a good programmer, so the code is not the real problem. I only want to know how to do this without damaging the board.
How can I do this?

Lookup voltage dividers.

@Gerben What should be the destination voltage to enter into a digital input pin on the arduino? 5v?

5v indeed. But I'd leave a bit of margin.

As @Gerben says, voltage dividers are a good place to start. To elaborate on the topic, you can use a combination of voltage dividers, zener diodes and clamping diodes.
This EE.SE post has some good info about this, related to ADC, but still the same.
First off, a voltage divider circuit is easily found on the internet,

Google
Wikipedia

This circuit from Hyperphysics shows the basics:

To add more protection to this so as not to go over the max I/O voltage of the MCU, you can add a zener diode on the Vout.
That would give you something like this(Olins):

This will give you the desired range to give legitimate High and Low on an I/O.

If you wanted to forgo the voltage divider and zener you can use clamping diodes to the microcontroller supply voltage Vcc. This will give a range that will not damage the I/O.

simulate this circuit – Schematic created using CircuitLab
The 10k resistor is there to limit the current through the diodes, which are Schottky diodes.

Another method, which I have used before and is reliable, is to use a diode and two resistors like below:

The logic is that, when the input IN is > Vcc(5V) the signal on the I/O _IN will be the voltage of the pull_up resistor R2, if it is low or floating the signal will be low. R1 also gives a known logic state if the input floats.
Edit: Changed the image to proper logic flow.

Be careful that the IN and _IN pins in the last circuit are "logically" swapped, i.e. the signal goes RIGHT to LEFT: IN is the input, _IN is the microcontroller

@frarugi87 - I copied it straight from a schematic I'm working on(makes sense to me, as I did it ;)), thanks for pointing it out, I will edit it tomorrow when I get a chance.

Of course, but it took me a while to understand it ;) anyway thank you for sharing, I'll tkeep it in my mind next time I'll need this kind of converters ;)


text:
Serial Monitor breaks normal behaviour of Nano + NRF24l01

Couldn't find any other post that mentions Serial Monitor crippling the normal workflow of the NRF24l01, so here it goes.
I have two Arduino Nano, both with NRF24l01 attached, and an RF24 library working. Both NRF24l01 have 10uF caps soldered on them. One is only sending data, another is receiving only. Both of them flash LED on, successful transmission and successful receiving respectively.
When I run both devices, i see both LEDs flashing, so one succeeds in sending, and another one in receiving. But whenever I try to open Serial Monitor in my Arduino 1.6.1 software, the LEDs flash only every forth of fifth time of expected, and in my Serial Monitor I can see only 1 of 4 or 5 packets received (though received correctly).
Any ideas what I could have done wrong? Could Serial Monitor somehow interfere with Nano talking to NRF24l01?
The code follows, it's simple.
Sender
    /*
     Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>

     This program is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     version 2 as published by the Free Software Foundation.
     */

    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    #include "printf.h"

    // On Successfull Sending Blink PIN

    #define BLPIN 5

    //
    // Hardware configuration
    //

    // Set up nRF24L01 radio on SPI bus plus pins 9 & 10

    RF24 radio(9,10);

    //
    // Topology
    //

    // Radio pipe addresses for the 2 nodes to communicate.
    const uint64_t pipe = 0xF0F0F0F0E1LL;

    void setup(void)
    {
      pinMode(BLPIN, OUTPUT);

      //
      // Print preamble
      //

      Serial.begin(57600);
      printf_begin();
      printf("\n\rRF24/examples/GettingStarted/\n\r");

      //
      // Setup and configure rf radio
      //

      radio.begin();

      // optionally, increase the delay between retries & # of retries
      radio.setRetries(15,15);

      // optionally, reduce the payload size.  seems to
      // improve reliability
      radio.setPayloadSize(8);

      //
      // Open pipes to other nodes for communication
      //

      radio.openWritingPipe(pipe);

      //
      // Dump the configuration of the rf unit for debugging
      //

      radio.printDetails();
    }

    // counter data to be sent
    unsigned long counter = 0;

    void loop(void)
    {

      // Increase the counter and send it
      counter++;
      printf("Sending counter = %lu...", counter);

      if (radio.write( &counter, sizeof(unsigned long) ))
      {
        printf("ok...\n\r");
        digitalWrite(BLPIN, HIGH);
        delay(10);
        digitalWrite(BLPIN, LOW);
      }
      else
        printf("failed.\n\r");

      // Try again 1s later
      delay(1000);
    }

Receiver
    /*
     Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>

     This program is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     version 2 as published by the Free Software Foundation.
     */

    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    #include "printf.h"

    // On Receiver Blink PIN

    #define BLPIN 5

    //
    // Hardware configuration
    //

    // Set up nRF24L01 radio on SPI bus plus pins 9 & 10

    RF24 radio(9,10);

    //
    // Topology
    //

    // Radio pipe addresses for the 2 nodes to communicate.
    const uint64_t pipe = 0xF0F0F0F0E1LL;

    void setup(void)
    {
      pinMode(BLPIN, OUTPUT);

      //
      // Print preamble
      //

      Serial.begin(57600);
      printf_begin();
      printf("\n\rRF24/examples/GettingStarted/\n\r");

      //
      // Setup and configure rf radio
      //

      radio.begin();

      // optionally, increase the delay between retries & # of retries
      radio.setRetries(15,15);

      // optionally, reduce the payload size.  seems to
      // improve reliability
      radio.setPayloadSize(8);

      //
      // Open pipes to other nodes for communication
      //

      radio.openReadingPipe(1,pipe);

      //
      // Start listening
      //

      radio.startListening();

      //
      // Dump the configuration of the rf unit for debugging
      //

      radio.printDetails();
    }

    unsigned long counter;

    void loop(void)
    {
      // if there is data ready
      if (radio.available())
      {
        while( radio.available() ) {
          radio.read( &counter, sizeof(unsigned long) );
          // Dump the payloads until we've gotten everything
          printf("Got payload %lu...\n\r", counter);
        }
        digitalWrite(BLPIN, HIGH);
        delay(10);
        digitalWrite(BLPIN, LOW);
      }
    }

I had a Leonardo sending data to a FTDI-breakout-driven 3.3V Pro Mini and to a Mega2560. Both the Mini and Mega had idenctial code, except for the pipe addresses. The Mega was able to pick up every transmission (perhaps six losses out of 10,000 attempts) but the Mini was missing at least half of the packets. I changed the datarate to 2MBps (call radio.setDataRate(RF24_2MBPS) in setup() for each device) and the Mini's success rate jumped from under 50% to over 90%. It might be a bodge - the transmission has finished before the voltage has a chance to drop low enough - but it worked.

The reason for the Monitor being unable to work properly seems to be the length of the usb cable or a faulty usb port on my computer. I had a usb-cable extender, to which another (this time short) usb cable of my Arduino Nano was attached. It seemed to work fine while I was uploading things to Nano, but a quick serial exchange was, perhaps, not possible.Another usb port, or bypassing the usb cable extender brings everything back to normal.
This is a solution, while I still had no reason, how debugging through serial could influence that much on the chip behaviour itself, until now. I just thought it may well be the same power problem, as FTDI chip both powers the radio (even with the capacitor I installed!) and talks to computer through my long usb cable. If it starts talking, there could be no power for RF24 for a longer period than could be saved by my capacitor.

Are you using the FTDI chip's low-current 3.3v regulator to power your NRF24L01?  That might not be a good idea.

Try a lower baudrate than 57600.

I thought large enough cap (100uF) soldered on NRF24L01 would be enough. Am I mistaken?

When you use a very long cable you are limiting the total flow of current available to your arduino. The radio takes a lot of current. The cap only stores energy during the time you are not tx and then dumps it when you are.  If you tx less often you will have more time to recharge Inbetween dumps. It's possible you were right on the edge of your budget and that the extra cable length made it so that you were running out of juice.

The radio takes 14mA at maximum, usually a few nanoamps. It could be the capacitator from the power pins that's weak. The regulator ain't great.


text:
Arduino Controlling a stepper motor
How can I get an Arduino to do the following to a Stepper Motor installed on a "Lead-screw" attached to my table-saw's Fence?

Turn the "lead-screw" clockwise when I press a given button, UNTIL I release the button.
Turn the same "lead-screw" counter-clockwise, when I press another button, UNTIL I release the button.
Adjust a "speed" knob, to control the motor's speed when the fence is moving; from very fast to very slow; and even stop when the control is completely counter-clockwise.
Turn a switch off, which will remove all control to the motor; so I can turn the shaft manually without resistance, whenever I do not want the fence to be under control of the motor.

That is ALL I need.
It is that simple. So what do I need? What do I need to purchase? I am a novice.

First you need to figure out the mechanical requirement, ie, how big a motor and what drive voltage which is determined largely by speed, and even if you want to directly couple the shafts or use timing belts for reduction and to ease mounting tolerances - none of which are really an Arduino questions. 3d printer parts are applicable to a certain light load range and readily available to get a tactile sense of. For more substantial tasks the are a lot of more expensive solutions for CNC machine tools. The Arduino part sounds like a simple combination of a stepper sketch and an analog read one.

patdee, I edited your question and removed an irrelevant paragraph.  You can post such paragraphs on arduino.meta.stackexchange.com if you wish.

I've got to ask here.  Why use a stepper?
This would be fairly easy with two button switches and a regular DC motor.  One switch provides power to drive the motor CW the 2nd motor drives it CCW.
You would still need to choose a motor with the right torque but IMHO this method would be WAY easier than using a stepper, and arduino, writing code, etc.

We can't tell you what to buy. We can help you understand how it will work, though, and what you should look for.
First off you need a suitable stepper motor. We can't help you with that. You need one that will a) connect to your lead screw in some way, and b) have enough power to drive the screw.  Maybe the robotics stack-exchange can help you better with that.
Once you have identified your stepper motor you need a driver that can control it. There's two kinds of stepper motor - "unipolar" and "bipolar" and the type of stepper motor you have chosen will determine the type of driver you need. Suffice it to say if you have a "unipolar" stepper motor you need a "unipolar" driver.
In brief: a bipolar stepper motor usually has 4 wires and needs a pair of H-bridges to drive it. A unipolar stepper driver normally has 5 or 6 wires and just needs beefy MOSFETs to drive it.
Your driver will, of course, need to be able to provide enough current to drive your stepper motor. For the finer details of the driver the electronics stack-exchange will most likely have the most expertise.
One further thing you will need is a potentiometer (and fancy knob etc) to set the speed.
Then it's just a matter of "gluing" everything together through the Arduino and writing the software.
How you write the software for the Arduino depends on  the driver for your stepper motor. There are libraries with examples for most types. Adding in an analogRead(...) and map(...) to convert the voltage from the potentiometer into a speed should be simple enough.

Thank you user37968. But there are a number of reason why I want to use stepper motors. To user Majenko♦, I gave ALL you need to determine what I need. I used the word "TABLE SAW FENCE". It should be assumed that I have installed a lead screw on the fence. Any sawyer knows that the fence is moved to the left or right and mine takes VERY little effort; because it rides on roller bearings. All the stuff you gave me was FAR and way above what I need. Thanks anyway for trying. patdee

@patdee Well I am sorry, but we are electronic engineers and makers, not "sawyers" (what are they? Do you mean carpenters?) I, and many others here, have no clue what a "fence" is in this context. To me a fence is what separates me from my neighbours, and I don't want it to move. My answer contained all the information you need to know to use a stepper motor. If you don't want to know that kind of information then you are looking for a ready made product and you don't want to be asking about that here.


text:
How to I press a button once to display text and again to remove it?
My code is displaying voltage and I want to have a button that when pressed it displays a text and when I pressed it again it would turn off the text. I put the word "YES" just for a test
float vPow = 4.7;
float r1 = 1000000;
float r2 = 100000;
const int buttonPin = 8;
int buttonState = 0;
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  lcd.begin(16, 2);
  pinMode(buttonPin, INPUT);
  Serial.begin(100);
}

void loop() {
  float v = (analogRead(0) * vPow) / 1024.0;
  float v2 = (v / (r2 / (r1 + r2)))/.48;
  lcd.setCursor(0,0);
  lcd.print("V:");Serial.println(v2); lcd.print(v2); lcd.print("%");delay(100);
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    lcd.setCursor(0,1); lcd.print("YES");
  } else {
    lcd.setCursor(0,1); lcd.print("");
  }
}

What is wrong with your current code? Also Serial.begin(100) is not right. You should put specified baudrates (i.e 9600/115200).

replace lcd.print ("")  with lcd.print("   ") (3 spaces) to force deleting "YES" on LCD screen

You can try to use a variable which is used to save the last condition. (whether it displaying or removing in the last button-press event)
bool state=false;
bool pressed = false;

void loop() {
  float v = (analogRead(0) * vPow) / 1024.0;
  float v2 = (v / (r2 / (r1 + r2)))/.48;
  lcd.setCursor(0,0);
  lcd.print("V:");Serial.println(v2); lcd.print(v2); lcd.print("%");delay(100);

  pressed = false;
  while (digitalRead(buttonPin)) pressed = true; //wait the button to unpressed

  if (pressed)
    {
    state=!state;
    if (state) {lcd.setCursor(0,1); lcd.print("YES");}else
               {lcd.setCursor(0,1); lcd.print("   ");} //3 spaces. To erase 3 characters ("YES")
    }
}

You need to somehow debounce the button. Using a long delay in the loop
(your delay(100)) can do the trick, but it's probably not the best
way, as it will slow down anything that you may later add to your
program.
Better would be to write your own debounce function, or to use one of
the libraries that already implement that. For example, with
Bounce2, you would write
something like:
#include <Bounce2.h>

const int buttonPin = 8;
Bounce button;       // debounced button
bool textDisplayed;  // whether the text is displayed or not

void setup()
{
    button.attach(buttonPin, INPUT);

    // etc...
}

void loop()
{
    // Read and display the analog value, then...

    // Update the state of the debounced button.
    button.update();

    // Toggle display on rising edges of the button.
    if (button.rose()) {
        lcd.setCursor(0,1);
        if (textDisplayed) {
            lcd.print("   ");
            textDisplayed = false;
        } else {
            lcd.print("YES");
            textDisplayed = true;
        }
    }
}


text:
Design considerations for creating an Arduino 'shield' shield to limit EMI
I am building a shield that contains an AC power supply and relay for an Arduino-like board. The problem I am having is that the relay is quite noisy with respect to EMI, and I can see a few jitters or jumps in my system during normal operation even with a zero cross detector.
I have added in another shield between the 'relay' shield and the main board, which has helped the problem by creating a larger gap, but I would like a more permanent and robust solution.
I was thinking of building a simple shield that has nothing much on it and is simply a large ground plane that sits in between the relay shield and the main board. This would be a simple solution that does not involve making any shielding cages.
This ground plane would be connect to the chassis of my device, which is then earthed.
Since the device has both a DC ground voltage (0V DC) and a AC earth (0V AC) I was thinking maybe I should use both as part of my shielding. Since the board has layers on both sides perhaps I could design it to have the side facing the relays to be earthed, while on the other side, facing the CPU, would be DC ground. I could even couple the two planes with a capacitor, if it helps.
On the one hand I think the earthed option should be fine, but on the other hand I would like to know more about using the DC ground as an EMI shield. Would the simple earth only option work? Would even a DC ground only option work? Does it help to use the DC ground as an EMI shield for the DC components or am I over complicating it?

How are you detecting "a few jitters or jumps in my system"? Why do you think it is EMI rather than a voltage dip causing them? How are you powering the relay? Is it from the Arduino's 5V supply? The simplest explanation for most "jitters" around an Arduino is electrical rather than EMI.

It's a number of things, but mainly if I take away the AC I don't get the issues. Also as mentioned in the question if I move the shield further away I also don't see the issues. I can detect them as I have a sensor that goes offline when it encounters bad signals over the SPI bus.

Unfortunately your question has been migrated to a site where, IMHO, you might be less likely to get the kind of help you'd like.

What would be helpful would be explanation of the type of AC you are using and then possibly a schematic or board layout.
That aside, there does seem to be noise between the two boards. The Idea of placing a PCB with just a large copper pour would work.
DC Ground
If you connect the DC ground from the main board you should use a ferrite bead(FB) between the two grounds, this will ensure that you don't get noise getting back into the ground of the main board after you have tried to shield it. You should try to match the ferrite bead to the noise frequency you experiencing (use a scope if you have one).
Using the DC ground as a shield is often done, if you look at the EMI cages on cellular phones, WiFi modules, and other noise generating devices/susceptible-to-noise devices, they are connected to ground. It gives the noise somewhere to go, instead of your signal lines. Thus using the DC ground is defiantly an option
i.e.:
Main ground>--------[__FB__]-------<SHIELD

AC Ground
You could use the AC earth line on the top part of the shielding board. The coupling part might be a bit over kill, leave space for it to test to see if it helps when you make the board. Also AC earth can be used for shielding but is used for the safety aspect of earth leakage.
Don't do a direct DC ground to AC ground unless you know what you are doing as this will create a ground loop, this will change the way stuff behaves and will make your circuit no longer a floating device.
Other stuff
I would also make sure how you drive the relay is isolated from the control circuitry, although from what you describe:

if I move the shield further away I also don't see the issues.

If you share power rails between the relay board and the main board, try filtering the power going to the CPU section. Also the control lines can be isolated between the controller and the relay with opto-couplers, this might stop noise coming back into the circuit from the relay part.


text:
Is it possible to reduce the size of this program to 1KB
I want to use attiny13 in my project but this program is going over 1KB
void setup()
{
  Serial.begin(9600);
  delay(2000);
  Serial.println("AT+CMGF=1");
  delay;
}
void loop()
{
  for (int i=0 ;i < 1 ;i++)
  {
    delay(1500);

    Serial.print("AT+CMGS=\"");
    Serial.print("+918269394684");
    Serial.println("\"");
    while(Serial.read()!='>');
    {
      Serial.print("22.7010709,75.9372517");
      delay(500);
      Serial.write(0x1A);
      Serial.write(0x0D);
      Serial.write(0x0A);
      delay(5000);
    }
  }
}

"Serial" Well there's your problem...

There are several problems with your program as shown that make a good answer impossible.  After I list those problems, I'll then proceed to give an answer, partly good, partly bad.  The good part is that the 432-bytes-of-code program shown below should send all the indicated text strings, in the proper order and separated by appropriate delays.  The bad part is that it sends at 115200 bps instead of 9600.  Depending on point of view, it may be good or may be bad that the code doesn't look for absence of '>' on Serial input; as I note in discussion of problems, the original code's unclear.
As promised, here are several problems with your program as shown, and how to fix them:

The statement delay; is a constant expression [address of the delay() function rather than a call to delay()] so take it out.
The statement for (int i=0 ;i < 1 ;i++) is a do-nothing so take it out.
The sequence while(Serial.read()!='>'); { is confusing – it compiles but isn't something a rational programmer would write – so take it out.  (As written, with a semicolon directly between the right parenthesis and the left brace, it busy-waits until it reads '>' on Serial input.  Then the unnecessarily-blocked block of statements within the matched braces executes one time and loop() exits its current pass.  If the semicolon weren't there, the statements within the braces would execute repeatedly until a '>' appears on Serial input.)

Anyhow, with the minor fixes outlined above, and using the BasicSerial library from nerdralph's writing AVR assembler code with Arduino page, we get the following message for the program shown below.

Sketch uses 432 bytes (42%) of program storage space. Maximum is 1,024 bytes.  Global variables use 68 bytes of dynamic memory.

#include <BasicSerial.h>
char *text = "AT+CMGF=1\n\0"    "AT+CMGS=\"+918269394684\"\0"
  "22.7010709,75.9372517\0" "\033\r\n";
#define send(item) while (*item) TxByte (*item++)
void setup() {
  //Serial.begin(9600);
  delay(2000);
  //Serial.write("AT+CMGF=1\n");
  send(text);
  //delay;
}
void loop() {
  char *msg = text;
  delay(1500);          // took out `for`
  //Serial.write("AT+CMGS=\"+918269394684\"");
  send(msg);
  //while(Serial.read()!='>'); {
  //Serial.write("22.7010709,75.9372517");
  send(msg);
  delay(500);
  //Serial.write("\033\r\n");
  send(msg);
  delay(5000);
  //}
}

Program Notes:

The string text contains all the text from your original Serial prints and writes.  With the text organized as a single string, the program only needs to set its character pointer msg once per loop, saving perhaps half a dozen bytes of code.
The commented-out Serial.write statements are equivalents of your various Serial.println, Serial.print, and Serial.write statements, with adjacent strings lumped into single writes, thus for example using one write instead of three to write the Esc, CR, LF sequence just before delay(5000).  Just changing those printlns, prints and writes all to writes reduces code size  by about 150 bytes, which might be enough of a reduction to get you by, depending where you start from.  But in my tests, substituting BasicSerial in place of Serial saves over a thousand bytes so is likely to be a requirement.
You probably can modify the code in BasicSerial.S for other data rates, or perhaps can substitute one or another of the small Serial replacements listed in ernstc's Serial communication with the Tiny's webpage, to get different data rates and/or receive as well as transmit.

Edit:  As Edgar Bonet noted in a comment, an ATtiny13 has 64 bytes of RAM, so the above program (using 68 bytes of RAM) will fail.  RAM usage can be reduced by copying string characters individually from program memory, instead of copying the string into RAM (per Arduino default).  See the following revision of the program, which also corrects a problem (leaving msg pointed at a null byte) that would keep the former program from working.  Note, with these changes, we have:

Sketch uses 456 bytes (44%) of program storage space. Maximum is 1,024 bytes.     Global variables use 6 bytes of dynamic memory.

#include <BasicSerial.h>
#include <avr/pgmspace.h>
const char text[] PROGMEM = "AT+CMGF=1\n\0"
  "AT+CMGS=\"+918269394684\"\0"
  "22.7010709,75.9372517\0" "\033\r\n";
char *front = (char*)text;
#define send(item) while (pgm_read_byte(item)) TxByte (pgm_read_byte(item++))

void setup() {
  delay(2000);
  send(front);  ++front;
}
void loop() {
  char *msg = front;
  delay(1500);
  send(msg);   ++msg;
  send(msg);   ++msg;
  delay(500);
  send(msg);
  delay(5000);
}

“Global variables use 68 bytes of dynamic memory.” Since the ATtiny13 has only 64 bytes of RAM, you may want to put text in PROGMEM.

Nicely optimized! But I think like better static void send(const char * &item) { while (char c = pgm_read_byte(item++)) TxByte(c); }, as it avoids all the ++front and ++msg.


text:
Broken Loop and dim LEDs
I want to make 2 LEDs blink back and forth continuously, but they only do so once, and the second one is very dim.
code:
int ledone = 12;
int ledtwo = 10;
int keepgoing = 1;

void setup() {
pinMode(ledone, OUTPUT);
pinMode(ledtwo, OUTPUT);
}

void loop() {
 while (keepgoing == 1) {
  digitalWrite(ledone, HIGH);
  delay(80);
  digitalWrite(ledone, LOW);
  digitalWrite(ledtwo, HIGH);
  delay(80);
  digitalWrite(ledtwo, LOW);
  delay(500);
 }
}

I am using an Arduino Uno and one 220 ohm resistor for each LED.

i have corrected keepgoing == 1, instead of keepgoing = 1, please check now.

By "second one", do you mean one of the LEDs?  If so swap the leads to them and then report back if the same kind of dimness still occurs – maybe one of your LEDs is just dimmer than the other.  If the dimness swaps, then try changing ledtwo = 10 to  ledtwo = 9, ie to some other pin, and rewire accordingly – maybe one of your IO pins has a problem or your wires are loose.  Also try changing those fairly-short 80-ms delays to perhaps twice or three times as long.

@goddland_16, as a condition for an if, keepgoing = 1 will always evaluate as true,which will keep the while statement going.   keepgoing == 1 also will evaluate as true, given that  keepgoing  was initialized to 1.

swapping fixed my brightness, but how do I make my loop keep repeating, it only executes once :(

@JamesWaldby-jwpat7, yes, it is. For this context I assumed he meant it as keepgoing == 1.

it now looks like this:  void loop() {
while (keepgoing == 1) {
digitalWrite(ledone, HIGH);
delay(160);

it still does not run more than once.

NerdyDude101, is the following a correct description of what you see?  When you press reset, LED 1 comes on briefly and goes off.  LED 2 comes on briefly and not as bright and goes off.  Then both LEDs stay off until you press reset again.

yes that is what I see.

Ok, what happens if you delete while (keepgoing == 1) { and the matching closing } ?

it stays the same.

May be some hardware or wiring problem... I would next try things like the following:  (a) with both LEDs wired up, comment out the digitalWrite()'s for one LED at a time, and see if loop() works; (b) pull the wire to one LED at a time, and see if loop() works (ie take one LED out of circuit, run test, put the LED back in, take the other out, run test); (c) try higher-resistance resistors, in case something is wrong with the ones you have.   BTW, does the Blink example sketch, which uses built-in LED, work ok?  And did the 160-ms delays look twice as long as the 80's?

You don't need the while loop. loop() loops forever anyway.

Ok. This is really weird. My code looks like this:

void loop() {
while (keepgoing == 1) {
digitalWrite(ledone, HIGH);
//digitalWrite(ledtwo, LOW);
delay(500);
digitalWrite(ledone, LOW);
//digitalWrite(ledtwo, HIGH);
delay(500);

(of course it has proper spacing)

but both LEDs blinked on and then off once?!

I think the problem is, that your delays are just too short, so you see the blinking not as blinking, but as a dim lit led.
Maybe you can try the following code:
void loop() {
 while (keepgoing == 1) {
  digitalWrite(ledone, HIGH);
  digitalWrite(ledtwo, LOW);
  delay(500);
  digitalWrite(ledone, LOW);
  digitalWrite(ledtwo, HIGH);
  delay(500);
 }
}

Is this working?

I tried this code and each LED only blinked once. This is really confusing!


text:
Arduino ultrasonic distance meter doesn't display correct distance
The Arduino distance meter that I made doesn't display the correct distance. It just displays "0.0 inches".
Here's the code I used:
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int pingPin = 7;
int inPin = 6;
long duration, inches, cm;
int indec, cmdec;
int inchconv = 147;
int cmconv = 59;
String s1, s2;

void setup() {
  lcd.begin(16, 2);
  pinMode(pingPin, OUTPUT);
  pinMode(inPin, INPUT);
}

void loop()
{
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(pingPin, LOW);

  duration = pulseIn(inPin, HIGH);

  inches = microsecondsToInches(duration);
  indec = (duration - inches * inchconv) * 10 / inchconv;
  cm = microsecondsToCentimeters(duration);
  cmdec = (duration - cm * cmconv) * 10 / cmconv;
  s1 = String(inches) + "." + String(indec) + "in" + "     ";
  s2 = String(cm) + "." + String(cmdec) + "cm" + "     ";
  lcd.setCursor(0, 0);
  lcd.print(s1);
  lcd.setCursor(0,1);
  lcd.print(s2);

  delay(100);
}

long microsecondsToInches(long microseconds)
{
  return microseconds / inchconv;
}

long microsecondsToCentimeters(long microseconds)
{
  return microseconds / cmconv;
}

Here's the wiring diagram:

Might there be a problem in my code, or in my wiring?

Please provide more information. Like e.g. code and way you hooked it up.

I provided more informations

Tip for debugging this kind of thing: Print the raw values first to see if you are getting a valid ping, then if you are print each stage of the calculation until you find the failure.

please explain me it properly

Question: Does the variable duration contain a meaningful value?

Another question: Are you sure the ping sensor has power?

Do you have some basic tools like a DMM (digital (or analog) volt meter) or an oscilloscope?

Another piece of information that would be useful is to know the actual sensor that you're using.

Using Arduino and Ultrasonic sensor Find The Range and Display reading on LCD

To solve a problem like this you need to break it down into smaller pieces so that you can build up some confidence about what is working and what is not. When you share a problem like this as a question it helps if you can give us some idea of your experience level and of what you've already done to debug the problem – that helps with avoiding telling you what you already know and makes it easier to focus in on where the problem might be.
From what you've said it appears that you have things working well enough that you get a display on the LCD but it does not represent a meaningful distance.
Looking at your schematic the first thing that comes to my mind is that you have the ultrasonic sensor at the opposite end of the breadboard from the LCD. Many breadboards split their power rails at the middle. So start by confirming that you have power to the sensor.
After that, double-check the rest of your wiring.
The next step for me would be to confirm that I understood the sensor and to try and prove that it was working as I expected. Look for some sample code that is known to work (often the site you bought the sensor from will have links to beginning tutorials or code samples). Try that to see if the sensor works with the sample code.
If that doesn't work then check to see what you can do to prove the sensor is good (or bad). You might also contact the vendor to see if they can give you advice on proving that the sensor works.
Basically, break the problem down into "bite sized" chunks and work through it one step at a time, doing the simple stuff first. Try not to assume anything…

Maybe you should use the New Ping library and check if the sensor works without LCD:
https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home

I think you should first check it in simulation and for that install Proteus software and get this Ultrasonic Sensor Library for Proteus and then test your code in simulation.
Once you confirmed that your code is working fine then you can come to the hardware debugging but I think its more probably because of programming issues.


text:
Drive a 12V pump do I need a l293 driver
Me and my girlfriend are working on a small automatic plant watering system. Our first goal is to make an electrical 12V pump suck water out of a bottle.
As we were reading tutorials online we noticed that many people hook up a driver such as the l293 to their arduino in order to control the pump (essentially a brushed DC motor).
http://www.ti.com/lit/ds/symlink/l293.pdf
Our pump is 12V 4.2 W.
My question is do we really need a driver like that for just activating / deactivating the pump ?
In my understanding the driver offers an H-bridge setup allowing to control up to two motors in both directions.
Are there any other reasons to prefer this driver instead of a simple MOSFET / Transistor setup with such a simple use case like ours ?
Thank you for your help.
Best regards

Unless you wish to reverse the direction of the pump without reconnecting the wires in the opposite way, there is no need for a L293. A MOSFET that operates as a switch should be sufficient in your case. You can also try to PWM it and reduce/control the water flow.

I was considering PWM as well. I will go ahead and do some reading on it :)


text:
How the output of a bicycle dynamo can be displayed using Arduino?
I am on a project in which I need to make bicycle dynamo frequency meter.
The power generator’s output should vary with the speed of the wheel.
Which parts do I need to make it work?
The project should look like: : http://www.lanzo.se/experiments/dynamo/dynamo.html
                 or http://practicalphysics.org/bicycle-dynamo-and-oscilloscope.html
-->without oscilloscope ( which is replaced with Arduino and panel )

The power generator’s output WILL vary with the speed of the wheel, and the frequency / amplitude of the signal will vary as well. Are you attempting to measure and display the frequency of the bicycle dynamo "pulses" or do something else?

I want to measure period where voltage is measured along the y axis and time along the x.

The first thing to look at before you connect the bicycle dynamo to an Arduino is what type of signal / voltage it generates. The link you've provided: http://www.lanzo.se/experiments/dynamo/dynamo.html gives you the answer. It's an AC signal which varies between +4V and -4V (It could be much higher if you spin it faster). On the Atmega328P data sheet under "Absolute Maximum Ratings" it says "Voltage on any Pin except RESET with respect to Ground -0.5V to VCC +0.5V". Obviously, -4V exceeds the -0.5V maximum so don't connect it directly to an Arduino.
The signal from the dynamo to Arduino must be limited to between 0V and 5V (for an Arduino operating at 5V). The answer on how to accomplish this is a general electronics question and should be asked on a different forum e.g. https://electronics.stackexchange.com/questions/132330/8v-ac-signal-into-3-3v-digital-input-pin
The "frequency meter" part of your question is easy to build with an Arduino. You could use an Uno or something smaller like a Pro Mini with a 16 x 2 LCD display and this library: https://github.com/k3ng/k3ng_antenna_tuner/tree/master/libraries/FreqCounter. An I2C backpack for the LCD is only a dollar more and makes the wiring much easier. To use the backpack you'll need this library: https://github.com/marcoschwartz/LiquidCrystal_I2C.

It al depends on what is the maximum output of the dynamo.

less than 5V (not likely): great just connect it directly with the Analog measuring pin of the Arduino (A1- A7)
more than 5V: we got different options here

Make a simple voltage divder to measure the output
use an external ADC

I have old bicycle with dynamo but not sure what the dynamo voltage actually is. I'm prefering "more than 5V".

Also, I'm beginner in this and describing the process would help me the most.


text:
Help with button library, hold>2s doA else doB
I'm using JChristensen's Button Library to debounce my buttons and provide extra functionality.  I'm trying to use his press & hold function to do something if the button is pressed and held for greater than 2 seconds.  If it is just pressed momentarily it should do something else.  His example use switch cases, and I couldn't get it to work.  Here is my example that currently doesn't work.
    #include <Button.h>
    #include <SPI.h>
    #include <printf.h>

    // Keypress state setup
    byte clearPin = 16; // Clear pin

    #define PULLUP true
    #define INVERT true // Since the pullup resistor will keep the pin high  unless the
    #define DEBOUNCE_MS 20 // A debounce time of 20 milliseconds usually works well for tactile button switches.
    #define LONG_PRESS 2000 // We define a "long press" to be 2000 milliseconds.
    unsigned long ms; // The current time from millis()
    Button clearBtn(clearPin, PULLUP, INVERT, DEBOUNCE_MS); // Declare the button
    int score=1;

void setup ()
{
  pinMode(16, INPUT_PULLUP); // Pin for clear button
  Serial.begin(9600); // Radio Setup
}

void loop()
{
 clearScore(); // sets both home and away scores to 0 or enters settings menu
}

void clearScore()
{
  ms = millis(); //record the current time
  clearBtn.read(); // Read the button

  if (clearBtn.pressedFor(2000)) {
    // Enter settings menu
     Serial.println("Settings Menu");
     while (clearBtn.read()!=1) {

     } // End While
   return; // Hopefully not proceed down to the next if
  }
  if (clearBtn.wasReleased() && !clearBtn.pressedFor(2000)) {
    score=0;
    Serial.println("Clearing Scores");
    delay(50);
  }

}

Can anyone help please?  My serial output repeats "Settings Menu" over and over.  Once I let go of the button variable1 always gets set to 0.

No it was an example of what my code was.  I was hoping for someone to write something generic and I'd learn and adapt from it.  In any event, I have included the full code now.

user1229925, I edited the question (selected code and pressed ctrl-k to code-format it; changed word 'Entering' to 'Setting' after the code; crossed out variable1, not knowing what it should be.  Does the "Clearing Scores" msg ever appear?

So it's supposed to work like this:  1) hold button down for 2 seconds to enter settings menu.  While in settings menu ill code other stuff.  STAY in settings menu until the clear button is pressed momentarily again.  Once you press clear button again from being in the settings menu, the score should NOT be reset, and it should just return to the main loop.  2) if the clear button was not pressed for more than 2 seconds, just clear the score.  Does that help @jwpat7 ?

My earlier comment about the action of the code had numerous incorrect parts, so I deleted it.  See my answer below.

The loop() and clearScore() code that you have is like the following.
void loop() {
  clearScore(); // sets both home and away scores to 0 or enters settings menu
}
void clearScore() {
  ms = millis(); //record the current time
  clearBtn.read(); // Read the button
  if (clearBtn.pressedFor(2000)) {
    // Enter settings menu
    Serial.println("Settings Menu");
    while (clearBtn.read()!=1) {
      // do stuff
    } // End While
    return; // Don't proceed to next if
  }
  if (clearBtn.wasReleased() && !clearBtn.pressedFor(2000)) {
    score=0;
    Serial.println("Clearing Scores");
    delay(50);
  }
}

When you reset the Arduino and then hold down the clearBtn, clearScore() will be called repeatedly. clearBtn.pressedFor(2000) will not be satisfied during the first two seconds of holding the button down, and clearBtn.wasReleased() will not be satisfied either, so clearScore() will do nothing during the first two seconds.
After the first two seconds, "Settings Menu" will be sent repeatedly:  clearBtn.pressedFor(2000) is true, so the first if succeeds each time clearScore() runs, and it will run repeatedly because it is called from loop().  The while test, clearBtn.read()!=1 [which in more-idiomatic C would be written as !clearBtn.read()] fails until the clearBtn is released, so the while loop does nothing.  Also, clearBtn.wasReleased() will be false, so the other if does nothing.
When the button finally is released, clearBtn.pressedFor(2000) goes false, so the first if fails and the second executes one time.
Here is some code that should act more like what you want, as expressed in your comment,

It's supposed to work like this: 1) hold button down for 2 seconds to enter settings menu. While in settings menu I'll code other stuff. Stay in settings menu until the clear button is pressed momentarily again. Once you press clear button again from being in the settings menu, the score should NOT be reset, and it should just return to the main loop. 2) if the clear button was not pressed for more than 2 seconds, just clear the score.

void clearScore() {
  ms = millis(); //record the current time

  while (clearBtn.read()) {
    if (clearBtn.pressedFor(2000)) {
      Serial.println("Settings Menu"); // Announce Settings menu
      while (clearBtn.read()) {}       // Await button release
      while (!clearBtn.read()) {       // Await button press
        // do  Settings menu stuff here
        // (possibly wait for clearBtn release, to
        // avoid immediately clearing score again)
      }
    }
    return;
  }

  if (clearBtn.wasReleased()) { // See if released, after short press
    score=0;
    Serial.println("Clearing Scores");
    delay(50);
  }
}

Edit edit: To avoid  resetting the score at every settings exit, in the above code replace
        // (possibly wait for clearBtn release, to
        // avoid immediately clearing score again)
      }
    }

with
      }
    }
    while (clearBtn.read()) {} // wait for the settings-exit clearBtn release
    clearBtn.read(); // Do another read to avoid clearing score on next clearScore()

That is, right before the return, wait for clearBtn release, and read it again to be sure later reads won't register a release.  The latter read might not be needed, because clearScore() does a read when it tests the first while condition; you could experiment.

I think 2 seconds is way too long; half a second might be a more reasonable transition from ordinary press to long press.

Wow.  This works great!  Thank you for the thoughtful explanation next to everything.  It unfortunately resets the score every time you exit settings, but other than that I'm much closer then before.  How do I ever repay you.

See edit about avoiding that  reset.  Feel free to accept answer (click some green button) and upvote.

That edit at the end didn't end up working.  Can I paypal you to help finish?

I'm too busy to accept more work at the moment.  I imagine the problem at the end was the two lines being before } } instead of after; see re-edit.

moving that made no change as did removing them completely.  I'll keep trying to figure something out.It's almost as if the return; isn't working.


text:
Sending data over TCP connection in one piece
I'm trying to send short strings via Java client to Arduino server and vice versa. Sending data to client goes fine, but when I try to send data to arduino it cuts the string into bytes and then sends the first letter.  Will the following work?
for(int i = 0; i < data.length(); i++)

Even if it can be sent as characters I want to send it in one piece, because strings are very short so there should be no problems with length.
EDIT: Alright, I read client.read() documentation, so the problem is at arduino.
This is my java code:
public class TCP {
static Socket clientSocket;

public static void main(String args[]) throws Exception {
    clientSocket = new Socket("10.10.10.57", 5000);
    sendToServer("HAI THERE\n");
    String msg = getFromServer();
    System.out.println(msg);
    close();
}

static void sendToServer(String msg) throws Exception {
    //create output stream attached to socket
    PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
    //send msg to server
    outToServer.print(msg + '\n');
    outToServer.flush();
}

static String getFromServer() throws Exception{
    //create input stream attached to socket
    InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
    BufferedReader inFromServer = new BufferedReader(isr);
    //read line from server
    String res = inFromServer.readLine(); // if connection closes on server end, this throws java.net.SocketException
    return res;
}

static void close() throws IOException{
    clientSocket.close();
}
}

This code sends only one byte at the same time.It might be problem in my arduino code, since I read it with
char c = client.read()

One more thing. If there is any java master, I would like to know what to do with exceptions. How should I handle disconnected socket, failed connection to server, and so forth?

The problem is, that "char" is just one character. So you have to build your return out of the chars... if you want to use the "client.read()" function.
String res = ""; //this will be the resived msg after the loop
do {
   char c = client.read(); //c will be -1 if no byte is left
   if(c!=-1)
       strcat(res, String(c)); //Append the char to the result string
} while(c!=-1);

//Code is not tested!!!
To your java problem... just put your code parts into try catchs not whole functions (remove it for the function and add it on the points eclipse tell you to). So you can react to each error individually. Then put client stuff in a own thread so it not blocks any other stuff. Every disconnect or faild connection will throw an exception if you dont catch it with an if. So you have to handel it their (try to reconnect or something)
EDIT:
static void close() {
    try {
        client.close();
    } catch (IOException e) {
        system.out.println(e.toString()); //Print the error or do something else

    }
}

great, thank you, it should probably work! soooo, for example: static void close() throws IOException, I delete IOException, and do it in main method?

I put some example code in my answer above.


text:
Overheating Shift-Register(74HC595)
I am working on a project where I need to use around 50 LED's connected to an Arduino UNO board. To begin with i worked on the tutorial provided by Arduino (https://www.arduino.cc/en/Tutorial/ShiftOut) to connect two shift registers(74HC595). Everything works fine, but the shift registers get very hot in just a few minutes. Is this normal?

Check the specs to see how much amps they can drive. Increase the current limiting resistance or buffer the signal using transistors if needed.

Calculate the total current driving your LEDs, and compare to the 74HC595 datasheet about the maximum driving current it can source. You may need to drive the LEDs with larger current-limiting resistors, or use the shift register to control transistors that do the actual switching. For example, the TI SN74HC595 (http://www.ti.com/lit/ds/symlink/sn74hc595.pdf) has an absolute maximum continuous current through Vcc or GND of 70mA.

@josecanuc Yeah I think I drawing too much current than it can provide. Thank you:)

That tutorial has many errors. You should ignore it and find a better one. There is a post here somewhere about all the things wrong with it.

Here's the post I mention: https://arduino.stackexchange.com/questions/39827/is-the-shiftout-tutorial-on-the-official-arduino-website-really-wrong-regarding

I can only think about two things:

(least probably): the entrance (VCC) voltage is too high.
(most probably): the resistors to the LEDs are (too) low .. Recalculate the values and check the max amperes which can be handled by the output pins of the shift registers.

Yeah the problem was with the LEDs having too low resistance. Thanks a lot:)

You are welcome ... you can accept / upvote the answer to let others know the problem has been solved.


text:
Additional Digital Input Pins
I require additional digital input pins for 5 PIR sensors. Can I use the shift register (74HC165) to read these input? And will I be able obtain real time values from all the 5 sensors?

Did you know you can use the Ax (A0, A1, A2, etc.) pins as digital inputs also? Or have you already used all of them?

Yes I have used all if them

Yes, a shift register will work fine if "real time" is on the milli-seconds level. Calculate the time to access the shift register input.

If you don't care about which sensor triggered, you could use an OR-gate.

You could use a GPIO expander (MCP23017 or similar) which could give you 14 extra pins (16-2 for I2C bus), but this is putting extra load on the microprocessor.  (you haven't said which one by the way).
Or another option might be to revisit you design and see if you can split it out to multiple processors.  This is effectively the same as a GPIO Expander, just using an Uno or ESP8266 as the expander.

I will look into the GPIO expander.

I am using an arduino uno by the way. Sorry didn't mention it. Thank you:)


text:
Save a fingerprint to the database of the fingerprint sensor
I'm using the Adafruit Kookye fingerprint module in my project. Since it can only allocate 256 fingerprints I need to make a program to free the memory and add additional users. I have made the following function at the library:
uint8_t Adafruit_Fingerprint::downloadModel(uint16_t id, uint8_t packet_1[], uint8_t packet_2[], uint8_t slot) {
  uint8_t packet[] = {FINGERPRINT_DOWNLOAD, slot};
  writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet);
  uint8_t len = getReply(recvPacket);

  if ((len != 1) && (recvPacket[0] != FINGERPRINT_ACKPACKET))
   return -1;
  if (recvPacket[1] == 0x00) {
    writePacket(theAddress, FINGERPRINT_DATAPACKET, sizeof(packet_1)+2, packet_1);
    writePacket(theAddress, FINGERPRINT_DATAPACKET, sizeof(packet_2)+2, packet_2);
    return recvPacket[1];
  } else {
    return recvPacket[1];
  }
}

This function is working, it puts the fingerprints to the buffer 1 and when I call the function to save with the ID it also works. When I print the fingerprints in the sensor, the structure is exactly the same as if they had been added directly from enrolling. However, when I serach the fingerprints the sensor always returns that the user does not exist.
I don't know what's the problem.

Don't cross post. Delete your other question on SO.

The sizeof() operator doesn't do what you think it does. It's not a function that is executed at runtime, it's an operator that is interpreted at compile time.
It takes a variable and returns the size (in bytes) of that variable. Since you are passing it a pointer it gives you the size of that pointer. That's 2 bytes on an 8-bit system like the Uno.
In C an array is not a single entity with a size. It's a pointer to a block of memory that has been reserved at the time the array is declared. All you get is that pointer, and it's up to your program to remember the size.
You will have to pass the size of the arrays your packet_1 and packet_2 pointers are pointing to, or always assume that those arrays are the same size at all times.


text:
Project structure to build for PC and Arduino
Recently I have started developing for Arduino Uno. I have 10 years experience in software development (C#, Delphi), but not much with C/C++.
Compiling the Arduino sketches seems a little slow, and debugging isn't as convenient as it could be on a PC (compile, upload, watch the serial monitor, modify code, start over.... way too slow with lots of unnecessary steps)
So what I would like to achieve is to organize my code in a way to be able to compile my code either to Arduino, or to PC for debugging purposes (to a small console app). I know that there are libraries that cannot be used on a PC, but those can be abstracted away (hidden behind a facade or something like that). Unfortunately I could not find any tutorials, or articles how to do this. So I hope you can help me out.
BTW I'm using Visual Studio (with Visual Micro) on a Windows 10 computer.

With abstractions as I said. Of couse those stuff won't work on a PC but for example a led can be replaced with a Console.WriteLine. Sensors are providing data in a form of bytes/bytearrays, which can be faked with abstractions. With fakes the logic can be built/validated on PC much more faster than with a real board.

What you're looking for is an Arduino Simulator. I seem to recall people doing it Proteus, but don't quote me on that. It's something like that anyway.

This may help: http://www.instructables.com/id/How-to-Simulate-Arduino-in-Proteus/

I haven't done it yet, but you could do the following things to get a somewhat close approximation:

Make three different projects, one for the PC (only), e.g. Visual Studio, and one for Arduino (with the default Arduino IDE or e.g. Visual Micro). The last will be a generic library to be used for both the PC and Arduino.
Use the Arduino specific libraries only for the Arduino project.
Create facade/wrapper classes for each Arduino library.
Use a mock/stub for the Arduino libraries in the PC only project.
Put all non-hardware related code in separate classes, to be used by both projects.
Write unit tests for the PC only project.
The PC project will be tested by unit tests, and can be debugged on a PC
Only the specific Arduino libraries/interfaces have to be tested using the 'hard way', e.g. with Serial.

So the projects (including testing) will look like:

PC Project

References common code
Stubs for Arduino libraries, stubs can possibly be reused by PC Unit tests

PC Unit Tests

Unit tests
References common code

Arduino Project

Containing Arduino libraries
References common code

Common Code

All domain specific classes


text:
Use command line to upload program through hex file to Teensy-LC
I want to make a standalone programmer for Teensy-LC in windows 8.1.
So basically I have provided the board to a client of mine and now I want to change the program loaded into the Teensy-LC board.
But the solution available right now is to send the Teensy Loader and send the hex file. But the teensy LC board is packed inside a device. So reset button cannot be pressed.
Also it would be better if this code can be burned in an installer format instead of the Teensy Loader.
Is there any way to make this work?
EDIT
My Teensy.exe does not have the option for program or reboot
The icons are not accessible

Does that mean my interrupts are disabled or there might be something else I am doing wrong?
My program loads on pressing the reset button but I cannot press the program button inside Teensy.exe
If I turn off the Auto Mode, all icons go grey.

Paul Stoffregen (Teensy creator) has released a command line version of the Teensy Loader which can be found on his website. However, this program appears to be Linux only, so unless your client has Linux, that may be a non-starter. The source code for the program is available, so you might be able to work out the logic and port it over to whatever platform you are wanting this to work on (just make sure you comply with the source code license).
All that being said, pressing the reset button is not necessary for programming. The Teensy loader should be able to trigger a reset over USB all on its own. So unless the current program on the device disables interrupts that are necessary for the USB port to function, or it was programmed with the USB port disabled (by selecting "No USB" in the USB Type menu), physically pressing the reset button isn't necessary for programming. For more details you can see this forum post.
Loading Firmware Without Pressing the Button
When programming via Arduino, it does a lot of things for you automatically. To replicate that manually, follow these steps:

Connect the Teensy to the computer via USB.
Run teensy.exe (found in C:\Program Files (x86)\Arduino\hardware\tools)
Click the button on the left to select the hex file to load.
Go ahead and leave Auto enabled (this actually doesn't matter).
Run teensy_reboot.exe (also found in C:\Program Files (x86)\Arduino\hardware\tools, this will restart the Teensy, as if you had pressed the button, and automatically start the programming process.)

I have editted my question explaining the problem I am facing. It would be great if you could help me out with what I am doing wrong in my present method.

@newbie2015 They are disabled because you have auto mode turned on. Click the green auto button and they will enable.

I turned off the auto mode. Now all the icons go grey

@newbie2015 I have added instructions, I was trying to describe it from memory (as I didn't have a Teensy handy) and I got it wrong. I got a hold of one and the correct process is described above.

Works perfect with this
But is it possible to make a bootloader without opening the Teensy.exe? Like it is possible that I send an installer from my end like a software update and the client does not have to go through loading the hex file himself. Have the hex file embed in the installer that I sent. Is that possible?

"pressing the reset button is not necessary for programming": This sentence is wrong if you have previously loaded a sketch to the Teensy which is compiled with USB Type: "No USB". The automatic reboot will only work if USB is running in the Teensy.

Sadly the accepted answer is incomplete and requires manual steps.
The reason why your "Auto" button is greyed out is that you did not execute the second executable that is required for that: "Teensy_Reboot.exe".
You find it on your disk if you have installed TeensyDuino.
First kill Teensy.exe if it is running (Important)
Then you write path and file of your Hex file into the registry:
HKEY_CURRENT_USER\Software\PJRC\teensy\dir
HKEY_CURRENT_USER\Software\PJRC\teensy\file

Then you start Teensy.exe
Then you start Teensy_Reboot.exe as a hidden process.
That is the solution of your problem!
It is a shame that Paul does not document his stuff.
NOTE: If you have previously loaded a sketch into the Teensy that was compiled with "USB Type: No USB" the reboot will not work and the button on the board must be pressed manually, but Teensy_Reboot.exe is still usefull because it enables the green "Auto" button in Teensy.exe.
NOTE: Teensy_Reboot.exe has a severe bug: If the Teensy.exe is not successfull because another program still had the Teensy CDC COM port open while you started Teensy.exe, the Teensy_Reboot.exe may run eternally consuming 100% CPU under some circumstances. I reported that bug in the forum of Paul but he never answered to my posting.

PLAN B:
The disadvantage of using teensy_reboot.exe is that you don't know if the programming was successful or not because sadly teensy_reboot does not return any usefull exit code.
So the better option (which requires more code) is to instruct Teensy.exe directly from your program. Therefore you need a TCP connection to localhost.
You find more details in this thread:
https://forum.pjrc.com/threads/38684-How-does-Teensy-Reboot-exe-communicate?p=120443
where Paul (once again) did not answer my question.

PLAN C:
You can even replace Teensy.exe with your own code.
Have a look at this project: https://github.com/Koromix/ty
Sadly this code depends on the huge QT library. Apart from that it may not work with future versions of Teensies.


text:
Issue with Serial PINs (RX/TX) on Arduino
I have an issue with an Arduino Nano.
I want to communicate with it through the Serial-Port. Meaning I want to send and receive Serial commands. With USB and the "Serial Monitor" this works nice.
Now I have connected the COM-Port of the PC with Adruinos Digital Pins 0 and 1 (RX and TX) and a GND PIN. (3 Cables total).
Here is a minimal example of my Code:
void setup() {
  Serial.begin(9600,SERIAL_8N1);
  Serial.println("Start");
}

void loop() {
  Serial.println("Hello World");

  delay( 1000 );
}

The Serial Monitor says:
Start
Hello World
Hello World
Hello World
Hello World
...

Putty however says:
▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒::
                                                     ▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒    ▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*

Putty is connected with
- BaudRate: 9600
- Data Bits:
- Stop Bits: 1
- Parity: None
- Flow Control: None
What is wrong here?
Update:
The PC has a 9-pin D socket (Image)
This is connected to a RS232 to RJ45 connector (image)
From the RJ45-Cable I used the Brown, Blue, and White/Green Cable to connect with the Arduino

Is this a 9-pin D socket built in to the PC?

I have updated my question

RS232 is not TTL. You need a level converter. For more details see https://www.sparkfun.com/tutorials/215.

Thanks. That's it! I just found it in the documentation: "Don't connect these pins directly to an RS232 serial port; they operate at +/- 12V and can damage your Arduino board." https://www.arduino.cc/en/Reference/Serial


text:
Sending IR (NEC)-Signals with Arduino
I have an Arduino Micro where I want to control a display with IR commands. So the Arduino should send the IR commands to the display.
I have found a library "Arduino-IRremote", which I am using to transmit Commands to the display. The display works perfectly with its remote control, however I can't get it accept signals from my Arduino.
Now the special part about my setup is, that I do not use a "classic" IR transmitter. Instead i uset an IR cable, which is connected to "IR-In" of the display. So no LED - only a wired connection. The IR-cable consists of 3 wires. 2 for power supply (VIN and GND) and one is for the data connection. The wire with the data connection is connected with the Arduino PWM pin 3 (like it is said on the example in the linked library), but I tried all other pins anyway.
#include <IRremote.h>
IRsend irsend;

void loop() {

  for (int i = 0; i < 2; i++) {
    digitalWrite(RXLED, HIGH);
    irsend.sendNEC(0x004eff71, 32);
    Serial.println( "sendNEC 00 4E FF 71" );
    digitalWrite(RXLED, LOW);
    delay(40);

  }
  delay(1000);
}

004eff71 is a NEC-Command from the original remote control
Now can somebody tell me, what I'm doing wrong? The program compiles and the LED lights up, everytime it should send the NEC-command. But still the display receives nothing.
What is wrong?

It isn't working probably because the output of the Arduino isn't simply an on/off signal.
That library uses a pulse width modulated output on the Arduino to drive an LED.  When the LED is "on" the signal driving it is actually pulsing at a very high rate.
I don't know what all you'd have to change to make that work with a direct wired connection.
Another thing that might becausing problems is that without checking, you can't be sure that the signal level you are sending matches the levels that the IR receiver would normally produce.

It would help to know the specifications of the IR input on the device you're trying to control but after a bit of googling it looks like most of them are just expecting a connection to an IR receiver. I found a link to what appears to be a common one, TSOP22.., TSOP24.., TSOP48.., TSOP44.. and here's a link to the data sheet (http://www.vishay.com/docs/82459/tsop48.pdf). If you check the Vo on page 2 it shows 0-5V. You didn't mention if you're using a 5V or 3V Arduino so that could be an issue.
The PWM outputs do in fact generate square wave signals so at first glance this does not look like a hardware issue (assuming it is wired correctly for the IR input on your equipment).
I'd start taking a look at the data you're trying to send. I haven't looked into the library you mentioned and hopefully it contains a sample to show how to properly initialize the library and send data. Maybe instead of first byte first it needs to be sent first byte last or requires a fixed number of bytes to send...
Providing more details about your project you might get a better answer.