text:
Send text according to an ultrasonic measurement, on battery
I have this big bucket where I would like to install an arduino on the top of the bucket where it would calculate the % of the bucket being filled up with water. Then, every day at night the arduino will send a text message (via SIM card) to the server where it would collect data for that bucket.
As far as a beginner point of view, I can understand that I will need:
an Arduino Board
PING))) Ultrasonic Distance Sensor
Battery pack that would allow to run the board for a year?
and the Arduino GSM Shield (integrated antenna) OR the GSM/GPRS Module M10?
My question is:
What arduino board do I need for my setup?
How long will 2 large or 4 AA batteries lasts for receiving a value from the ultrasonic sensor once a day and sending that value to a server? The point of the instrument is to be as small as possible.

You'd probably need more than 4x AAs, as that's only 6V. The regulator on the Uno needs at least 7 to function correctly, so say 6x AAs. My Uno uses about 25mA, so that battery pack would -- as a generous estimate -- last about 3 days. Unless you could put the GSM shield and sensor into a low-power state they would shorten that time. I agree with Tom below when he says to consider solar power and rechargeable batteries.

Related: http://arduino.stackexchange.com/q/501/37 and http://arduino.stackexchange.com/q/488/37

First of all: what is the intention of your setup? What are you trying to measure, what do you want to do with the data? Where is the bucket located, in your backyard or miles away in a forest?
I foresee some problems with your current setup.
First of all, you need a enclosure that keeps your 'duino and other components dry and at a comfortable temperature. I don't know how severe the weather conditions are, but stuff can get unreliable when used close to the min/max operating temperatures. Can you find an enclosure that can protect your electronics against the elements?
My advice: think of a good enclosure.
Second, do you really think PING))) is the best sensor? Have you already tested how it behaves around water? Are the measurements correct?
Another option would be an array of metal strips, one connected to +V or GND, the others to separate ports on your Arduino. Space them evenly from the bottom of your bucket to your maximum water level (drill a hole in the bucket to prevent overflowing or drowning your duino). Poll the pins at a predefined interval (not too short, keeping battery life in mind) to see which ones make contact with the water (allowing current to flow from/to the pins from/to +V/GND)
My advice: do some research on sensors, or try to make your own
The best way to communicate with your 'server' (what are you going to use?) totally depends on how far it is from the bucket. GSM shields are quite pricey, other alternatives may be preferable (and do not have additional phone costs).
Is your server on the other site of the window? Bluetooth? Somewhere in your backyard? Zigbee. Across the street? High-power Zigbee (if allowed by local authorities). Far away but with WIFI access? Zigbee, posting data to an online place. In the middle of nowhere but with great cell phone reception? GSM.
My advice: check out wireless communication possibilities. There's a ton of them, each with pros and cons.
Last hurdle, energy. Your battery setup will most definitely NOT be able to provide enough energy for a whole year. There's just too little juice in them.
Arduino and standalone AVRs often have a sleep mode, in which power consumption can be very very low. Google is your friend on this one. Still, that won't let your setup last a year.
Unless there was a gigantic glowing ball of plasma hanging around some 8 lightminutes from here and we could harness its incredible power with the use of photovoltaic elements... Wait, we totally can! Using (a) solar panel(s) and some simple circuitry you can recharge your batteries, and depending on the weather conditions this could keep your project up and running for a year.
My advice: get down and dirty with small solar panels.
I really appreciate your ambition. If done right, this could be quite the project for a beginner! Just make sure you thoroughly research every part of the system, on itself and as a whole. This could prevent a lot of disappointment and unnecessary costs, while only expanding your knowledge.
Good luck!


text:
Arduino Mega XBee Limited inputs
I'm currently using an Arduino Uno with the Wireless SD shield with an XBEE attached so I can wirelessly send voltages from sensors to a computer. This works great but I am limited to 5 analog inputs. I am thinking of using a Mega but the Wireless SD Shield is the same for both models. Are there any shields/techniques were  I can wirelessly transmit up to 15 analog inputs to a PC using XBEE or otherwise,
Many Thanks,
AH

Why 5 inputs? The Uno has 6. (A0 to A5).

Sorry I meant 6!

See 74HC4051 multiplexer / demultiplexer. That describes how you can use a multiplexer chip to multiplex analog inputs.
The 74HC4051 multiplexes 8 inputs into one, and the 74HC4067 multiplexes 16 inputs into one. Thus you would only use one analog input, plus 3 or 4 pins to tell the chip which input you want at a particular moment.
The general way a multiplexer works is like this:

By outputting a binary pattern to the A/B/C pins you select which input you want active at a particular moment. That is then copied to the output pin (pin 3 in this case). You would connect that to your analog port on the Arduino.
The code would rotate between each of the 8 pins (or 16 pins with the bigger chip), and then do an analogRead.

Example wiring

Example code
// Example of using the 74HC4051 multiplexer/demultiplexer

// Author: Nick Gammon
// Date:   14 March 2013

const byte sensor = A0;  // where the multiplexer in/out port is connected

const byte addressA = 5; // the multiplexer address select lines (A/B/C)
const byte addressB = 6;
const byte addressC = 7;

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Starting multiplexer test ...");
  pinMode (addressA, OUTPUT);
  pinMode (addressB, OUTPUT);
  pinMode (addressC, OUTPUT);
  }  // end of setup

int readSensor (const byte which)
  {
  // select correct MUX channel
  digitalWrite (addressA, (which & 1) ? HIGH : LOW);
  digitalWrite (addressB, (which & 2) ? HIGH : LOW);
  digitalWrite (addressC, (which & 4) ? HIGH : LOW);
  // now read the sensor
  return analogRead (sensor);
  }  // end of readSensor

void loop ()
  {
  // show all 8 sensor readings
  for (byte i = 0; i < 7; i++)
    {
    Serial.print ("Sensor ");
    Serial.print (i);
    Serial.print (" reads: ");
    Serial.println (readSensor (i));
    }
  delay (1000);
  }  // end of loop

That only does 8 ports, but the 16-port chip would be conceptually similar.

source: Stack Exchange

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

sort: votes


text:
Motor Shield StepMotor

What the two yellow cables as you can see in the picture do not know?

There are two types of stepper motors: unipolar and bipolar. Bipolars usually have four wires and unipolars have six.

--http://hobbymilling.com/wp-content/uploads/2011/05/Unipolar-stepper-motor-windings.png

--https://www.codeproject.com/KB/system/steppermotorcontrol/pic6.jpg

The motor shield is designed to drive a bipolar motor (4 wires) but the motor is unipolar (6 wires). As you can see in the pictures, if you ignore the middle wire of the unipolar motor, it is the exact same as a bipolar stepper motor.

Here is the link from the original answer that you rudely deleted. You will read that there is a difference between the two http://digital.ni.com/public.nsf/allkb/C4A024DA9F197E6286257BC8005DC236. I also +1'd the querstion because you or someone else -1'd it unfairly. It's a good question!

@VisualMicro please read the comment I left on your answer: “Whilst you link may answer the question, it would be preferable to include the essential parts of the linked here, and provide the link for citation. I've deleted this answer for now. Feel free to add another answer. Thanks! –  Annonomus Penguin♦ 3 hours ago”

I read your message and think my post gave an accurate answer which is a link to a very simple overview. You deleted my post and added an incorrect answer. You seem to be purely interested in gaining points for your Annonomus account. You should be brave, tell people who you are, stop deleting correct answers to gain points and give accurate responses.

Please see the stack exchange policy on link only answers: http://meta.stackexchange.com/q/225370/190823. Your post basically said "there are two configurations, both outlined HERE." If you have an issue, please create a meta post where I and I (and the rest of the community) will be happy to discuss this further. Until then, please post an answer here that is valid without any links that is the correct answer. Thanks.

See above I already posted the link. I think the policy requires accurate answers 1st. It's a long answer and best read via the link I posted. I won't be adding another answer I think the user has the answer now. I am not here to waste people time.

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

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


text:
Arduino Mega vs. RasPi Pro Cons in 3D Printing
Recently I tooked a look at cheaper China 3D Printers and noticed they're all based on RepRap (mostly using Ramps for the electronics part) and the next day i saw a 2d Plotter based in the pi. Then I asked myself why the Pi isnt used in 3d printers.
Question:
Why is the Arduino Mega/Due more used in 3D Printing than the RasPi? What are the Pro's and Con's for 3D Printing on the two systems?

Hard realtime is more difficult when you can't get the full specs for the main processor.

A mutli-tasking operating system such as the Linux normally run on the pi is not particularly suited to doing hard real-time control such as coordinated pulse generation for multiple stepper motor axis trying to move as quickly as the rigidity and motor power will permit.
It is possible to use realtime extensions to the Linux kernel to get reasonable performance.  And it is also possible to run something simpler than Linux on the pi.
However, it is also possible to use a far cheaper processor to get the actual G-code execution done (you don't really pay the Arduino cost premium when buying an ATmega on a dedicated board, so it's only a  dollar or three more expensive than it "should be").  If one were to design printer electronics from scratch today, there are probably better choices, such as as ARM Cortex M0, M3 or M4 - but most of the printer designs came out of the same community where Arduino was a familiar choice, and there are probably more people willing to try to make small personal customizations to an Arduino codebase than there are willing to install the toolchain for a perhaps technically better, but less familiar solution. .
People do use Raspberry Pi's with 3d printers quite frequently though - they just use them for a different job: that of slicing and motion planning and potentially functioning as a network print server, which then drip-feeds the G code to the simpler (ATmega or whatever) based realtime executive.  In effect, they use a pi as a cheap PC to host the ATmega-based printer, rather than dedicating an old PC to that job.
Ultimately, the rarely taken alternative of using a realtime Linux kernel extensions to control motion directly from a pi, vs the more common one of using an ATmega as a realtime motion delegate for the pi, are conceptually similar - it's just that in one case the realtime executive engine is a highest priority task on the main processor, and in the other it runs on a dedicated motion co-processor.


text:
Triggering the push button on the analog input of the L293D motorshield
I'm trying to drive a 12v dc motor using three push buttons, one to turn clockwise, the other counter-clockwise and the other to stop the motor completely.
However the code below is not working, apparently it feels like I'm doing something wrong in the code on the connect buttons on the analog part of the engine shield L293D.
The Arduino is powered by a 9v battery and motor shield **L293D with an external power.
#include <AFMotor.h>

    AF_DCMotor motor(1);

    int val;

    #define btnleft A0
    #define btncenter A1
    #define btnright A2

    void setup()
    {
      pinMode(btnleft, INPUT);
      analogWrite(btnleft, HIGH);
      pinMode(btncenter, INPUT);
      analogWrite(btncenter, HIGH);
      pinMode(btnright, INPUT);
      analogWrite(btnright, HIGH);
    }

    void loop()
    {
     val=digitalRead(btnleft);
       if(val!=1)
        {
        Serial.print("LEFT: ");
        motor.setSpeed(255);
        motor.run(FORWARD);
        delay(3800);
        }

     val=digitalRead(btncenter);
       if(val!=1)
        {
        Serial.print("CENTER");
        motor.setSpeed(255);
        motor.run(BACKWARD);
        delay(3800);
        }

     val=digitalRead(btnright);
       if(val!=1)
        {
        Serial.print("RIGHT");
        motor.run(RELEASE);
        delay(3000);
        }
    }

Why are you using analogWrite() on an input?

I thought it was to be an analog input in motorshield

So then why would you treat it as an output regardless?

Maybe he means digitalWrite, to set the internal pull-ups. Doing an analogWrite of 1 doesn't make a heap of sense.

As noted in Nick Gammon's comment, digitalWrite(btnleft, INPUT) (etc.) would make a lot more sense than does analogWrite(btnleft, INPUT) (etc.).

Edit: INPUT is a constant defined in wiring.h (as in following extract), and is intended for use in pinMode() calls that set an IO pin's mode to one of INPUT, OUTPUT, or INPUT_PULLUP.  It's inept to use it in a call of either digitalWrite() or analogWrite().
    #define HIGH 0x1
    #define LOW  0x0
    #define INPUT 0x0
    #define OUTPUT 0x1
    #define INPUT_PULLUP 0x2

Note that digitalWrite to an input-mode pin leaves the pin in input-mode, while an analogWrite to an input-mode pin changes the pin to output-mode.
When you want a pin to be input-mode with pullup, it is simpler to use INPUT_PULLUP as the mode parameter, rather than using two separate calls.  That is, instead of saying pinMode(pin, INPUT); followed by digitalWrite(pin, HIGH);, just say
pinMode(pin, INPUT_PULLUP);

Actually digitalWrite(btnleft, INPUT) is not correct. You should only call digitalWrite with a HIGH or LOW parameter, to avoid misunderstandings. Ok, for arduino INPUT = LOW = 0x0 and OUTPUT = HIGH = 0x1, but... I don't think that someone writing digitalWrite(btnleft, INPUT) wants the pin set at 0


text:
Disabling a push button after being under pressure for some time?
Disabling a push button after being under pressure for some time?
I need to disable a button where the user is pressing for a time it is disabled.
Code:
int ledPin = 13;

int inPin = 7;

int val = 0;

void setup() {

pinMode(ledPin, OUTPUT);

pinMode(inPin, INPUT);

}

void loop(){

val = digitalRead(inPin);

if (val == HIGH) {

digitalWrite(ledPin, LOW);

} else {

digitalWrite(ledPin, HIGH);

}

}

You want to what?  I don't understand what you're asking.

Okay, sorry if the question was misdirected, English is not my main language. What I mean is how to disable a push button after it is pressed for a certain time.

That's pretty much what you said before.  I don't understand what you want when you talk about "disable a push button". Do you want to have it physically disconnected from your Arduino, or only have the Arduino ignore any state changes from the button?

int ledPin = 13;
int inPin = 7;
int val = 0;
int oldVal = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(inPin, INPUT);
}

void loop(){
  val = digitalRead(inPin);
  if (val == HIGH && oldVal == LOW) {
    digitalWrite(ledPin, LOW);
    oldVal = HIGH;
  } else if (val == LOW && oldVal == HIGH) {
    digitalWrite(ledPin, HIGH);
    oldVal = LOW;
  }
}

Can you please edit your post to include exactly how this code works and how it's different than the original code? Thanks!

I think the question is about activating something on a switch push, but only for x seconds. For example, you press a button to sound an alarm, but it stops after 5 seconds.

This should do it:
const byte ledPin = 13;
const byte inPin = 7;

const unsigned long MAX_PUSH_TIME = 2000;  // ms
const unsigned long DEBOUNCE_TIME = 20;    // ms
unsigned long whenPushed;

bool switchState;
bool awaitingRelease;

void setup()
  {
  pinMode(ledPin, OUTPUT);
  pinMode(inPin, INPUT_PULLUP);
  }  // end of setup

void switchPushed ()
  {
  // we want them to let go now, ignore it
  if (awaitingRelease)
    return;

  // is LED already on?
  if (digitalRead (ledPin) == HIGH)
    {
    // held for too long? turn off LED, remember it
    if (millis () - whenPushed >= MAX_PUSH_TIME)
      {
      awaitingRelease = true;
      digitalWrite(ledPin, LOW);
      }
    return;  // all done
    }

  // turn LED on, remember when
  digitalWrite(ledPin, HIGH);
  whenPushed = millis ();
  delay (DEBOUNCE_TIME);
  }  // end of switchPushed

void switchReleased ()
  {
  digitalWrite(ledPin, LOW);
  awaitingRelease = false;  // they released it!
  delay (DEBOUNCE_TIME);
  }  // end of switchReleased

void loop()
  {
  switchState = digitalRead(inPin);
  if (switchState == LOW)
    switchPushed ();
  else
    switchReleased ();
  }  // end of loop

Note: I used an input pull-up resistor on the switch to avoid having to use extra components. Thus the switch is wired between pin 7 and ground. That is why the test for the switch being pressed is for it to be LOW.

Reference

Switches tutorial


text:
Connect Arduino with fischertechnik TX Controller
Is it possible to cinnect the Arduino with a fischertechnik TX Controller? Maybe with I²C, but i want to use I²C for something else on the arduino. So are there multiple I²C Ports on the Arduino (I haven't got one yet)?

As described in the Wire library that brings supports I²C support to Arduino, except for the DUE that has 2 pairs of pins for 2 I²C buses, other Arduino boards support one I²C connection.
However, this is when you want to use hardware facilities of ATMEL chips that these limitations apply; there is a software I²C library exists that allows using other pins for I²C. One major drawback, though, is that it is very slow; not sure if this is a problem in your situation.
One important thing though: the principle of I²C is to be able to plug several slave devices (more than 100) to one master device. In general, Arduino is the master device, but the Wire library can be used as master or slave. Wouldn't that fit your requirements?
In this situation, you could just use the same I²C bus for everything, including connection to Fischertechnik TX controller.


text:
Stacking shields without headers
In the project I am working on, I have a limited space with which I can work. I am using an Arduino Uno with 2 Adafruit motor shields, and when I stack them using normal, female stacking headers it is too tall to fit. I thought that one way to solve this would be to lay them out side to side rather than one on top of the other. So, instead of this
+--------Motor shield 2 ----------+
|||||||||||||||||||||||||||||||||||
+--------Motor shield 1 ----------+
|||||||||||||||||||||||||||||||||||
+---------Arduino Uno ------------+

it would look like this
               -----------------------------------------Wires -------------------------------
+---------Arduino Uno ------------+    +--------Motor shield 1 ----------+    +--------Motor shield 2 ----------+

Would this be possible if I were to connect all of the pins with wires, and has anyone successfully done this before?

It is possible to have some success with this, but keep in mind that the longer the wire, the higher the inductance and voltage drop across the wire. Prefer to use a star topology rather than a chain topology, with the Arduino in the middle of all the shields in use.

Also you probably only need a few wires connected.  It looks like the motor shield uses 6 pins, 2 I2C pins, pins 9 and 10 (if using hobby servos), power and ground.

Yes, no problem running individual wires, and also like Craig says, only run the wires you need. For some inspiration, here's a project I did with a bit of hand wiring. And then there's this project with kinda epic wiring.


text:
Adafruit motor shield + Adafruit stepper not working
I have the Adafruit Motor Shield V2 and an Adafruit stepper motor. I have not soldered the shield onto the Arduino (which is an Uno) yet because I don't want to make anything permanent yet. I have the Arduino plugged into a DC wall adapter and have the VIN jumper in the shield, and the green power light on the shield is lit. This is how the stepper is connected.
As you can see in the picture, all the wires from the stepper are plugged in. The order of the wires is what it says it should be on the website, which is orange-pink-red-blue-yellow.  My sketch's code is an adapted version of the StepperExample from the Adafruit motor library. Here's the full code
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();

Adafruit_StepperMotor *myMotor = AFMS.getStepper(513, 2);

void setup() {
  Serial.begin(9600);
  Serial.println("Stepper test!");

  AFMS.begin();
  myMotor->setSpeed(5);
}

void loop() {
  myMotor->step(100, FORWARD, SINGLE);
}

But the stepper still doesn't move. Can anyone point out what I'm doing wrong here?

You must solder the header pins to the shield.  You can then plug and unplug that from the sockets of the arduino board, but you must solder the pins to the shield board for reliable electrical connection.

You have a lot of extra exposed wire that may cause problems if they touch. You should have little or no bare wire extending out of the screw terminals.

As far as I know, you have to solder the header pins. Here is a nice video demonstrating the assembly: Motorshield V2 assembly

Ok, I'll try this later and see if it works.

Also we removed the vin jumper when we attached an external power source. Cant really see on your pic whether its on or off.


text:
Arduino sizeof Servo array objects is.. wrong?
After searching for a quite long while over the internet, I have no choice but to try asking someone if they can explain me this apparently strange situation.
I'm doing some tests using some servo motors, trying to move them almost together using millis() and Servo object.
It is, of course, working either for single Servos and multiple servos.
The case, more detailed, is about this:

Move one, two or more servo motors together.
Force them to take ALMOST the same time to accomplish any action.
Have a dynamic number of servos.

About the first two points I had no problems to solve them, I was easily able to make a function and then make a library to accomplish such a job.
However, since I'm NOT that used to C++ and I was wondering if it actually was possible to create an array of Servo objects, like you can actually do, on arduino, with strings:
String stringArray[] = {"string1", "string2", "and so on, I love it."};

So, after wondering a while, I've tried this:
Servo servObject;
Servo servObject_2;
Servo servObject_3;

Servo servos[] = {servObject, servObject_2, servObject_3};

And you know what's cool? my function is actually working correctly by forcing the amount of elements of the servos array.
What I mean by that is that if I force my function to know that it is going to have 3 elements into the array it will, of course, work; However, for some reason, if I use sizeof(servos); the value returned, surprisingly, is 2....
Moreover, if I only push two servo objects instead of three into the servo array, its sizeof returns 6.
By googling, I've found out a couple of discussions about the fact that, for some reasons, in some cases, sizeof returns an incorrect value (if I'm not wrong it was the correct value -1), but in my case it apparently is not following any logic at all.
The board I'm using is an Arduino nano w/ ATMEGA 328.
Any idea of why it is not returning the correct value? Am I actually going totally wrong because I shouldn't make an array of servo objects?
ps: I didn't post the whole code because it would've been useless, since the sizeof is the first function called in the loop()
Regards,
briosheje

What you describe is weird; could you please post the exact code that calculate the size of the array and displays it (I suppose this is through Serial)?

@jfpoilpret: arduino supports the standard sizeof construct available for any array object. Therefore, any array (ex. int elements[] = {2,3,1,3,9};) outputs its correct value (in the previous case 5) and I'm getting the value directly from the Serial port. In any case, tonight, I will upload the whole code, I'm not and home and can't really paste it from my Nexus 5 :P

It would help if you post a version of your code cut down to the minimum necessary to demonstrate the erroneous returns.

@JRobert: Tonight I'll post the whole code, even though, as I said above, the array is declared (and filled) right before the setup and even if I print the sizeof at the start of my loop, it still outputs the same value as in the function where I'm using it. Also, is there any alternative to check if an array element exists? If it's possible, then I could make my own sizeof prototype.

My point was that it's easier for someone to try a simple or trivial program showing the error that to try your - likely hardware dependent - full program. To answer your question, I use this macro #define countof(a) (sizeof(a)/sizeof(a[0])) to find the # of elements in an array, but since it depends on sizeof() it's won't be much help to you.

What you describe seems to be a common issue that many C or C++ developers can get (or have got) with sizeof.
Take a look at the following code:
char a[3];

int size(char b[]) {
    return sizeof b;
}

void setup() {
    int size1 = sizeof a;
    int size2 = size(a);
}

In that code, size1 will be evaluated, by the compiler, to 3 which is the real size of a variable, whereas size2 will be 2.
Why so?
This is just because sizeof a is evaluated by the compiler, and the compiler knows that a is an array of 3 char; but when a is passed as an argument to function size(), it is converted to a pointer (to the first element of the array), hence its size is the size of a pointer, which is 2 bytes on AVR ATmega MCU.
This subtlety of sizeof may explain strange values as you describe.
How to fix the issue?
Most C functions that take an array as argument will require another argument that tells the size of the array; that's the way (the only one I think) to deal with this problem.
Here is a sample code:
Servo allServos[] = {...};
#define NUM_SERVOS (sizeof(allServos) / sizeof(Servo))
...
void handleServos(Servo *servos, int numServos) {
    for (int i = 0; i < numServos; i++) {
        servos[i].write(...);
        ...
    }
}

void loop() {
    handleServos(allServos, NUM_SERVOS);
}

It is common practice in C to declare an array and immediately after, define its size as above.

Oh, thanks, I didn't know that sizeof, in that case, would have refered to the pointer of the Array. So, is there any way to get the true size of the above array of Servo objects? Am I supposed to count each element and use a counter?

@briosheje see the latest edit to my answer.

Thanks! It works! :) I've already confirmed the answer as solution but still, thanks for the clear explanation!


text:
How do I replace a burnt atmega328 with a new atmega328(bootloaded) in arduino?
I have an arduino UNO with atmega 328 whose microcontroller got burnt. I bought a new atmega328. I have another working arduino with atmega8. I followed the instructions in http://arduino.cc/en/Tutorial/ArduinoToBreadboard but I got a little confused.
I burnt the bootloader into my new atmega328 using atmega8 arduino as described in the link above. Now, can I replace my old atmega328 with this new bootloaded atmega328 to upload sketches to it? Or should I follow the steps described in the link to upload sketches?

Once the bootloader has been burned to it, the chip can replace the one that is currently on the Arduino board. Simply follow normal DIP removal and insertion procedures to replace it.


text:
Multiple upload/ Synchronization problem
I am trying to do an experiment with Arduino Uno r3 board plus a 2-channel relay shield. What I need to do is to alternatively turn on and off the relay shields. So, it requires multiple compile and upload of the program to assign values to corresponding pins. What I have seen by now is that uploading the program to Arduino is a kind of painful process and it requires nothing to be connected to pins 0 and 1 to prevent synchronization errors. So, I was wondering how I can do my experiment without having to mount/unmount relay shield each time I want to upload a new program into it.
Thanks in advance

Would it be possible to just add some other kind of input to change what your sketch does while it is running without re-uploading?

Well, you can write a program that takes numbers out of Serial input.
int pin1 = Serial.parseInt();
int pin2 = Serial.parseInt();
// etc., etc.

Simple.


text:
3-Way Bluetooth Communication?
I need two Arduino units with the HC-06 Bluetooth board to communicate with each other and one of these Arduino units also connected to my Android phone. Is this possible to do with just two HC-06 modules, or even three? Or is there a better solution for this?
To reiterate what is going on here:
I have two Arduinos that are running off battery. Arduino 1 is sending data every 0.5 seconds to the Arduino 2. Arduino 2 collects this, adds its own bit of data to it, and then sends this new data packet to my Android phone which will only be connected to Arduino 2.
I haven't completely decided upon what kind of Arduino board to get, but it needs to be fairly small, but I am planning on the Adafruit Pro-Trinket 5v.
Hopefully you get the basic scenario, let me know if you need more clarification and what you think could be done here.
Thanks a lot!

Just a thought: If you store data in Bluetooth advertising data, you won't need to do anything fancy with Arduino 2. Have Arduino 1 update its advertising data as often as you want. Have Arduino 2 scan and get the data stored in Arduino 1's advertising data. Then, Arduino 2 can update its own advertising data with the updated data. Scanning and getting Arduino 2's data from Android is do-able. I didn't add this as an answer because I don't know if the HC-06 supports bluetooth scanning (it probably does).

Should be possible, but only if you setup the Bluetooth module of Arduino 2 as the master. You see, Bluetooth requires to connect to a master. A master can connect to 8 slaves in total. Because Arduino 2 connects to multiple devices (Arduino 1 and your Android device) it should be the master. This also means your Android device cannot connect to any other devices.
Hope this gives you a place to start exploring.

Ok
So From Whatever I can Understand you could do this.

make one of the boards talk to a master control board.
make the control board talk to your phone.

Why don't you change  your approach

Make the board A communicate with board B with Bluetooth.
Use different pins to setup communication b/w phone and board b.

Arduino to Arduino Bluetooth- http://www.martyncurrey.com/arduino-to-arduino-by-bluetooth/
Arduino to phone via Bluetooth- http://www.instructables.com/id/Connect-Arduino-Uno-to-Android-via-Bluetooth/
PS: - USE DIFFERENT PINS!


text:
Specify F_CPU in arduino to use 8MHz clock
I am using a custom made AVR board with Atmege-328p on it and it doesn't have a 16MHz crystal on it. I would like to use the internal 8MHz as clock. I have set the appropriate Fuses but now I am unable to tell the programs that F_CPU is 8000000UL. One way of doing it is to add another variant to the boards. I would like to if there is another way to set F_CPU ?

No, the boards.txt file is where it is defined and the only place it is (or can be) defined. Making a new board variant is the proper way of adding a new board with new settings.

Maybe there is already a board in "boards.txt" that is compatible with your board. The bootloader doesn't know if the 8MHz is from a crystal or from the internal oscillator, that means you can even use a bootloader for a 8MHz crystal, and you only have to change the fuse for the internal oscillator. During programming (for example burn the bootloader) with a programmer the ATmega328p requires a clock. Therefor you have to be careful not to set the external crystal (when there is no crystal), because then the programmer doesn't work.


text:
file directory for saving .cpp & .h for the Arduino IDE for short #include statement
I am trying to write a class/function that I think I will be using often in my Arduino IDE, I know the code but where should i save the file so that the IDE picks it up without a full directory address in the #include line, as you may guess I'm a little new to this....

If you think you will be reusing this code frequently, you might want to make a library as suggested by Joachim. Your library can then be added to any sketch you write using a #include statement.
The arduino website has a nice guide on writing libraries, check it out here.
If you would just like to include your header file in a sketch without writing a library, placing the header file in the same directory as your sketch should compile if you use #include "header_file_name.h".


text:
Timer1 stops firing
I am trying to use interrupts to play notes on a speaker.  Timer2 works fine, but after about 15 seconds, Timer1 stops firing for about 5 seconds, and then it comes back on.  If I keep running the sketch, it will stop and resume every now and then.
Here is my code:
#define SPEAKER1 8
#define SPEAKER2 7
volatile bool swap1;
volatile bool swap2;

ISR(TIMER1_COMPA_vect)
{
    digitalWrite(SPEAKER1, swap1);
    swap1 = !swap1;
}

ISR(TIMER2_COMPA_vect)
{
    digitalWrite(SPEAKER2, swap2);
    swap2 = !swap2;
}

void playNote1(unsigned note) { //Play a note on Timer1.
    uint8_t oldSREG = SREG;
    cli();
    bitSet(TCCR1B, CS10);
    bitSet(TCCR1B, CS12);
    unsigned ticks = (16000000 / 1024) / (note);
    ticks /= 2;
    OCR1A = (ticks <= 65535 ? ticks : 65535);
    SREG = oldSREG;
}

void playNote2(unsigned note) { //Play a note on Timer2.
    uint8_t oldSREG = SREG;
    cli();
    bitSet(TCCR2B, CS20);
    bitSet(TCCR2B, CS21);
    bitSet(TCCR2B, CS22);
    unsigned ticks = (16000000 / 1024) / (note);
    ticks /= 2;
    OCR2A = (ticks <= 255 ? ticks : 255);
    SREG = oldSREG;
}

void stopNote1() {  //Stop playing a note on Timer1.
    uint8_t oldSREG = SREG;
    cli();
    bitClear(TCCR1B, CS10);
    bitClear(TCCR1B, CS12);
    SREG = oldSREG;
}

void stopNote2() {  //Stop playing a note on Timer2.
    uint8_t oldSREG = SREG;
    cli();
    bitClear(TCCR2B, CS20);
    bitClear(TCCR2B, CS21);
    bitClear(TCCR2B, CS22);
    SREG = oldSREG;
}

void setup() {
    pinMode(SPEAKER1, OUTPUT);
    pinMode(SPEAKER2, OUTPUT);
    pinMode(13, OUTPUT);
    // initialize timers
    cli();          // disable global interrupts
    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B
    // turn on CTC mode:
    bitSet(TCCR1B, WGM12);
    bitSet(TIMSK1, OCIE1A);

    TCCR2A = 0;     // set entire TCCR2A register to 0
    TCCR2B = 0;     // same for TCCR2B
    // turn on CTC mode:
    bitSet(TCCR2A, WGM21);
    bitSet(TIMSK2, OCIE2A);
    sei();          // enable global interrupts
}

void loop() {
    playNote1(523);
    delay(1000);
    stopNote1();
    delay(500);
    playNote1(131);
    delay(2000);
    stopNote1();
    delay(500);
}

Why are you using those ISRs instead of PWM?

I'm not sure why you think that answers what I asked...

You're twiddling pins manually instead of letting the hardware do it.

Fair enough. But the hardware timers can do square waves too. Try COMnx[1:0]=0b01, WGM1[3:0]=0b0100, and WGM2[2:0]=0b010.

They represent all the sequential bit places that should be accessed. The datasheet uses this convention quite a bit.

It means WGM22, WGM21, and WGM20.

The problem you have is that you never reset Timer1 counter (TCNT1) when you stop a note and then play another one.
Also, changing the clock divider selection to "no clock" by clearing bits CS10 and CS12 as you do is not the most effective way to stop the timer; in fact, rather than stopping it, you can let it run but just disable its interrupts.
I have modified your program and this worked correctly:
#define SPEAKER1 8
volatile bool swap1;

ISR(TIMER1_COMPA_vect)
{
    digitalWrite(SPEAKER1, swap1);
    swap1 = !swap1;
}

void playNote1(unsigned note) { //Play a note on Timer1.
    uint8_t oldSREG = SREG;
    cli();
    unsigned ticks = (16000000 / 1024) / (note);
    ticks /= 2;
    OCR1A = (ticks <= 65535 ? ticks : 65535);
    TCNT1 = 0;
    bitSet(TIMSK1, OCIE1A);
    SREG = oldSREG;
}

void stopNote1() {  //Stop playing a note on Timer1.
    uint8_t oldSREG = SREG;
    cli();
    bitClear(TIMSK1, OCIE1A);
    SREG = oldSREG;
}

void setup() {
    pinMode(SPEAKER1, OUTPUT);
    pinMode(13, OUTPUT);
    // initialize timers
    cli();          // disable global interrupts
    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B
    TCCR1C = 0;     // same for TCCR1C
    // Set clock divider
    bitSet(TCCR1B, CS10);
    bitSet(TCCR1B, CS12);
    // turn on CTC mode:
    bitSet(TCCR1B, WGM12);
    bitClear(TIMSK1, OCIE1A);
    sei();          // enable global interrupts
}

void loop() {
    playNote1(523);
    delay(1000);
    stopNote1();
    delay(500);
    playNote1(131);
    delay(2000);
    stopNote1();
    delay(500);
}

Note that I have removed all code for Timer2 as it does not play any role in the initial problem.
The important changes are:

setup() now performs Timer1 setup completely (CTC mode, clock divider); note that I also included TCCR1C to ensure full setup (it is preferrable as Arduino libraries may have initialized it differently before setup() is called); it also ensures Timer1 interrupts are initially disabled.
playNote1 now clears TCNT1 and then enable Timer1 interrupt for TIMER1_COMPA_vect
stopNote1() just disables Timer1 interrupt for TIMER1_COMPA_vect

To be complete, you would also want to limit useless consumption on output pin 8, thus stopping a note should also force its output level to LOW (or HIGH depending on your actual circuit behind, but LOW is more likely):
void stopNote1() {  //Stop playing a note on Timer1.
    uint8_t oldSREG = SREG;
    cli();
    bitClear(TIMSK1, OCIE1A);
    swap1 = false;
    SREG = oldSREG;
    digitalWrite(SPEAKER1, LOW);
}

Now what about your code for Timer2, the code is the same, so why does it work?
Actually it doesn't :-)
But you can't hear the difference between Timer2 is an 8-bit counter so if you don't reset it, then it won't take long until it reaches 255 and resets to 0, so only the first wave phase will be wrong but your hear won't notice that...
So you should also modify the code for Timer2 to make it correct.

Wow!  I never would have guessed that!


text:
Why is that any sensor signal need to be hooked up to the interrupt pins on Andruino boards?
I have come across some Andruino Sensors like Motion, Light and all recommend to be connected to pin 2 or 3 on Andruino Uno board which are interrupt pins. This is especially true if you are looking for HIGH or LOW values. Why is that to be connected to interrupt pins?
One example would be is I used CC3000 Wifi Breakout and Motion sensor. Both were in fight to occupy the interrupt pin 2. I have seen the Motion sesnor not working correctly after getting it's signal hooked to Pin 4[It has pull up resistor enabled]
What should I do if i need to hook up more sensor which uses the limited interrupt pins and how should i handle the above scenario?

The interrupt pins are used to notify the MCU that a device needs attention. The INTx pins are chosen first because they are easy to program for; each gets a dedicated interrupt vector and hence ISR.
There is another type of external interrupt though, the Pin Change interrupt. This can be invoked via any of the PCINTxx pins on the device; on the '328 any pin can act as an interrupt.
The main difference between INT and PCINT is that PCINTs are grouped into banks of 8, which means that once the ISR has been invoked the appropriate pins need to be checked for their level, which furthermore means that it is possible to misread an interrupt if a bank is shared by multiple devices and the interrupt pulse itself is very short.
Further details can be read in the "External Interrupts" and "Interrupts" sections of the MCU datasheet.

Ignacio provides a great answer on the differences between the two types of interrupts.  But to add to that, it isn't a universal requirement to even use an interrupt.
Polling is also a possibility, though it has been compared to periodically picking up the phone to see if anyone is trying to talk to you.

Advantages of using an interrupt can include faster response, background response while a program is primarily doing something else, and often an associated ability wake up the processor from low-power sleep mode used in battery powered gadgets.
But polling can have a role, for example when the program runs in a tight loop and can only take action in response to input at certain times anyway - an interrupt service routine that merely sets a flag to tell the main program loop that something has happened may or may not be much benefit.
Often the best solution is a hybrid approach - an interrupt service routine records events - especially ones which might vanish or be repeated before the main program loop can poll for them.  Then when the main program loop reaches a logical decision point, it checks the flags or event queue to see if the interrupt service routine has recorded anything to which it should respond.  Serial receive is typically handled this way in the Arduino framework.


text:
Arduino error in code
i'm making a project and i came across the follwing error.
Whan i'm trying to compile and upload the code i'm getting those errors:
ShiftRegisterTest1.ino:In function 'int* return_pins(int)'
displays.ino:9: error: expected primary-expression before '{' token
displays.ino:9: error: expected `;' before '{' token
displays.ino:12: error: expected primary-expression before '{' token
displays.ino:12: error: expected `;' before '{' token
displays.ino:15: error: expected primary-expression before '{' token
displays.ino:15: error: expected `;' before '{' token
displays.ino:18: error: expected primary-expression before '{' token
displays.ino:18: error: expected `;' before '{' token
displays.ino:21: error: expected primary-expression before '{' token
displays.ino:21: error: expected `;' before '{' token
displays.ino:24: error: expected primary-expression before '{' token
displays.ino:24: error: expected `;' before '{' token
displays.ino:27: error: expected primary-expression before '{' token
displays.ino:27: error: expected `;' before '{' token
displays.ino:30: error: expected primary-expression before '{' token
displays.ino:30: error: expected `;' before '{' token
displays.ino:33: error: expected primary-expression before '{' token
displays.ino:33: error: expected `;' before '{' token
displays.ino:36: error: expected primary-expression before '{' token
displays.ino:36: error: expected `;' before '{' token
displays.ino:39: error: expected primary-expression before '{' token
displays.ino:39: error: expected `;' before '{' token
displays.ino:42: error: expected primary-expression before '{' token
displays.ino:42: error: expected `;' before '{' token
displays.ino:45: error: expected primary-expression before '{' token
displays.ino:45: error: expected `;' before '{' token
displays.ino:48: error: expected primary-expression before '{' token
displays.ino:48: error: expected `;' before '{' token
displays.ino:51: error: expected primary-expression before '{' token
displays.ino:51: error: expected `;' before '{' token
displays.ino:56: error: expected primary-expression before '{' token
displays.ino:56: error: expected `;' before '{' token
Error compiling

I don't really understand why since the code (see below) should be working.
int * return_pins(int get_number)
{
static int rp[8];
switch(get_number)
{
            //DP, A, B, C, D, E, F, G
    case 48: //0
        rp[8] = {0, 1, 1, 1, 1, 1, 1, 0};
        break;
    case 49: //1
        rp[8] = {0, 0, 1, 1, 0, 0, 0, 0};
        break;
    case 50: //2
        rp[8] = {0, 1, 1, 0, 1, 1, 0, 1};
        break;
    case 51: //3
        rp[8] = {0, 1, 1, 1, 1, 0, 0, 1};
        break;
    case 52: //4
        rp[8] = {0, 0, 1, 1, 0, 0, 1, 1};
        break;
    case 53: //5
        rp[8] = {0, 1, 0, 1, 1, 0, 1, 1};
        break;
    case 54: //6
        rp[8] = {0, 1, 0, 1, 1, 0, 1, 1};
        break;
    case 55: //7
        rp[8] = {0, 1, 1, 1, 0, 0, 0, 0};
        break;
    case 56: //8
        rp[8] = {0, 1, 1, 1, 1, 1, 1, 1};
        break;
    case 57: //9
        rp[8] = {0, 1, 1, 1, 1, 0, 1, 1};
        break;
    case 65: //A
        rp[8] = {0, 1, 1, 1, 0, 1, 1, 1};
        break;
    case 70: //F
        rp[8] = {0, 1, 0, 0, 0, 1, 1, 1};
        break;
    case 69: //E
        rp[8] = {0, 1, 0, 0, 1, 1, 1, 1};
        break;
    case 80: //P
        rp[8] = {0, 1, 1, 0, 0, 1, 1, 1};
        break;
    case 72: //H
        rp[8] = {0, 0, 1, 1, 0, 1, 1, 0};
        break;
            //DP, A, B, C, D, E, F, G
    case 45: //-
    default:
    rp[8] = {0, 0, 0, 0, 0, 0, 0, 1};
    break;
}
return rp;
}

What this code does is to basicaly get an int ad input and based on this number it returns an int array. It's a very simple code which is called inside the loop() method which is located on an other file.
Also i'm using Atmel Studio 6 instead of the original Arduino IDE but i dont think it has to do something with the problem :/

As fuenfundachtzig said this cannot be done in this version of C++ Arduino uses. A replacement for this method is to set the number for each place.
For example:
case 48:
    //rp[8] = {0, 1, 1, 1, 1, 1, 1, 0};
    rp[0] = 0;
    rp[1] = 1;
    rp[2] = 1;
    rp[3] = 1;
    rp[4] = 1;
    rp[5] = 1;
    rp[6] = 1;
    rp[7] = 0;
    break;

This works the same however it takes more space but i dont this there is a problem.

What you try here:
rp[8] = {0, 1, 1, 1, 1, 1, 1, 0};

is only valid in C++11. (Before that you can initialize an array like this only upon initialization.)
Besides, as pointed out by Pete Becker, you need to declare rp as an array rather than a single int.

And what if i want to change the values of the array?

This isn't valid at all. rp[8] is an int.

Oh. And that. :)

Have you tried compiling without the "static" keyword. I think the compiler is complaining because it sees multiple statements trying to make an assignment to a static variable. Even if your logic is such that only one of the assignments will ever be executed the compiler doesn't know that.


text:
XBEE coordinator WITH or WITHOUT Arduino?
I am building a wireless system that has got an Arduino with a XBEE as the 'end user' and I need to acquire data/control that Arduino from a PC graphical interface.
As far as I'm aware there are two options to obtain the communication:

I could use another Arduino with XBEE (coordinator) that is connected to my PC (serial) to control the 'end user'. The code is stored in this Arduino which works as a bypass between PC and XBEE.
I could simply use a XBEE without Arduino (coordinator) connected to my PC to control the 'end user'. The code should be stored within the PC or the XBEE to establish communication and control data transmission to different end users (???)

As I am new to the Arduino world, would you please direct me to the best/easiest solution to obtain such thing?

If you want just to control and receive data from your end user, option 2 is easy to implement.
You can use any programming language that supports serial communication such as python, node.js, etc.
What you have to is to note how your coordinator is recognized by your operating system (in windows as com1 port, unix-like as ttyACM or similar) and open it from your preferred language.
After that, you establish a protocol that should be agreed with your Arduino. For example. Suppose you want to collect data from end user, so, you send a message from the coordinator connected in your PC with a code #data through the serial. When the Arduino receives it, it decodes the message and return something like #d125 where it says it is sending the data and the value is 125 (supposing integer values).
Making sure you already have configured the XBees in the same network by setting Same PAN id and cross setting the destination address of each one so they send packates to each other.
I am supposing you are using AT transparent mode where they just send whatever comes in the serial interface, in this mode they work basically sending chunks of bytes and it is up to you to establish a protocol to provide a good flow of data. In this mode there is no guarantee that your packet will reach the destination. In order to fully extend the XBee usage, you'd need the API mode where all the transmission checks are done.
But for you purpose, AT mode seems enough.


text:
6 + 1 motors connected to an arduino uno?
Is it possible to connect 6 dc motors and 2 dc servo motors to an Arduino Uno? I intend to control the Uno with a Raspberry pi connected through USB.
Assuming every motor to be bidirectional, how many L293 or L298 motor driver boards do I need? Is there any other better option than using multiple driver boards?

It is hard to answer your question until we know the specs of motors you intend to use. Also ensure that you use a specific power supply for motors (don't use power provided by the UNO).

6 12volt 10 rpm dc motors and a microservo motor to be exact. Yes, I will run them with a separate power supply to the driver boards. Are the pins on the Uno sufficient to provide signals to all the motors?

In out project, we connected the motors that werd going in the same direction, to the same driver board. Not sure if they were in series or parallel. For a vehicle with 4 motors, it can be enough to control the left and right side, instead of all 4.

TI is only one of the many manufacturers who make some really nice motor control chips.  The  DRV8835 is one such device: it will drive two motors at voltages up to 11 Vdc at currents up to 1.2 Amps each.  Each channel requires two control lines: enable and direction.
Pololu sells this chip already mounted to a carrier board for a rational price.
You will need a total of (6 motors * 2 lines per motor) = 12 i/o lines PLUS two more lines to control your servos for a total of 14 i/o lines from your controller.

Normally a full H-bridge (for one motor in bi-directional mode) will need 3 ouput pins. You can potentially force the enable pin to a constant level but that means you will always draw current for your motors even when they don't move, which is probably not what you want. ou might also wire all 6 enable pins together to one Arduino pin just to control power of all motos altogether.
In addition, each servo will need one output pin (typically 9 and 10 for both servos).
Hence in the worst case, you would need 20 pins overall. You have them on Arduino UNO but this means you don't have anyhting else left, even Serial communication!
If you can wire all 6 enable pins together, then you will need "only" 15 pins.
Also, note that if you want to control the speed of the DC motors, you will need PWM pins, but then you won't get enough with a UNO.
Regarding drivers ICs (L293 or L298), each of them has 2 full H-bridges, hence can drive 2 DC motors in bi-directional mode, so you will need 3 of them overall.


text:
Learning to use ATmel Studio - using BOSSA downloader
The basic question - is BOSSA the right SOFTWARE  "tool" to use in ATmel Studio to connect / download to Arduino DUE AND NOT using VisualMicro?
I cannot get BOSSA to AUtoScan for COM port.
Getting error "Could not find a device"
When I select my COM port ( COM4 ) which works in Arduino IDE
I get "Could not connect to device on COM4"
This tells me that ATmel Studio does not recognize my Due at all.
Could someone please advise me what did I missed in configuring the Studio?
I can use Studio to run Arduino IDE (VisualMicro ) but I need to get away from Arduino IDE environment.
Thanks for your time.

Per doc SAM3X8E has build-in downloader( NO need for BOSSA?) , so I have installed SAM-BA but having trouble installing CDC driver for XP

The Arduino Due needs a patched version of Bossa, not the 1.2.1 version available on SourceForge. Supposedly the patched version is available on GitHub, or you can copy the version in the Arduino IDE.
Also, the Due USB port must be put into bootloader mode. Open then close the serial port at 1200 baud, and it will re-instantiate as a Bossa programming port.
To return to serial port mode, the only way I have found is to power cycle the Due.


text:
Strange comportment of stepper motor while connected to internet
Problem moving a stepper motor after reading a value from a webpage....
I have a project to move a stepper motor from an angle after reading a number from internet; I have a typical 28BYJ-48 stepper with the hardware driver and an arduino + ethernet shield.
I have tested the motor alone with different library and it is working very well, the motor turn correctly to the proper angle and without shaking.
I have also been able to read a specific page with a number on it with the Ethernet shield and library. I am able to light a led whenever a certain value is read from this webpage.
Once I connect the 2 parts, either the stepper motot is vibrating a lot and moving from half the correct angle, either it is only shaking and not moving at all....
Note: I have powered it with an external power source thinking it was because of power issues but it doesn't change anything.....
I don't get it... Why would it work well before the etheret connection an not after?? Maybe it's late and I miss something obvious, but frankly I spent a lot of time looking online and checking my code
Here is my sketch if it anyone could help... thanks a lot in advance, I know it's quite long....but i'm quite desperate :-(
#include <AccelStepper.h>
#include <Ethernet.h>
#include <SPI.h>

////////////////////////////////////////////////////////////////////////
//CONFIGURE
////////////////////////////////////////////////////////////////////////

#define HALFSTEP 8

// Motor pin definitions
#define motorPin1  8     // IN1 on the ULN2003 driver 1
#define motorPin2  9     // IN2 on the ULN2003 driver 1
#define motorPin3  10     // IN3 on the ULN2003 driver 1
#define motorPin4  11    // IN4 on the ULN2003 driver 1

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper with 28BYJ-48
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
const int stepsPerRev =  2038;

byte server[] = { 192,168,0,11 }; //ip Address of the server you will connect to
String serverIP = "192.168.0.11";

int port = 8888; // server port

// if need to change the MAC address (Very Rare)
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// byte ip[] = { 192, 168, 0, 188 }; // case we want to use fixed IP

//The location to go to on the server
//make sure to keep HTTP/1.0 at the end, this is telling it what type of file it is
String webPage = "/index.php HTTP/1.0";

EthernetClient client;

char inString[32]; // string for incoming serial data
int stringPos = 0; // string index counter
boolean startRead = false; // is reading?
int ledPin = 5;
String pageValue;

//////////////////////////////////////////////////////////////////////////////
// SETUP
//////////////////////////////////////////////////////////////////////////////

// setup the stepper parameters

void setup() {
  stepper1.setMaxSpeed(3000.0);
  stepper1.setAcceleration(1000.0);
  stepper1.setSpeed(500);

// start a full rotation ==> this is perfectly working!!

int steps = degreesToSteps(360);
  stepper1.moveTo(steps);
  stepper1.runToPosition();

   Serial.begin(9600);

   Serial.println("starting communication");

  //Connect the Ethernet Shield by specifying the board's mac and ip address

  if(Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
   }else{
    Serial.println("Ethernet shield connected & obtained IP address : ");
    Serial.println(Ethernet.localIP());

   //Shield already connected during setup phase, now connect to the webpage and retrieve the value

    //Connect to the server
    if(!connectToServer(server, port, webPage)){
        Serial.println("Failed to connect to server");

        }else{

               Serial.println("connected to server page");

               //Read the output value written on the webpage

              int angle = readPage().toInt();
              Serial.println(angle);

              int steps = degreesToSteps(angle);
              Serial.println(steps);

              stepper1.moveTo(steps);

              stepper1.runToPosition();

              delay(1000);

      //end of success case connection
      }

   }

 //end of setup
 }

void loop(){}

///////////////////////////////////////////////////////////////////////////////////////////
//Connect to a web page
////////////////////////////////////////////////////////////////////////////////////////////

boolean connectToServer(byte* server, int port, String webPage)
{
  //connect to the server
  Serial.println("connecting...");

  //port 8888 for our mamp server
  if (client.connect(server, port)) {
    Serial.println("connected");
    client.print("GET ");
    client.println(webPage);
    client.println();
    return true;
  }else{
    Serial.println("connection failed");
    return false;
  }

}

///////////////////////////////////////////////////////////////////////////////////////////
//Parse a value located between a < and a >
////////////////////////////////////////////////////////////////////////////////////////////

String readPage(){
  //read the page, and capture & return everything between '<' and '>'

  stringPos = 0;
  memset( &inString, 0, 32 ); //clear inString memory

  while(true){

    if (client.available()) {
      char c = client.read();

      if (c == '<' ) { //'<' is our begining character
        startRead = true; //Ready to start reading the part
      }else if(startRead){

        if(c != '>'){ //'>' is our ending character
          inString[stringPos] = c;
          stringPos ++;
        }else{
          //got what we need here! We can disconnect now

          startRead = false;
          client.stop();
          client.flush();
          Serial.println("disconnecting.");
          return inString;

        }

      }
    }

  }

}

///////////////////////////////////////////////////////////////////////////////////////////
//Convert the degrees into the closest number of steps relative to the step motor model.
////////////////////////////////////////////////////////////////////////////////////////////

int degreesToSteps(float angleDegrees) {
  //return the closest number of steps to accomplish to move the motor for the specified angle

  const float stepsPerDegree = stepsPerRev/360.00;
  int steps = angleDegrees * stepsPerDegree + 0.5;  // we add 0.5 as when converting to an int the floating part is truncated, this allows to round the value to the nearest Int
  return steps;

}

Pin 11 is used for SPI to communicate with the Ethernet Shield. And pin 10 is used for the ChipSelect.
 So using the ethernet shield will toggle those pins, making the motor shake around.
Try using pins 6, 7, 8, and 9 instead.

Top!!!  It worked perfectly!! Thanks a lot you helped me a lot!!! Now I will have this interferences in mind and check each shield for each pin configuration inside the libraries!


text:
Is there a board that can act as both a USB host and client for HID devices?
Trying to build an arduino-based Mouse/Keyboard enhancer.  This will let me do things like press certain keyboard or mouse shortcuts on the input side, then do something custom on the output side.  For instance, this would let me add keyboard shortcuts at the hardware level instead of having to do them at the OS level.
As such, I'm looking for a board which can act both as a USB host (i.e. it can have a keyboard and mouse plugged into it) as well as one that can show up as a USB HID device to the computer it's plugged into.
The boards that I'm aware of which have something close to this are the Leonardo and chip-similar, which work to emulate a keyboard/mouse to the computer they're attached to, but which don't let you connect a keyboard/mouse to them.
So is there such a board?

Leonardo + USB Host Shield?

Trying to keep it on a really small board like a trinket (which I'm seeing if it already does what I need.) I'm planning on making this so it's like a thumb drive that plugs inline into a computer (i.e. Keyboard/Mouse-->This device--> Computer)

You require a chip with two usb peripherals in it, one of which at least has host capabilities. I only know of one chip family with that off hand and I haven't ported it to Arduino yet. Maybe there is as ST arm chip with it.

Well I know the ZERO (and I'm guessing other SAM/M0-based boards) supports both host and device, but even though it has two USB ports, it doesn't look like it does so simultaneously. One seems dedicated to serial/programming while the 'native' one can be used for both.

They only have one usb port. The other is connected through a usb to UART adapter to the serial port. You need one with two natives. I only know of the PIC32MM series that has that in a small MCU, and as I say I haven't ported that sub family of the PIC32 yet, though it is on the cards...  Along with host support for the USB stack for PIC32...  The Beaglebone Black has both host and device ports, but that is a Linux embedded computer and too big and complex.

Hey… I just checked out your profile and see that you do board design and help with manufacturing. I’ve actually been looking for someone to help me with several board Designs for several different projects for a while. How can I reach out to you personally about this?

Use the contact form on my website (majenko.co.uk)

The TMK USB to USB converter is a thumb drive sized board with ATMega32u4 and max3421e with pass through/remapper software. It has the same functionality as a Leonardo with USB host shield.
https://geekhack.org/index.php?topic=69169.0

This looks promising.  I'm asking there too, but do you know if this can be used exactly like a Leo with the Host shield (i.e. can I use my own custom firmware, even if I have to flash a boot loader on it manually?)

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


text:
Problems with Dallas temperature sensor code
I have connected up my temperature sensor and I am trying to run the one wire address finder to find the address of the sensor.
The problem is that when I run the code it gives me the error: 'OneWire' does not have a type.
I have imported by the temperature and the onewire libraries but it still does not work.
#include <OneWire.h>

OneWire ds(6);  // This is where the error is

I assume this a compile-time, not run-time, message? Please copy/paste it. What OneWire library are you using? Were there any other error messages, especially any about OneWire.h not being found?

I presume the exact error you get is

error: 'OneWire' does not name a type

This error is typical when the OneWire library (or any other library for that matter) is not located under the  libraries folder, which should be at the root of the Arduino installation folder.
Also, make sure that the OneWire.h and OneWire.cpp files are 1 folder down the hierarchy, as follows:
[Arduino Installation Folder]\libraries\OneWire\OneWire.h
If they are nested deeper inside the folder hierarchy, the Arduino IDE will not find these files in its initial scan, and you will get the same error.
Make sure to close all Arduino IDE windows and re-open it after fixing the folder path.


text:
1 Wire temperature sensor
I bought a waterproof temperature sensor from Ebay, I am fairly new to this and not sure what I need or need to do in order to get the sensor to output the current temperature to the serial monitor.
Does anyone have any information on where I can get some information on how to wire this? I have looked at various videos online but they are all for a dallas temp sensor and use the dallas library.
http://www.ebay.co.uk/itm/181393039374?ssPageName=STRK:MEWNX:IT&_trksid=p3984.m1439.l2649

"The probe the temperature sensor DS18B20 original chip" from the product page. Look for the DS18b20 library.

This probe has the Dallas (now Maxim) DS18b20 sensor in it so you're already on the right track. Search for DS18b20 at arduino.cc. You'll find libraries and lots of forum discussions about using these sensors.
Also see page 6 of the DS18b20 datasheet; there are two schematics for wiring the device.
I'm using the parasitic mode (Figure 4 on that page) except I eliminated the transistor switch and connected the MCU pin for the strong-pullup directly to the one-wire bus.


text:
Writing serial data, just once after read
I have developed a program and the idea is that when it receives serial data (any single character) it returns a single random number.
I have it working but it returns 3 x random numbers one after another for each read that it does and I can't figure out why.
int led = 13;
char incomingByte = 10;
long randNumber;
// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
 Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {

//  delay(1000);               // wait for a second

   if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();
                // say what you got:
              //  Serial.print("I received: ");

                randNumber = random(1, 2000);
                Serial.println('PL' + randNumber);
                  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
                  delay(1000);               // wait for a second
                  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW

}

}

When you enter a single character into the Serial Monitor and press Enter, three bytes are sent: the character, a carriage return, and a linefeed. Serial.read() only reads a single byte, so data is available three times.
Either loop reading until no more bytes are available, check for and discard any CRs and LFs, or use a serial terminal that doesn't require pressing Enter to send data.


text:
How to measure whether air is flowing through a pipe?
I'm looking for a way to check the air-flow from an aquarium air pump. I need something that can test whether air is flowing or not and I'm not bothered about measuring flow speed. The air will be flowing through a pipe but if required I can have the sensor on the end of an additional pipe just used for measuring.

Did you consider a barometric sensor deployed inside the pipe?
The pressure should be higher when the pump is active.

The issue is that the sensor is very big and the pipe is 1/4"

As it was commented below, you can use various means to make the measurement, either by duplicating the path or by using a mechanical sensor, however there is also a more creative approach.
If you know (you can measure it once) the profile of power consumption of the pump, you can measure it over time and verify that it behaves as it should. This of course is an indirect measurement and implies trust that the system is not leaking air after the pump. But it might be less invasive.

Flow sensors tend to be expensive. However, there are many pressure sensors that provide a simple analog voltage input and others with easy to use digital interfaces.
As Igor Stoppa points out, these can be used to infer flow. Some can be purchased with tube ports that allow the user to mount the hose directly to the sensor. This would only require a "T" connector and some additional hose to connect to the air pump.
Aquarium air pumps may be pulsatile. So be sure to use an average pressure.
Average Pressure:

above a certain point may indicate blockage
between certain values indicates correct flow
below a certain value indicates no flow

.

Grab yourself something like this

Butcher it to get inside it, and add three small magnets to the fins (should be simple enough - just keep it balanced).  Then glue it all back together again.
Add a hall effect sensor to the outside, and Bob's your uncle.
Or, since the principle of that unit is so simple, you could make your own from scratch.

Even simpler: if that thing is transparent, one can add a photodiode/photo transistor pair around it and detect pulses (interrupts) on the transistor.

Good idea :) I hadn't thought of that obvious one.

Love that the linked page header says "enema flow indictors" (sic) - is that in, or.. out?

authors: عبد الر ضا البديري


text:
Arduino Mega - get mac adress
I am new on Arduino, and I am trying to use the Ethernet shield...
but it need:

IP adress
MAC adress

IP adress is easy to get... but not MAC..
how can I get my arduino MAC adress?

A MAC address must be unique throughout the environment in which it operates, but apart from that is largely arbitrary.  Typically the problem is solved by selling 3-octet prefixes (called OUI's) to manufacturers, who then uniquely assign the remaining 3 octets to individual device units they manufacturer.
However, if you are unable to discovery a globally unique address assigned to your device by its manufacturer, and know that its traffic will be confined to a local network, you can use a privately assigned (ie, "made up") address with the Locally Administered bit set.   An address of the form
02-xx-xx-xx-xx-xx-xx

or any other with the 2's bit of the first octet set will satisfy this criteria as long as you guarantee that it is unique in your system.
Be especially careful not to set the 1's bit of the first octet - if you do so, traffic will be marked as broadcast and so given wider distribution/attention than needed, wasting network capacity and processor time of connected devices.

Arduino doesn't have a MAC address, your Ethernet adapter shield however will. The MAC address is likely printed on the interface and is constructed from 12 hexadecimal numbers, usually grouped 2 hex digits at a time.
If it isn't printed on the box or the shield, then the only way to find out is to connect it to your network, configure a valid IP address on the shield and try to connect to it (eg. ping to the address) from your PC) Then you can list MAC addresses from your PC  with arp -a.
Or when using dynamic addresses and DHCP, you can find the mac address in you DHCP server (probably your home router).
Either way, you need a sketch on your Arduino to configure an IP address.

i cant vote for you... i dont have reputation =(

This answer seems somewhat at odds with the documentation cited in the other - if the shield has to be told its MAC address by the sketch, then you can't meaningfully query it until you have done that.

No MAC address is hard wired, IP address is configured in software @ChrisStratton Arduino doesn't have a MAC address, the Ethernet NIC does. Arduino can probably overrule the hard wired address, but that is advanced use of the shield.

@ChrisStratton according the the other answer some shields come without a hard wired MAC address. When inventing your own address it is essential to make it unique on your network.

Yes, it's quite clear that some come without an address stored in the hardware, what is unclear is that any come with.  Certainly though there are other embedded devices and adapters that have one stored in an eeprom or similar, bridge devices with a network stack in flash and an address stored alongside it, etc.

@ChrisStratton With a regular NIC (network interface card) as the one in your computer, tv, phone, ... the MAC address is always hard wired. This obviously is not a complete NIC, just some sort of bare bone.

Actually, no, it's usually not hard wired in the MAC, but rather stored somewhere outside the MAC chip (an eeprom on a classic ethernet card), queried from there by the software and then injected into a register in the chip by software... serializaton of ICs that aren't otherwise programmable is expensive.

I guess the more the Ethernet interface can offload workload from the microcontroller, the more tasks are done on the Ethernet interface. If you have a Ethernet interface without hard wired MAC, then your microcontroller will be much busier with communications than an interface with hard wired MAC (and related 'accelerating' hardware).

Although I can't comment on all the specifics of this, I can say that the official ethernet library documentation implies that you can choose your own mac with: older Arduino Ethernet Shields include a sticker with the device's MAC address. For older shields, choose your own.

@jippie - normally except in a "promiscuous mode" the MAC chip handles filtering of incoming packets by MAC address (so the processor doesn't have to), but by using an address set in a volatile register - which has to be externally loaded from some other source of information at power on / reset.  If you have something like an ethernet<>serial bridge where the whole network stack is running on a dedicated embedded processor, then that probably does have the MAC address persistently stored, though again, not typically actually within its ethernet functional block but rather elsewhere inside.

Current Ethernet shields come with a sticker indicating the MAC address you should use with them.

(source)

my Ethernet shield doesnt :( it is not the official

Ultimately, all but a few bits of the MAC address are irrelevant - they only need to be globally unique.  There is a range of MAC addresses reserved for "locally administered values" (ie, a range in which you are allowed to make up your own).  Pragmatically speaking, you can also take the address off an obsolete device you physically possess (old ISA bus NIC?) and know is not in use.


text:
Arduino amplifier
I want to drive my model trains (märklin) with my arduino UNO, it requires 32 watt (0-12/24v, 2A MAX(changes))
This is Direct current
How can I amplify the output of the arduino to get my 32 watt?

Usefully driving trains is more than a matter of on/and off, but involves PWM and possibly more complicated waveforms.  I expect if you look on train enthusiast sites you will find documentation of both manual throttles and automated drivers, probably no few of them based on ATmega MCUs if not the Arduino libraries as well.

You certainly can. For relatively small amplifications, you can use transistors. MOSFETs are similar and work well for larger solid state amplification. If all you need is to turn power on or off (no switching faster than ~20Hz) a relay is you best bet, but most standard ones take more power than a raw arduino output can provide so you have to buy one for this purpose. They are all easy to use, for the most part just plug in ground, power, signal, and signal out. You can look up any of these for more details on use, it should not be hard to find.
The easiest pre-built solution is something like this relay board: http://www.sainsmart.com/arduino-compatibles-1/relay/arduino-pro-mini.html

I would love to be able to either adjust the voltage, live: to control the speed of the train, or be able to use PWM, which will also work with my trains.

a transistor/MOSFET can switch fast enough to do PWM. The DC motor driver John referenced will also do exactly what you want.

Definitely go with MOSFETs. Normal transistors will get quite hot when you run 2A through them.

This company, among others, has a range of drivers, meeting your volt/current/PWM speed control requirements, with good documentation, manual and use examples. http://www.pololu.com/category/11/brushed-dc-motor-drivers


text:
Arduino Control over the internet
I am really interested in IoT (enthusiastic noob) and I would like to use the arduino board. Here are the steps according to me, with my queries:

User goes to example.com/arduino_switch
Interacts with an HTML form to toggle an action
Sends the data over the Internet (This is the part I have problem understanding)
Arduino receives the data point (how can we do this? polling a url or can we actively send it)
performs the action (easy to do for me)

Any and all help will be appreciated, even if its just pointing me to the right resources.

Check out Xively. You should be able to get something up and running with minimal effort. They have Arduino libraries and example code.

Sounds like a good solution, but I was looking at less of a platform(they tend to have a magical black box approach ) :D.

No problems. There are open source projects, but probably overkill. Are you going to use an ethernet board? A lot of people use Heroku and there are quite a few Arduino examples. As for sending stuff over the internet. Unless you can get a public IP for the Arduino, polling is probably the best bet. Check out the HTML GET, POST and PUT messages.

kiwiron has a great answer, but I have a few things to add:

You don't have to risk security... you can create a VPN to your network or you could just stay inside local LAN. It's just if you want to access it from outside
If you can't get a static IP for your network from your ISP, you can use something like No-IP to give you a name like example.no-ip.biz that's easier to remember and it will change the IP when your IP changes. I've used them before...
A Raspberry Pi might be a good partner in crime to work with the HTTPS connection with a web server like Nginx and with PHP to run a script. I personally like the Arduino better for interfacing with the actual components since it is 5V and has 40 mA per pin, but it's possible that you could use the GPIO pins on a Pi for your server. This might be a little cheaper since you can remove the ethernet shield and replace that with USB.
For the approach of polling a web server, it might be better to have the web server send a GET request to the Arduino and then the Arduino can respond ASAP.

For this, you might want to learn the basics of HTTP headers and try to figure out what goes on behind the scenes.

(how can we do this? polling a url or can we actively send it)

Assuming you're using the Arduino directly, here's roughly what would happen:

The client would request the Arduino for the content for the homepage using HTTP requests
The Arduino would send the content and close the connection
In the HTML there's a little attribute to the form that tells it to send the data via post to response.php. The client hits "submit" and it sends the data via POST to that URL.
The Arduino sees that it's sending data to that URL and reads the data and then process it accordingly. The socket is closed.

You have two choices:

The Arduino regularly communicates with an external web server, sending data and asking if there is anything to do. This is the way Mitsubishi heatpumps can be controlled from the web. The advantage is that your internet connection does not need to publish a web server. Drawback is that the communication is slow (being dependent on the polling interval), plus the need for a web server to talk to. For instance, to control your Mitsubishi heatpump, you need to create an account on one of their servers for the purpose.
The Arduino exposes a web interface that is then exposed to the internet. This needs configuration of your internet router and preferably a static IP address on the internet. Security is a problem, and I'm not sure that even the Due can do HTTPS plus some form of authentication. I used this method, but fronted my Arduino with an old laptop running Linux and Apache web server. The laptop does the authentication and HTTPS processing. Advantage is near real-time control; disadvantage is the amount of hardware and configuration required.

I feel the first one will meet my needs well (can manage with polling every five minutes). Can you point me to any specific reading material, especially something to learn the process of communicating with a web server and publishing the server.


text:
"EVERY_N_MILLISECONDS"
One of the FastLED examples that I've seen was using code that looks like this:

EVERY_N_MILLISECONDS( 300 ) { transition_step(); }

I've copied it and successfully used it in the same context - but I have no idea what it is or how it works.
A Google search finds no reference anywhere at all.
I'm still a beginner with C but this looks like a Define to me - all being in uppercase - is it defined somewhere in the FastLED library?

Yes, it is defined in the FastLED library.  It is a preprocessor macro which is replaced by a block of code when compiled:
It is a very convoluted bit of preprocessing code that is difficult (even for me) to follow through with lots of concatenations and multiple layers of definition, so my advice is to just not worry about it and just use it.
If you want to try and decypher it all it's in the file lib8tion.h in the FastLED library.

Excellent answer, thank you Majenko. If it's that complicated then I almost certainly won't be able to decypher it without a lot of headache, I mainly wanted to be sure I wasn't misunderstanding something fundamental about the language. I'm guessing that I can't have the thing appearing twice then if it defines Functions...?

Do you happen to know if it is blocking or just a NOP if the timer has not cone yet?

Its a macro that wraps the code you put inside of it to only be run based on the time interval you pass to it. The purpose of it is to allow for timer based code to be ran without having to block the main loop(). When the code is compiled it gets wrapped by other code that governs how the code inside it should run.
Lets say you want to run a method every 100ms. A simple approach would be the following:
// loop() runs the code within it over and over at a rate based on the
// how fast the microprocessor runs - specifically how long it takes
// for the processor to get through the code inside of it.
void loop(){

doMethod();
delay(100);

checkForButtonInput();

}

The issue here is that during the delay(), the delay() function, by its design, hogs all the processor time for 100ms, and so the checkForButtonInput() is not able to check for input, as the program is currently stuck looping inside of delay() until 100ms has passed.
EVERY_N_MILLISECONDS( <mseconds> ){} is the answer here, and you can think of it working to add code to you code like this (although this isn't exactly accurate):
void loop() {
   EVERY_N_MILLISECONDS( 100 ){
  //pseudocode
  //if ( it has been 100ms since last time we did doMethod() ) {
      doMethod();
      // reset time since we did doMethod() to 0
  //}
  //else {
  //  continue...
  //}
  }
  checkForButtonInput();
}

so if it hasn't been 100ms since the last time we were in the EVERY_N_MILLISECONDS wrapped code then we just move on, and so the checkForButtonInput() is called as much as possible and inputs wont be missed.

As @Majenko has said it is defined in the FastLED library http://fastled.io/.  There is also EVERY_N_SECONDS.
It is not necessary to call any other FastLed function in the run loop (such as FastLED.delay()) in order to use these functions.
include <FastLED.h>

void loop() {
   ....
   EVERY_N_MILLISECONDS( <mseconds> ) {
     <your timed code here>;
   }

   EVERY_N_SECONDS( <seconds> ) {
     <your timed code here>;
   }
}

authors: น้ำส้ม น้ำส้ม


text:
Pulldown resistors and multiple switches
Maybe this is a question for Electronics SE but I’m not a member there yet so hopefully someone will have an answer here.
I did an experiment with having some push-to-make buttons connected to my Uno. I copied the circuit from the aduino.cc website and all worked exactly as expected. Here is my schematic of the circuit as I have it now:

The pins are both held LOW by the Pulldown resistor until the switch is closed, when they go HIGH.
All well and good. But I’ve just been looking at the circuit and something puzzles me. I can see a direct connection from Switch 1 to Pin 2 VIA the resistors and the Ground connection – and vice versa, S2 to P1. See my pathway in Red here:

Now, to be clear, this is NOT happening – but I just want to understand why not. Is it just that the 2 resistors in combination provide enough resistance to stop the opposite pin from going HIGH? In which case, this Pulldown resistor is actually serving 2 completely different functions in the circuit…?

An input pin is in what is known as high impedance mode. That is, to all intents and purposes, to the external circuit it looks like a massive resistor to ground.
This resistance can be in the millions of ohms.
So let's redraw your circuit with those input pins as big resistors:

simulate this circuit – Schematic created using CircuitLab
Now you can see how the schematic really looks (see how it's set up so +5V is at the top and GND is at the bottom - the [conventional] current flows then from top to bottom).
So with SW2 pushed (as shown) the current wants to flow from 5V (top) to GND (bottom). That goes through SW2, through R2, and down to ground. Some tiny amount also flows through R4, which represents the input pin.  Since by then the current is already at ground and has reached its destination there is no reason at all for it to then flow back up through R1, and back down to ground again through R3. For current to flow through R1 the voltage at IN1 would have to be negative since current will only flow from a higher to a lower voltage. And since it isn't negative, no current can flow.

This explains it the best way for me. I've marked it as the answer, thank you. So if we were to have NO R1 on this diagram, IN1 would still not go High because that would mean the current would have to flow back through R3 to get to the place where it's already managed to get...?

Call the resistors R1 and R2, the negative terminal Ground, and the positive terminal V+.  The junction of R1 and R2 is connected to Ground.  This holds the resistor ends at the junction to zero volts relative to ground.  Ignoring P2 for the moment, the other end of R2 is open circuit to V+ when S2 is open.  Applying Ohm's law, we have a finite resistance in series with an infinite resistance, so zero volts across R2 when S2 is open.  Thus one sees that voltage across R2 is not affected by voltage changes across R1.
P2 as an input is not completely an open circuit; typically its effect is similar to a multi-gigaohms resistor to some voltage between Ground and V+.
Edit:
More directly, observe that the voltage at the Ground ends of R1 and R2 is zero and remains at zero no matter what S1 and S2 do.  Thus, operation of S1 does not affect voltage at P2, and operation of S2 does not affect voltage at P1.

Sorry, I'm failing to understand this, why would there be zero volts across R2? I assume you mean with S1 closed...? Also, if we imagine replacing the resistors with just conductors, they would presumably have a "finite" resistance as well - but then that just looks like a direct circuit connecting S1 to P2.

@Lefty, see edit

jwpat7 +1 but I'm obviously deficient  in my understanding here so I will need to re-read your answer a few dozen more times before it starts to make sense to me. Fundamentally, I feel that, just because the ground ends of R1 and R2 are connected to ground, that doesn't mean that there is no circuit from  S1 to P2. If you replace the resistors in the circuit with straight conductors, you will see that there is nothing "special" about having a connection to ground - the value of the resistors therefore MUST be important (withing reason)...?

Well yes, there is a circuit from S1 to P2, but the resistors' junction is always at ground, thus any charge anywhere else in that circuit can flow only to that junction and ground. P2 - as an input - has "no" ability (read: very little) ability to source or sink current so with negligible current in R2 then by ohm's law, P2 must also be at ground.

It helped me to draw an equivalent schematic to yours when S1 is closed and S2 is open. P2 is neither high nor low by itself; it is a high-impedance (which is why you need a pulldown or pullup resistor). It is pulled to ground by R2 and the fact that the junction of the two resistors is grounded. If you disconnected that junction from ground, P2 would see a 20K pullup, but as it is, the (left) end of R2 stays at ground, regardless of what you apply to the P1-R1 junction.

simulate this circuit – Schematic created using CircuitLab

A simple rule of thumb is that electricity always follows the path of least resistance. The energy going over the switch has a lower resistance path to ground through the Arduino than it does through the pull-down resistor, so it will prefer to go that way than through one - or both resistors when it is available.

True - but (correct me if I'm wrong) the need for the Pulldown resistor shows that even an open circuit actually needs to be grounded to stop the pin from fluctuating - hence the need for the resistor. It seems to me that I would expect more current to flow through 2 resistors than to to flow through an open circuit..?


text:
Newbie and string of 300 WS2811s
I’m trying to make a string of 300 Christmas tree lights where the colour of each of the lights is entirely controllable by my own code. I am a programmer so that side of things is the easy part as far as I’m concerned.
My researches so far have led me (no pun intended) to WS2811s driven by an Arduino. I prefer the look of these to the flat Adafruit-type ones. I don’t own an Arduino yet but have been dipping my toe into this site for quite a while now so am beginning to understand the basics.
I’ve established that I will need to have a fairly hefty 5volt power supply for the LEDs but that the Arduino itself can then run happily on its own USB supply.
Some of the things I’ve read seem to imply that the Arduino will struggle to process my program and supply the data to 300 LEDs at the same time, but it’s not clear what the problem will be. I assume each LED will continue to glow with the same colour until it receives the data for its next colour and the code for “Fire!” which then prompts all of them to switch to their next colour. Is this wrong?
I realise that 3 bytes per LED for 300 LEDs is a fair amount of data to keep having to send up the wire. I will also be having an array in the program to keep track of all 300 colour values.
Will this work? Can you offer any advice that might mean I don’t hit a brick wall somewhere when putting all this together?

You don't need a full Arduino. You can use either a bare AVR chip or breakout or a small Arduino-like for this.

@IgnacioVazquez-Abrams AVR is a new term I've never heard of, can you link to somewhere I can read-up please? What would be the advantage over Arduino, just cost and physical size?

http://stackoverflow.com/questions/1447502/whats-the-difference-relationship-between-avr-and-arduino

Make sure to provide power to the string at multiple locations. With the amount of current 300 leds use, the small resistance in the wires can create a big enough voltage drop for the leds at the end to be dimmer or malfunction.

@IgnacioVazquez-Abrams Thanks, I think the native AVR may be a bit out of my comfort-zone. I'll get the thing working with an Arduino and move on to the big-boy stuff if I get bitten by the bug! I don't get a lot of time to play with things like this - I really just want some Christmas lights that are better than can buy in the shops! I know I can code a better version and just need the hardware to work.

@Gerben Thank you, this is exactly the sort of information I didn't want to find out the hard way. Do you think it would be adequate to just supply the power at both ends? That's quite common on Christmas lights from my experience.

It depends on the wire-gauge, and total wire length. But on second thought you will probably be okay. It's more of an issue in led strips, with only thin copper traces carrying all the current. Wires have a lot bigger cross-section area. But providing power at both end would be a good idea. By the way, a lot of boards, and strips, have decoupling capacitors sprinkled around. I think that would be more important that power.

@Gerben of course, with 300 of them I have to provide up to 18 amps at 5 volts (300*0.06) so thàt will mean a hefty power supply. I'm not familiar with the concept of decoupling capacitors, can you explain please?

The leds are dimmed using PWM. So constantly alternating between using power, and not using power. This creates small power fluctuations  called noise on the power line. If there is enough noise, the chip on the WS2812 will malfunction. The capacitors act like little local reservoirs of power, keeping the power supplied more constant (/less noisy).

I don't think you'll have any problems. The LED's have a data rate of 800kbps, so you can theoretically push out 110 frames per second if your Arduino does nothing but transmit data. If you keep the routine that updates the colors fairly efficient then you'll have nothing to worry about.
Note that the array storing the colors would take up 900 bytes of memory, leaving you with only 1100 bytes for everything else your program would need to store (which should be fine).

Thanks Tom. I didn't realise that there is only 2K of memory on board, I'm sure I will be able to work with that though. I saw a video where this guy says something like "The Arduino will struggle to provide data fast enough", so I was a bit concerned about the speed.

@Lefty of course speed is a concern, but... Since the application requires low resources (you will not make really complex animations, will you?) you won't have issues. Just don't waste too much time in useless things, don't use delays and try to use 8-bit variables.. And avoid mallocs or variable size buffers

No complex animations - just colour fades of individual LEDs which will be fairly sedate. In a way, what I want is to be able to just send data for ONE LED at a time but I realise that there is no actual address for each LED, just this clever bit-shifting thing where each one steals the first 3 bytes and passes the rest on. I take it Delay uses an internal loop to waste cycles? What about the LEDs? Will they maintain the same colour until the next refresh signal?

Yes, they maintain their states.

Excellent, thank you. Unless anyone else gives an answer that concerns me, I think I will invest in the equipment and hopefully get this all working. Is it worth me buying a particular type of Arduino that may be faster just to be sure?

@Lefty: The Arduino will struggle if you restrict yourself to Arduino operations. Using low-level AVR operations (or using a library that does so) will let it keep up handily.

Specifically, FastLED is a good library.

Thank you both, I will look into all this before I start the project. Maybe I'll get it working with just 50 LEDs initially and expand slowly until it hits any problems. Would it be viable to write the program in C initially and then gradually replace the process-heavy parts with low-level code where I need to? Remember that this is all new to me so I have a lot of learning to do!

Using FastLED to get started would help a lot. I don't think you'd need much optimization besides that.

If you only want one led to change at a time, you could choose to make e.g. 5 separate strings of leds. That way you only need to send 1/5th the amount of data per "frame".

@Gerben Amazingly, you have hit upon exactly the idea that I want to do - just change every 5th LED in each change cycle while the others are static. But I really want to keep the number of wires down to a minimum so I don't want to have an extra 4 wires. I also want them to be in one long string. I figured that I could create my "one in 5" idea in software whilst keeping the hardware configured for different future options if I want to change the pattern.


text:
Arduino User Input
Is it possible to accept input from an end user via terminal, or some other application?
I want to create a prototype for a friend, but he'd need to enter his wireless network and password to complete the setup of the project.
Any advice?
Thanks!

Use Serial. It can be used to send text to the console, and receive text-input from the user.

Is there a way to use the c prompt? I hate to have him download something and hung up on the install. I realize it's simple but he's not computer savvy. Thanks for the info!

No, you can't do it from the "c prompt". You need some kind of serial terminal. Many versions of Windows come with Hyper Terminal which will do the job.  Downloading a terminal program isn't a onerous task or particularly difficult. There are many to choose from and they are easy to install.  I have never known one to get "hung up on the install".

Since you have mentioned that all that you want your friend to do is enter the WiFi SSID and password, I am gonna assume that its where his interaction with the device ends.
In this case, I would recommend using the arduino YUN, it cant get simpler than that.
The YUN is capable of creating an AP network, your friend can connect to it and then go to the arduino home page and then connect to his WiFi.
EDIT:
Another option would be to use a matrix keypad and LCD screen and have your friend manually enter the details

Ya, I see that recommendation, thought of it, but don't think 80 bucks is worth the project to buy the yun.

you could always use a matrix keypad and a LCD display for entering the details.
Via the computer will involve installing drivers and will require you to create a simple app to send data via the serial port

Yes, I think that's going to be the best answer. Thanks :)