text:
How do I change pin assignments for the LUFA AVRISPMkII?
I just managed to get Dean Camera's LUFA AVRISP clone working on my Arduino Pro Micro, when to my dismay I found that to use PDI for my XMega, I need to have PD5 exposed for the clock source! The Pro Micro has PD5 connected to an LED, so I am not easily able to use it.
If worst comes to worst, I can desolder the LED and wire a jumper, but that would be a pain in the butt. So I am wondering if any of you know if I can change the clock pin assignment from PD5 to PD6 or some other accesible pin. Thank you in advance for your help!
--[[ EDITS ]]--
Sorry for my lack of clarity, I am using the Pro Micro as the programmer, and the AVRISP clone supports PDI to the XMEGA. The 32u4 is actually directly supported by the programmer firmware. Here is what I am doing:
--[[ EDITS II ]]--
There is a schematic.. umm.. draw-o? I don't know but anyway the cathodes of D1 and D3 are NOT connected. That wire is an error.

simulate this circuit – Schematic created using CircuitLab
--Cantos

Umm, moderator? I do not know if this really belongs in arduino. I am not using any Arduino software or anything, and is more relavant to general AVR programming...

Mentioning Arduino in AVR questions on electronics.SE is like tagging a C question with C++ tag on SO. People will pay attention to the respective artifact instead of the question itself.

Okay, I'll remember that

Note that you may also bring your question up on meta if you feel the migration should be reversed. I doubt leaving your question on arduino.SE will bring you answers, while you got at least one on EE.

Do you have access to the source code? I can't seem find it. Only the .hex files. If only the hex code is provided, it won't be easy to change the pin mapping in the code. That would involve decompiling the hex etc.. I don't see anything particularly special about pin PB5, so changing the code to PB6 would most likely be possible (provided you have the code).

I do have the source code (it has to be built from source for this processor). I guess I will just serch through it until I find the pin assignment :)

I found the answer searching through the Doxygen files. I had to go to AppConfig.h under Config in the project root directory, and edit AUX_LINE_MASK to change the pin. Thanks to everyone who helped!

Can you give more details on your problem? Schematics or something like that?
As I see from here, the Arduino Pro Micro uses ATmega32u4 chip, which is not part of XMega family, so I'm not sure if their internals are mutually compatible. In any case, if you configure PD5 as an input for your clock, it will work as an input, since it's a GPIO pin (DDRD &= ~(1<<PIN5)). You'll just additionally have the LED blinking :). You can also configure PD6 as an input in the same way (DDRD  &= ~(1<<PIN6)).

just in case anyone else is trying to use a Pro Micro as a makeshift PDI programmer with the AVRISPMKII firmware included in the LUFA library: contrary to what the OP claims to have accomplished by editing AppConfig.h, it is NOT possible to reassign the XCK pin on ATMEGA devices (at least not to my knowledge). I can only conjecture as to why he made that claim (perhaps he confused XMEGA/ATMEGA, and thus ISP/PDI). I do not wish to blame the OP, but his post had sent me and others down a dead end for a minute, too bad there is no easy fix like that. :(
The XCK function is hard-wired to the pin, in this (ATMEGA32U4) case PD5. The LUFA code utilizes the ATMEGA's USART transmitter configured for synchronous operation, hence a clock signal must be provided to transfer data to the target device. That's why XCK must be used and there is no other way, at least not with LUFA. The call that enables the PDI target has nothing to do with the AUX_LINE define in AppConfig.h
The only way a Pro Micro board can be used is by either soldering a wire to the XCK pin or by holding a wire against it (if you can hold it steady for a couple of seconds without slipping, that is). Thus, if you need a makeshift PDI programmer that will not require soldering, get a Teensy 2.0 or something else that breaks out PD5 as a GPIO pin.

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


text:
Mysterious RX pulses on UART connect on OS X Arduino Due
Arduino IDE 1.6.8, Arduino Due, Mac OS 10.11.3
I am seeing eight mysterious pulses on the RX line when I connect to the serial port using multiple client libraries (Python, JavaScript as well as the built-in Serial Monitor in the IDE). About 78-79us apiece, sampled at 1MS/s with a Logic Pro 16.

These eight pulses when interpreted at 57600 baud will jam the Firmata firmware. And they happen on every connection.
This is using a new install of the Arduino 1.6.8 IDE and with multiple sketches (the normal "Blink" sketch will reproduce this also).
Repro steps on my machine:

Install any sketch
Start a logic analyzer if you want to catch it
Go to Serial Monitor. I have mine configured for 57600 baud, Newline line ending, but it doesn't matter
If you want, close and repeat step 3
Note pulses each time you connect to the serial port

Any suggestions for diagnosing this? It sounds like it's serial driver-level in some way.

Regardless of where it is coming from, consider that it has done you a favor by indicating a critical bug in the firmware you are running - this should not be able to put it in an unrecoverable state.  Is it a program logic bug, or does the UART handling code not deal appropriately with an error flag?

In terms of tracking down the source, it would be helpful to try another serial  client program, another computer/operating system, another USB-serial device, etc...

Thanks for the input, Chris. When the Firmata firmware sees a 0xF0 START_SYSEX, it will process bytes until it sees a 0xF7, and there is no provision for a timeout. So I think what is happening is that these pulses generate a 0xF0 (you can see this from my decoding) which effectively turns off further command processing since there is no terminating 0xF7. I think that the best thing I can do for Firmata is submit a patch to time out after some interval that is long enough for the longest legitimate data packet.

As for trying other serial programs, there are multiple libraries that interact with the Firmata protocol and use different underlying serial implementations (Python, JavaScript and the built in Arduino IDE Serial Monitor) that exhibit the same behavior. My next plan is to try this on a Linux machine and see if I see the same behavior, which will hopefully isolate if this is OS X-specific.

You get a single pulse on Linux that is interpreted at 57600 as 0xF0

You also get one when you disconnect. The connection baud rate has no effect on the length of the pulse. My suspicion is that it's the ATMega16U2's firmware that is doing it (or whatever chip it is on whatever version).

Is your Arduino taking the power from the USB?

When you start the serial monitor, software resets the arduino module. If arduino module has bootloader in it, i think these are the STK500 protocol signals.

Short:
Looking at the ATMEGA16U2 firmware (https://github.com/arduino/ArduinoCore-sam/blob/master/firmwares/atmega16u2/arduino-usbserial/Arduino-usbserial.c) I find that, when you configure/change settings of the USB emulated serial port, the USART is resetted. This happens even when you open the Arduino Serial Monitor (it must configure the serial speed, etc.). This causes your spike.
Long:
Look at function:
void EVENT_CDC_Device_LineEncodingChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo)
There you'll see that after some lines, it resets the USART, by zeroing its registers:
/* Must turn off USART before reconfiguring it, otherwise incorrect operation may occur */
    UCSR1B = 0;
    UCSR1A = 0;
    UCSR1C = 0;

At page 168, of the current ATMEGA16U2 datasheet, you'll find that, by setting  UCSR1B's bit 3 (TXEN1), you enable the transmitter,  overriding the normal port operation (i.e. it becomes output). Quoting the datasheet:

Writing this bit to one enables the USART Transmitter. The Transmitter
  will override normal port operation for the TxDn pin when enabled. The
  disabling of the Transmitter (writing TXENn to zero) will not become
  effective until ongoing and pending transmissions are completed, i.e.,
  when the Transmit Shift Register and Transmit Buffer Register do not
  contain data to be transmitted. When disabled, the Transmitter will no
  longer override the TxDn port.

Therefore, by writing UCSR1B = 0; you no longer override the TXD1 pin, which will act as input.
The ATMEGA16U2 TXD is connected to the ATSAM3X8E's RX line. In normal operation, with the UART enabled, that line stays high if no data is being transmitted. If you disable the UART, that particular line is no more driver to 1. Since the initialization code does not set the pull-up on that pin (and neither it's configured as output), the pin becomes a floating input, and any leakage to GND or even the input impedance of your probe (which is between your pin and GND), will slowly bring the logic level to 0.
To override this, problem, you should either:
1) Modify ATMEGA16U2 firmware, by setting that PIN as OUTPUT, with value 1.
2) Modify ATMEGA16U2 firmware, by enabling the pull-up on that pin.
3) (suggested) Enable the pull-up on the RX line on the ATSAM3X8E.

source: Stack Exchange

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

sort: votes


text:
How to convert String to byte array
I have the code, it's purpose is to receive the string from a comport like:
Set@1234567890123456@1234567890123456@1234567890123456@1234567890123456
and translate it into four byte arrays byte user1[16], user2[16], pass1[16], pass2[16]. Here's the code:
String inString = ""; // COM port incoming data buffer

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

void loop() {
  // put your main code here, to run repeatedly:
  // Receive data from com port
  while (Serial.available() > 0) {
    int inChar = Serial.read();

    if (inChar != '\n') {
      inString += (char)inChar;
    } else {
      // New line
      String Action = inString.substring(0, 3);
      if (Action == "Set") {
        SetCard(inString);
      } else if (Action == "Get") {
        Serial.println("1");
      } else {
        Serial.println(Action);
      }
      inString = "";
    }
  }
}

void SetCard(String Data) {
  Serial.println(Data);
  // Data Set@user1@user2@pass1@pass2
  // Set@1234567890123456@1234567890123456@1234567890123456@1234567890123456
  byte user1[16], user2[16], pass1[16], pass2[16];

  String user1str = inString.substring(4, 20);
  String user2str = inString.substring(21, 37);
  String pass1str = inString.substring(38, 54);
  String pass2str = inString.substring(55, 71);

  Serial.println("Strings");
  Serial.println(user1str);
  Serial.println(user2str);
  Serial.println(pass1str);
  Serial.println(pass2str);

  Serial.println("Arrays");
  user1str.getBytes(user1, 16);
  user2str.getBytes(user2, 16);
  pass1str.getBytes(pass1, 16);
  pass2str.getBytes(pass2, 16);

  writeByteArray(user1, 16);
  writeByteArray(user2, 16);
  writeByteArray(pass1, 16);
  writeByteArray(pass2, 16);
}

void writeByteArray(byte array[], int arrlength)
{
  for (int j = 0 ; j < arrlength ; j++) //print the block contents
  {
    Serial.write (array[j]);//Serial.write() transmits the ASCII numbers as human readable characters to serial monitor
  }
  Serial.println("");
}

When I run this code and send my string through a com port I expect the output:
Start
Set@1234567890123456@1234567890123456@1234567890123456@1234567890123456
Strings
1234567890123456
1234567890123456
1234567890123456
1234567890123456
Arrays
1234567890123456
1234567890123456
1234567890123456
1234567890123456

And yet, I receive
Start
Set@1234567890123456@1234567890123456@1234567890123456@1234567890123456
Strings
1234567890123456
1234567890123456
1234567890123456
1234567890123456
Arrays
123456789012345
123456789012345
123456789012345
123456789012345

Why? And how do I receive desired output?
getBytes docs

Why? And how do I receive desired output? getBytes docs

The String member function getBytes() will null-terminate the string. You must add space for that.
  byte user1[17], user2[17], pass1[17], pass2[17];
  ...
  user1str.getBytes(user1, sizeof(user1));
  ...
  Serial.print((char*) user1);

That should do the trick.

Thank you. It worked. So, how can I truncate user1[17] array to user1[16] after I set it value with getBytes?

Or do I need to create a buffer array[17] and then write the first 16 elements from there to array[16]?

Come to think of it I could just   for (int j = 0 ; j < sizeof(user1) ; j++)    {     user1[j] = user1str.charAt(j);   } and it would work with 16 elements

Using String.getBytes(buffer, len) to get bytes.
"len" is the length to copy, but usually need to add 1 for the end of string '\0'.
For example:
String s = "123";
int count = s.length();  // lenth() is 3
s.getBytes(buffer, count);   // copied "12\0" => HEX(31 32 00)
s.getBytes(buffer, count + 1);   // copied "123\0" => HEX(31 32 33 00)

The official document not mentioned those above, and it's not reasonable for the modern function design.
Misunderstanding in that and waste our life so much.

toCharArray() is documented https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/tochararray

toCharArray(buffer, len) will still keep the last bye for 0x00 ('\0'). So if want to copy the specific length of the content, len should add 1 for '0'. Also, care the buffer length as the last damn byte.

that is what is expected for char-array (C string) (but not expected for getBytes)

If the official document has mentioned the '\0' in details, it's fine for purpose. It's pity for none.

I am heaving difficulties reading your post and comments. How do you declare buffer?

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


text:
ESP8266 blue led stays stays on
I have found a similar qustion to mine but there was no good response.
I've connected my ESP8266 to Arduino UNO.
Then I got some trouble with software serial communication with Arduino and decided to change baud-rate to 9600 (previously it was 115200).
I used AT+IPR=9600 command to change it.
After that blue led of esp stays on and not taking AT commands any more, but output some gibberish to serial monitor.
Note: I connected the esp8266 through a voltage regulator and a power source and both gave the same problem. My firmware is supposed to be updated so I don't think that it is the issue.
Could anyone please help me?

You have changed the baudrate. Try to match up your UNO's baudrate with your new baudrate. Unmatching baudrates will indeed cause gibberish. Maybe the "updated firmware" is actually the problem, since the device isn't responding well, try to re-update the firmware (when you know which baudrate it is).

Did you change the firmware? I think Baud rate can be changed only if you flash it with newer version of the firmware.

Yes I changed the firmware. The problem is that when trying to change the baud rate back it is not accepting any AT commands even though I tried with different baud rates.

as mentioned by paul, have you tried to reupload the firmware ? I found  Nodemcu Flasher to be the easiest way to upload the firmware. Also create your self a simple flashing setup like this one. It is worth making if you plan to use ESP8266.


text:
What does it mean in I2C, "NACK received"?
I am reading about I2C. On this site:
http://playground.arduino.cc/Main/WireLibraryDetailedReference#endTransmission
It says that endTransmission() can return one of the following status codes:

0: Successful send.
1: Send buffer too large for the twi buffer. This should not happen, as the TWI buffer length set in twi.h is equivalent to the send buffer length set in Wire.h.
2: Address was sent and a NACK received. This is an issue, and the master should send a STOP condition.
3: Data was sent and a NACK received. This means the slave has no more to send. The master can send a STOP condition, or a repeated START.
4: Another twi error took place (eg, the master lost bus arbitration).

If I attach nothing to my Arduino (or with pull-up resistors to both SDA/SCL), I always get status 2. But how can a NACK (or anything) be received when there is nothing to communicate with? Does it mean something else?
Here is my example code
#include "Wire.h"
void setup() {
  Serial.begin(9600);
  Wire.begin();
}
void loop()  {
  Wire.beginTransmission(42);
  Wire.write(0);
  byte status = Wire.endTransmission();
  Serial.println(status); // always prints 2
}

A NACK is signaled by an acknowledgement slot in which SDA remains high while SCL cycles under control of the master.
Since high is the un-driven state of the pulled-up bus, in the absence of a peripheral at the selected address to positively acknowledge by pulling it down, a NACK condition will passively result.

Could you please elaborate more? You mean that peripheral is not connected? How about was able to get data for a while, then it stopped working and keep return 0x02?

Anything that means a peripheral fails to respond can cause this - no peripheral, broken traces or wires, wrong address, noise making the address look wrong, weak pullups distorting the data, absurdly strong pullups distorting the signalling, bad power, buggy software or silicon design in the peripheral, even mismatching support of extensions like clock stretching.


text:
Sizing relays for audio circuit?
Non-technical person here, so please be gentle. I moved into a place that has ceiling speakers in each room (I tried, but they don't come apart, aren't marked other than manufacturer, and that is a company that went out of business 15+ years ago). So, let's assume they are 8 ohm speakers.
I have a media amplifier, and have successfully played music over all the speakers so I know that they work.
My wife would like the ability to select which speakers are on or off, so I'm thinking a quick Arduino project and relay board with 8-12 relays... but I'm not sure how to estimate the load, so I don't know how to appropriately size the relays.
Any suggestions on the best way to do this, or should I just get mains-rated relays and over-engineer the heck out of this?

Unless you're working with kilo-watt level audio equipment it'll be hard to under engineer it with relays.

Bear in mind you may need transistors to drive the relays. Don't forget the snubber diodes over the relay coils. You can buy "speaker switch boxes" which might be a simple solution.

Pretty much any "Arduino" relay board on eBay will be more than adequate and contains all the drive circuitry you need.

Relay's will do the trick. You might try FET's or transistors, which might become under-engineering at some point.

You wouldn't even need an Arduino, to be honest. Just put in some switches that power on/off the relays.
Unless you would like to make some kind of web-interface or timing schedule or anything that's not 1-on-1 connected with a switch :)

See a similar project I did: http://iceboundflame.com/projects/multi-room-audio-control-with-rpi and related question about speaker current: http://electronics.stackexchange.com/questions/155779/home-audio-how-much-current-flows-through-my-speaker-amplifiers-output

If you can estimate speaker power, it probably is reasonable to use the ordinary power formula P = I²R for estimating the current the relay needs to handle.  Typically, high-power speakers of a given kind are bigger than low-power speakers of the same kind.  But as you can see from pictures of
5W,
10W, and
40W speakers, some 10W speakers are smaller than some 5W speakers, and some are bigger than 40W speakers, so power estimation based on speaker size can be difficult.
If you have access to the sound source (tuner or player or whatever, connected to an amplifier) you may find output power listed on the amplifier.
In any case, due to the I² term in the power formula, the range of current to plan for is relatively small.  For example, if 5W is going to an 8Ω speaker, 5/8 = I², and I =  0.79 A.  If it's 40W, then I = 2.24 A.  This range is likely to be handled ok by relays sold for ordinary use with Arduino systems.
Note 1: A relay's current rating ordinarily is derated significantly when the relay is used to switch DC or high-voltage AC.  Audio is low-voltage AC and relay derating probably isn't needed.  Note 2: The current a relay can safely switch in a live circuit may be much less than the unswitched current that closed contacts can carry.  This might not be a problem with low-voltage audio.  Note 3: Some commercial high-wattage audio distribution systems operate at higher voltages (see, eg, wikipedia's high-voltage audio distribution systems article, re 70.7 V etc systems); if you have one of those – as amplifier labeling might reveal – the example calculations shown above would need adapting.


text:
Comparison of a bit vs. setting a bit
Simple question really, I just want to be sure that I understand it correctly. I understand this isn't necessarily Arduino specific.
With regards to the ATmega2560 I'm doing 3 back-to-back A/D conversions - one immediately after the previous finishes. I'm accomplishing this by calling a Single Conversion each time.
I stumbled across this useful code to wait for the conversion to finish:
while(ADCSRA & (1<<ADSC))

I understand that it is waiting for the conversion to finish and that when this is done the ADSC will be set to 0. (Conversely, I could wait for ADIF to be set to 1.) I'm not as clear on how exactly this line is interpreted.
Normally when I see something along the lines of (1<<ADSC) it means write a 1 to the ADSC bit.
But, in this instance, that isn't the case.
Why not just write:
while(ADSC);

You misunderstand the meaning of:
1 << ADSC

That actually means Bit-shift 1 left by the number of bits specified by the value ADSC.
ADSC in this case is 6:
#define ADSC    6

So if you did:
while(ADSC);

you would actually be doing:
while(6);

Which of course will never end, since 6 is not 0, so is true.
Instead you shift 1 left 6 times, which in binary would be:
00000001
    << 6
01000000

That, of course, is 64, or 0x40 in hexadecimal.  That is then ANDed with the value of the ADCSRA register to return the value of one single bit within that register.  It's then the result of that AND that you control the while with.  So it ends up as:
while(ADCSRA & 0x40);

Which will either equate to:
while(0x40);

if the 7th bit is set, or if it's not set:
while(0x00);

And since 0x00 is 0 it will equate to false when the bit isn't set and the while will finish.

I should've specified because I think it will make a difference, my apologies, ADSC is a flag in the ADCSRA register.

It is also a #define for a number. In this instance it is the number of the ADSC bit in the register. You use it to manipulate the register - you can't (easily) manipulate the bit by itself.

There is great support for this in the AVR library. Please see http://www.nongnu.org/avr-libc/user-manual/group__avr__sfr.html. This also helps explain the AVR MCU registers and bit field symbols and usage. loop_until_bit_clear(ADCSRA, ADSC);


text:
Failed to read DHT22 sensor using Intel Galileo Gen2 board
Why do I end up with the display

Failed to read from DHT sensor!

in the serial monitor in most cases when I run the code given below? When I reduce the delay to 1000ms the reading shows 0.00 for both temperature and humidity which, as well, is pretty much false. Any help would be highly appreciated.
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

#include "DHT.h"

#define DHTPIN 2     // what pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);
// NOTE: For working with a faster chip, like an Arduino Due or Teensy, you
// might need to increase the threshold for cycle counts considered a 1 or 0.
// You can do this by passing a 3rd parameter for this threshold.  It's a bit
// of fiddling to find the right value, but in general the faster the CPU the
// higher the value.  The default for a 16mhz AVR is a value of 6.  For an
// Arduino Due that runs at 84mhz a value of 30 works.
// Example to initialize DHT sensor for Arduino Due:
//DHT dht(DHTPIN, DHTTYPE, 30);

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

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index
  // Must send in temp in Fahrenheit!
  float hi = dht.computeHeatIndex(f, h);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hi);
  Serial.println(" *F");
}

Is that library designed for the Galileo? I see that it runs at 400 MHz, whereas the library (when I last used it) was for a 16 MHz Arduino. The DHT11 uses a highly timing-specific protocol. A search for intel galileo dht11 revealed DHT workaround for Galileo and Galileo Gen2 using 2 pins instead of one

This is only because i am using the same material as from where ctrl+c and ctrl+v was done! :) Further adding to it, please can you specify in detail the pin connections? means in simple words like which pin is to connect diode with, which pin to connect resistor with from the link you have shared above! (also the specification of diode and resistor). Thanks mate for the help!!! Cheers..

And in addition I am using 3 pin DHT22 (Vcc, Out, Gnd).

The article link by Nick is the same that I found, so it must be a well search problem.
What is described on the Intel forum is that the Galileo is not capable of direct communication with the sensor as it is a computer and not a microcontroller, so therefore lacks the ability for accurate timing required by the sensor and also the DHT* is considered a peripheral and would thus require a way to interface with the "PC".
What is described in the post is to use two pins to create the proper digital signal for the DHT.
The circuit makes use of a diode to protect the output pin.
The OP on the forum describes the connections like this:

Pin 2 of Galileo is connected to the data pin of the DHT11.
Cathode of the diode is connected to pin 3 of the Galileo.
Anode of the diode is connected to the DHT11 data pin.

The diode would be a standard diode, possibly a fast switching signal diode as the 1N4143. The resistor would be the standard pull up resistor of 10K Ohms.
Here is the OPs schematic:

(source: intel.com)
You will also need to make use of the code linked to by the OP in the linked post as it was modified to work with the workaround.

Here it is written, "pin 2 is connected to the DHT11", But whose Pin 2 to connect to DHT and on which pin of DHT i should connect.

@JayM hi, the PIN2 is the Galileo and PIN3 is also the Galileo. Pin 2 is connected to the data pin of the dht, while pin 3 is connected to the cathode of the diode and the anode of the diode to the data pin of the dht check this schematic from the op https://communities.intel.com/servlet/JiveServlet/downloadImage/2-245223-237707/DHTGal.PNG


text:
How can there be not enough current?
I am new to the Arduino world. I have a question regarding current that the Arduino outputs over its 5V port. Why is the current in the Arduino too weak for current hungry circuit when the only thing that changes in this equation V=IR is the current itself.
For instance, the voltage in an Arduino is restricted to 5 volts. Assuming that the resistance of the current stays the same, shouldn't the current also increase (following Ohm's law) over its 5V port? More specifically, I am talking about powering ESP8266 with an Arduino.

Are you talking about the microcontrollers pins or the 5V power point, the reason why the later would be restricted would be because of the type of regulator not being designed for current hungry applications.

When I enumerate my Arduino using USB I see this: MaxPower              100mA - so it is only requesting 100 mA from the USB port. Can you clarify what you mean by: Assuming that the resistance of the current stays the same ...

Why is the current in the arduino too weak for current hungry circuit ... there isn't "current in the Arduino" in the first place.

The problem is not that "there is not enough current", but that you can't dissipate enough power.
Let's assume you are powering the board from an external 12V supply. Now, the 5V are obtained from 12V with a resistive regulator: this means that the regulator (see this image if you are interested in knowing what component it is) simply behaves like a variable resistor, dissipating the power in excess. Now, let's assume you want to draw 4A from the 5V rail, since you want to turn on a lot of LEDs and other stuff. Since P=VI, the regulator (that very little component) has to dissipate (12V-5V)*4A = almost 30W. This means that it becomes a little heater and.. Puff! it breaks.
Now, 4A is a really high current, but that regulator can withstand very little power dissipations. According to the datasheet, and estimating a 1cm x 2cm heatsing under it, we can estimate a 25 K/W thermal resistance, which means that each watt you dissipate raises the internal temperature by 25K (=25°C). You can't go beyond 150°C without damaging the component, which means that if your room is at 25°C you can dissipate AT MOST 5W. In practice, never go beyond 3W. Anyway even 5W mean that, at 12V, you can't get more than 5W/7V=0.7A.
By the way, the regulator is rated 0.8A, so you should never go beyond that value in any case.
Now, this was the external regulator. As for the usb, you can't get more than 500mA from that power supply. That's written in the specs. For this reason, a 500mA fuse is on that rail, so going beyond 500mA will blow that one, interrupting your power. Well, that's a self-healing fuse, so after some time (maybe hours?) it will operate again, but.. Don't try that.
In the end, the digital pin current. The atmega datasheet says that

The absolute maximum current per I/O Pin is 40.0mA
The absolute maximum current inside VCC and GND Pins is 200.0mA

This means that from each single pin you can get at most 40mA (but I suggest you never go beyond 20mA), and the sum of all the currents (and the internal peripherals) should never exceed 200mA. So if you need to power 2 leds, you can give each of them 20mA, if you need to power 15 of them you can't (you are limited to, let's say, 10mA). If you need more, use transistors to separate the current paths.

More than likely, the reason for the 20ma/40ma safe/absolute limits per pin is not a current cutoff, but as your first sentence states, the inability to dissipate enough power - specifically, heat - to exceed them without eventual damage. They probably would pass more than 40ma, briefly, but fail, doing so.

The per pin limits are of course due to the thermal design of the IC. Probably because of the wire bonding diameter, or the IC traces width, or the parasite resistor, or... Whatever, the Atmel characterized the IC and stated that you should not exceed it, otherwise you COULD damage it. Of course, maybe getting 10A for 1ps can leave you with a sane IC, but.. Hey, no guarantee ;)

Could you explain how you would use a transistor to separate the current path? I have tested some things with PNP and NPN transistors but I did not know you could use that to separate the current path. I just used them as logic gates.

@steven well, if you attach an NPN base to an arduino output through a resistor (usually in the range 10k-47k), emitter to ground and the load to the collector you just separated the two current paths, since now the load discharges through the NPN instead of the arduino. So.. using an NPN as switch actually "separates" them. Personally I tend to prefer nMOSs instead of NPN (and pMOS instead of PNP) because they behave more "ideally" in my mind ;)

A very simple answer:  The Arduino is limited to an absolute 40mA per pin, because within the controller chip (ATMega328 usually) the path the current follows is very small.  More current can destroy the tiny transistors in the chip.  Best case, you burn out that pin.
If you have a problem that requires more than 40mA (and really, as other posters point out, 20mA!) you should be using a transistor, mosfet or relay controlled by the Arduino, rather than directly power the end device.


text:
Arduino digital input fluctuates with neighbouring pins
I am using digital pins (2,3,4,5) to play midi notes on and off with 3pdt switches with pull down 10k resistor between input pin and ground.
However when I press button 2 randomly at different time interval it sometimes shows pin 3 high in the monitor. (after reading forums here I have realised that it might be due to big switches that I am using where the physical contact plates might be reason for this). I have even changed wires and isolated them from each other to rule out the noise from the wires.
I have checked all the connections and soldered the Arduino board pins with best possible skills that I have and tracks are all clear.
Same case occurs between other buttons as but its not always.
However after reading about Debounce I have made changes to the code as following, now I got the error only once after that I havent seen it. Can someone have look at the code and advice me if I have assigned Debounce function to multiple switches correctly and if not, what should it be as I am new with coding
Since I am using 3pdt switch I have added switch mode..
#include <MIDI.h>

int buttonPin[] = {2, 3, 4, 5};
byte mode[] = {0, 0 , 0 ,0};
boolean currentState = LOW;
boolean lastState = LOW;
int buttonPinM[] = {6, 7, 8, 9};
byte mode1[] = {0, 0, 0, 0};

boolean currentState1 = LOW;
boolean lastState1 = LOW;

long lastDebounceTime = 0;
long debounceDelay = 50;

void setup (){
    MIDI.begin(MIDI_CHANNEL_OMNI);

    int i;
    for (i = 0; i < 4; i++) {
        pinMode(buttonPin[i], INPUT);
    }
    int j;
    for (j = 0; j < 4; j++) {
        pinMode(buttonPinM[j], INPUT);
    }

    {
        int i;
        for (i = 0; i < 4; i++);
    }
    {
        int j;
        for (j = 0; j < 4; j++);
    }
}

// This will track which pin/mode we're using

int j = 0;
int i = 0;

void loop () {
    {
        currentState = digitalRead(buttonPin[i]);

        if ( (millis() - lastDebounceTime) > debounceDelay) {
            switch (mode[i]) {
                case 0:
                    if (currentState == HIGH) {
                        MIDI.sendNoteOff (i+55, 0, 1);
                        mode[i] = 1;
                        lastDebounceTime = millis();
                    }
                    break;
                case 1:
                    if (currentState == HIGH)
                        mode[i] = 2;
                    break;
                case 2:
                    if (currentState == LOW) {
                        MIDI.sendNoteOn (i+55, 127, 1);
                        mode[i] = 3;
                        lastDebounceTime = millis();
                    }
                    break;
                case 3:
                    if (currentState == LOW)
                        mode[i] = 0;
                    break;
            }
        }
        lastState = currentState;
        if (++i > 3)
            i = 0;
    }
    {
        currentState1 = digitalRead(buttonPinM[j]);
        if ( (millis() - lastDebounceTime) > debounceDelay) {
            switch (mode1[j]) {
                case 0:
                    if (currentState1 == HIGH ) {
                        MIDI.sendNoteOn (j+61, 127, 1);
                        mode1[j] = 1;
                        lastDebounceTime = millis();
                    }
                    break;
                case 1:
                    if (currentState1 == HIGH)
                        mode1[j] = 2;
                    break;
                case 2:
                    if (currentState1 == LOW) {
                        MIDI.sendNoteOff (j+61, 0, 1);
                        mode1[j] = 3;
                        lastDebounceTime = millis();
                    }
                    break;
                case 3:
                    if (currentState1 == LOW)
                        mode1[j] = 0;
                break;
            }
        }
        lastState1 = currentState1;
        if (++j > 3)
            j = 0;
    }
}

Please edit your post and format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.

Usually when something "fluctuates" it means that it had not a fixed state: this is usual when you use a button without a pull-up/pull-down. But if you have a double-throw (xxDT) switch and connected BOTH vcc and ground to its terminals, well, maybe it's just a bad contact...

@frarugi87 I cross checked all that and changed the pcb as well. Do you think its the code??

@NickGammon have made the changes.

Your code is very hard to read. The IDE has an auto-format feature. Please use it and re-submit your code. Also please include (an image of) your wiring. Descriptions of wiring rarely do the actual situation justice.

Posting here since it is quite long, but it's not a complete answer, just a few thoughts and a possible improvement.
Ok, so there are a couple of things in your code I don't understand:
1: in the setup()
{
    int i;
    for (i = 0; i < 4; i++);
}
{
    int j;
    for (j = 0; j < 4; j++);
}

What are these for?
2: debouncing
You are not implementing it correctly, at least not for me. You are reading the button every 50ms, without debouncing. Ok, you won't see "bounces", but there are better solutions (see later).
3: modes 1 and 3
They are quite useless. What are they for?
4: pins 6,7,8,9
What are they for?
5: variable laststate
What is it for? You never use it
6: updating one button per loop
Is it needed? I mean, you are just updating one button per loop instead of all of them for each loop.
In the end
Ok, now my suggestions, apart from learning to indent the code (otherwise it's impossible to read it): I always use the bounce2 class to debounce a button, since it contains everything inside and.. Well, it works well. It can also detect the rising and falling edges of the button, thing that you need if I interpreted correctly your code.
One more thing: debounce delay can be lowered (even to just 5ms):
#include <MIDI.h>
#include <Bounce2.h>

int buttonPin[] = {2, 3, 4, 5};
int buttonPinM[] = {6, 7, 8, 9};

Bounce debouncers[4];
Bounce debouncersM[4];

int debounceDelay = 50; // Usually is lower - even 5ms is fine
uint8_t i = 0;

void setup ()
{
    MIDI.begin(MIDI_CHANNEL_OMNI);

    for (i = 0; i < 4; i++)
    {
        pinMode(buttonPin[i], INPUT);
        debouncers[i].attach(buttonPin[i]);
        debouncers[i].interval(debounceDelay);

        pinMode(buttonPinM[i], INPUT);
        debouncersM[i].attach(buttonPinM[i]);
        debouncersM[i].interval(debounceDelay);
    }
}

void loop ()
{
    for (i = 0; i < 4; i++)
    {
        debouncers[i].update();
        debouncersM[i].update();
    }

    for (i = 0; i < 4; i++)
    {
        if (debouncers[i].rose()) // button i switched from 0 to 1
            MIDI.sendNoteOff(i+55, 0, 1);
        if (debouncers[i].fell()) // button i switched from 1 to 0
            MIDI.sendNoteOn (i+55, 127, 1);
        if (debouncersM[i].rose()) // button i switched from 0 to 1
            MIDI.sendNoteOn (i+61, 127, 1);
        if (debouncersM[i].fell()) // button i switched from 1 to 0
            MIDI.sendNoteOff(i+61, 0, 1);
    }
}

Thanks @frarugi87
1.In the set up mode INT i and j are for 2 groups of switches (4 switches each)  and have different functions in this code One group of switches are sending NoteOn command when the Input is high and other group will send NoteOff command when the Input is High.
2.I might be absolutely wrong with my debounce logic with this code
3. BY mode 1 and 3 you mean Case 1 and 3 right???Since its a 3pdt where the switch physically locks the State of the switch I thought its better to make CASE but I will try your code and update if it works with my switch

@Ashish well, you always have just two states. You can use a switch-case approach, but cases 1 and 3 are useless, since you exit from that mode (I called them modes since the variable mode decides the case) immediately (the condition is the same as the previous one). Anyway I suggest you the bounce approach: easier, faster and less error prone

@fraugi87 I understood what you said and it makes sense. Thank you for your prompt reply. I will do some test and revert back asap!!!

@fraugi87 I tried your code and its working fine. I didnt make any changes just your code and it works. Earlier you mentioned its not a complete solution. Is there more to improvise??

@Ashish I said it was not complete because I did not understand where the problem was, and so mine were just "generic" advices. If it works, this becomes a real solution, but again I do not understand why this works and yours not ;) Maybe just because of the incorrect debouncing, but anyway... The only improvement you can make is to remove the division between the two button sets, but it's not a practical improvement, just a more readable solution..

My code is working as well but only sometimes the digital pins reads another number. Maybe you are right about the Debouncing :-)


text:
Issues on Arduino, LiPO battery and two mottors setup
My main objective with this project was to control these two DC motors with an Arduino Nano (it is not a UNO), powered by a 3-Cell 750mAh LiPO battery (both the motors as the Arduino itself). So, I came up with something like this (it is a simplified version):

If the load on the two mottors rise, could the Arduino be damaged by this current increase? Is the voltage too high for the Arduino handle? Is there any more issues that this setup can have?
When searching, I found that it would be wise to get a fuse between the power supply and the arduino (before reaching Vin). Is that necessary?

You're not controlling anything, they will run as long as the battery is connected.  Yes, you need the fuse - Lithium Polymer batteries do not tolerate shorts.

You mean shorts at the motor part? If it happens, it may damage the arduino? How the current would behave in case of a short before the first motor?

Any short of the battery can cause it to quickly overheat, burst, and even burn.  It has nothing to do with the Arduino being damaged, rather the connection of prototypes modules like this increases the chances of wiring being - even very briefly - wrong either during connection or if something moves later.

But how would a fuse between the first branch and the Vin be of any help?

The fuse should be between the battery and the rest of the circuit, so that in the case of a short it can hopefully disconnect the battery from everything entirely.

If the load on the two motors rise, could the Arduino be damaged by this current increase?

No, the motor current doesn't pass through the Arduino. It is completely separate.

Is the voltage too high for the Arduino handle?

Borderline. The regulator (a lowly 7805) may well get very hot at that voltage (depending on the Arduino's current draw) and go into thermal shutdown.

Is there any more issues that this setup can have?

Maybe add a small buck regulator to the 5V pin instead of using the on-board linear regulator. That will not overheat and will be far more efficient making your batteries last longer. Often marketed as "UBEC" (Universal Battery Elimination Circuit) and used throughout the model vehicle industry these are very easy to get hold of and are ideal for powering things like Arduinos from batteries like this.

So besides the temperature, this setup will work, right? If I can't find these regulators, is there any possible home-made circuit to replace it?

You will be able to find them unless you live in Vanuatu. Even then you can probably get someone to fetch one in a canoe. Building buck regulators is a bit of a black art and not a very easy task - you need to do the PCB layout properly or you end up with a lot of stray EMI being generated. But yes, besides the heat, it should work. I assume the "simplification" has removed the control circuitry?

The arduino itself probably isn't going to draw enough current to justify a switching supply.  Smaller RC BECs are linear anyway, and those large enough to be switchers may waste enough power themselves to negate the advantage for a light load.  An intermediate regulator at 9v can move some of the heat off the board, but will require its own capacitors.

@ChrisStratton It all depends on what the OP has connected to the Arduino. Add a bunch of LEDs and the load will rise.


text:
Water pressure an salinity sensor connected to arduino
I am trying to design a project that Arduino would have connected water and salinity sensor, would be packed in a special box be droped into ocean up to 500 meters. What sensors should I use and how should they be conencted. I assume that I would need professional equipment, not chineese stuff from ebay.
Hardware needs to be able to work under 50*C and up to 50bar
Update:
Budget is about up to 400 pounds for sensors.
Resolution of pressure 0 to 100 bar
Resolution of salinity doesnt matter so much. Few percents of mistake, just to measure it somehow

What sort of resolution and accuracy do you need? How long is the deployment? Any communication?

pessure about 1bsi accuracy and accuracy of salinity doesnt matter. just something that measure quite properly under these conditions.

I'm unfamiliar with bsi, it seems like 500m of saltwater would be a pressure of 5 MPa or 750 psi.    The arduino can interface electrically to most things, but for advice on selection of an uncommon, special sensor, you might do better in an engineering forum.

oh I meant bar, sorry. 50 bar, 5MPa

You may find Robotics Stackexchange useful for questions like this.

On "sea water", each 10m you have 1,007 bar. So at 500m you'll get about 50 x 1.007 = 50,35 bars.

I suggest that you look for a sensor from Honeywell. The problem is that the pressure is very high for a board mounted sensor and the atmospheric pressure is varying. The board mounted sensors measure a maximum of 10 bar.  It is not clear what accuracy you require. Is there a connection to the surface? If so you should measure differential pressure between the seabed and the surface.  Can you be content with a maximum depth of 100 m?
I don't think salinity varies much offshore so it might not be worth measuring.


text:
PC cannot access HC-06 Bluetooth COM port
I have an HC-06 Bluetooth module connected to an Arduino Uno board to allow for the data received by the Ultrasonic sensor to be transferred to my PC via Bluetooth and serial communication.
I am using the PuTTY program to view the data. The thing is, my PC says that it has paired with the Bluetooth and I was able to see the COM number, but when I opened PuTTY and entered the COM number while choosing the option 'serial' an error box appeared saying: "Unable to open serial port."
The way I am currently connecting my b
Bluetooth to the arduino board is:
RX->pin 10
TX->pin 11
GND->GND pin
VCC-> 5V VCC
I am sure that the sketch in the Arduino for serial communication via Bluetooth is right as I have tested the system yesterday and it worked.
Only after a time (say like 5-10 min) the connection breaks and I can't seem to figure out the problem. The Arduino is being powered by USB, if that matters.

If you have powered the BT module from 5v you may have fried it, I recall that the hc-06 module is 3.3v and 3.3v signal too.

The HC-06 vcc needs minimum power 3.6 to 6V, but it's the rx, tx pins that need 3.3 v output from the arduino

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


text:
Arduino and DC Motor control board
I've this PWM Module - 6V-90V 15A Pulse Width PWM DC Motor Speed Controller Switch which I use to control a peristaltic pump (ordinary DC motor), now I want to replace the potentiometer with an Arduino in order to create a soft-start for the pump by pressing a button.
The control is a 0-5V input from the potentiometer, and the description says "you can external drive" and "It could use of PLC controls speed of motor", unfortunately I cannot provide datasheets or schematics.
Is it possible? Or I need a digital pot?
How should I wire it? The 3 cables from the board to the pot are: ground, 0-5V and 5V

Or you may exchange the whole controller with a power mosfet module connected to your arduino. And use pwm directly from your arduino.
http://store.arduino.cc/product/T010020

(Welcome on Arduino.StackExchange) The problem seems to be on the potentiometer. But you're right. (When you can, you should place such an enhancement as a comment, not an answer. But you'll need some more "points".)

Maybe add some more info to make it a non-link only answer, possibly a schematic?

Functionally you can replace the potmeter with a digital potmeter.
If your arduino runs on 5 volt, you can simply connect the grounds and the wire connected to the middle of the pot to a pwm pin.
If the pwm pin does not work smoothly use a RC filter. That is a resis  tor and a capacitor.  As explained here instructables
If your arduino runs on 3.3 you can still use the rc filter but you need to add a bridge.


text:
Compare the new sample in a high sampling rate datalogger
I am using sdFat library the analog bin logger example,
Github: SdFat/SdFat/examples/AnalogBinLogger/

The program is working fine and every thing but the thing is, this high speed datalogger uses interrupts and timers to make the ADC work at a pre-determined sampling frequency and it DOES NOT use the normal analogRead ()
What I want is, when the input of some analog pin is bellow a pre-determined value, I want to write HIGH or LOW to some digital pin,
my question is, how can I compare the new sample in the analog bin logger example as I simply want to compare the new sample as in:
if ( analogRead() < 256 ) {// do something}

knowing that there is no analogRead() in the program because it uses timers and interrupts.

In the function
ISR(ADC_vect) {

the variable d contains the current sample:
  // Read ADC data.
#if RECORD_EIGHT_BITS
  uint8_t d = ADCH;
#else  // RECORD_EIGHT_BITS
  // This will access ADCL first.
  uint16_t d = ADC;
#endif  // RECORD_EIGHT_BITS

So you can just "do something" depending on what is in d.  Of course, since this is a timer interrupt you have limited time to do anything, so you need to make sure that whatever you do is fast and efficient - so really you want to be using direct port access instead of digitalWrite().

this is perfect, thanks
but how to know which analog pin that this d value belongs to, because more than one channel are being used? @majenko

@SabirMoglad Try looking at adcindex.


text:
Why perform bitwise operations here? (SPI FRAM read method)
See: https://github.com/adafruit/Adafruit_FRAM_SPI/blob/master/Adafruit_FRAM_SPI.cpp
The following method reads and converts the input to 8 bit. I have several questions concerning its function.
Using addr = 0xFFFF as an example, the method converts the variable to 0xFF. I understand that bits are removed from the end, but surely 65535 != 255. Perhaps relatively, to their max size, but how is this a useful conversion? I might be missing something about bitwise here..
uint8_t Adafruit_FRAM_SPI::read8 (uint16_t addr)
{
 digitalWrite(_cs, LOW);
 SPItransfer(OPCODE_READ); //read memory from fram array (2-byte)
 SPItransfer((uint8_t)(addr >> 8));
 SPItransfer((uint8_t)(addr & 0xFF));
 uint8_t x = SPItransfer(0);
 digitalWrite(_cs, HIGH);
 return x;
}

Correct me if I'm wrong, the casting is to keep sign extension from occurring.
The masking I understand in theory, but do not at all understand its application here.
Finally, it always returns the same value x = 0, why?
I also see there's a write method but no read method. Only read8. Reasoning?

Think about what happens to the numbers and then plug those into 4 SPI transfers and think about what actually then happens on the SPI bus.

The code above first send the highest 8 bits of the address (addr>>8), and then the lowest 8 bits. Not sure why they do both masking  and casting. After that it sends 8 zero bits. During the sending of those bits the FRAM send the value in the address to the arduinos MISO pin. The 8-bit value is stored in the `x variable. Note that SPI is bi-directional, and you can send and receive data at the same time.

Let's assume addr is 0xbeef. Then, if we break down each operation:
expression             │ value
───────────────────────┼───────
addr                   │ 0xbeef
addr >> 8              │ 0x00be
(uint8_t)(addr >> 8)   │   0xbe
addr & 0xFF            │ 0x00ef
(uint8_t)(addr & 0xFF) │   0xef

So this is essentially breaking down the address into two 8-bit chunks,
and transmitting those chunks individually. It's done like this because
SPI only transmits bytes.

the casting is to keep sign extension from occurring.

Non, sign extension cannot occur, since addr is an unsigned number.
The casting really serves no useful purpose, other than documenting the
code. It would be done implicitly simply because SPItransfer() takes
an uint8_t argument. The casting could be useful if SPItransfer()
was overloaded with a 16-bit version.

Finally, it always returns the same value x = 0, why?

No, it returns whatever the call to SPItransfer(0); returns, i.e. the
data sent by the FRAM module.


text:
Controlling HDMI Switch via RS232/UART
Problem:
I have an HDMI switch that is controllable via RS232

Scenario 1:

Setup: PC connected to HDMI switch using USB -> serial adapter
Test: Opening PuTTY on COM port and sending command "sw i01" from my PC
Results: HDMI switch input changes to port 1 [Good]

Scenario 2:

Setup: Arduino UART port connected to TTL->RS232 adapter connected to serial->USB adapter connected to PC with PuTTY program open on COM port
Test: Sending command "sw i01" from Arduino to PC using code below
Results: "sw i01" prints repeatedly on the Putty terminal [Good]

Scenario 3:

Setup: Arduino UART port connected to TTL->RS232 adapter connected to HDMI switch serial port
Test: Sending "sw i01" from Arduino repeatedly to HDMI switch using code below
Results: HDMI port does not switch from port2 to port1 [Bad]

Hardware:

Intel Galileo Gen 2
SparkFunRS232/TTL Shifter connected to Galileo UART
HDMI switch is IOGear GHSW8141

Code:
[Note: Galileo Gen 2 requires Serial1 for UART communication]
void setup() {
    Serial1.begin(19200);
}

void loop() {
    Serial1.print("sw i01");
    Serial1.write(13);    // CR
    Serial1.write(10);    // LF
    delay(1000);
}

Question:
It seems like Scenario 1 and 2 confirm that the Arduino->HDMI switch communication should work, but it doesn't. Am I missing something regarding physical connectivity? Does manually typing "sw i01" in PuTTY send different commands than I have in the Arduino code?

How have you connected this?

I can't tell how you have it physically connected. So I can't tell if it's wrong.
It should work indeed. But you'll need the exact right settings and probably an (correct me if I'm wrong) uart<->RS232 converter.

@MikaelPatel I edited the description above to include how I connected everything for each scenario. Let me know if I need to be more clear on anything. Thanks!

@Paul I edited the description above to include how I connected everything for each scenario. Let me know if I need to be more clear on anything. Thanks!

You might want to check if inverting the Rx and Tx lines does something. But judging from the tests you've done, it shouldn't make a difference. Worst case, you could try an ossiloscope and compare the actual raw electrical output of the working and non-working examples. Are you sure you need an CR + LF? Maybe your putty settings only send an LF (and does work for that reason)

I found it is was related to the physical connection!
In Scenario 3, I originally had the Sparkfun TTL/RS232 adapter that had a female DB9 connector wired to the HDMI switch female DB9 connector using a male/male serial cable. The serial cable I bought was a straight through cable.
I swapped it out with a null modem cable and it worked right away.
Looking at the wiring diagram, I thought swapping the Tx/Rx pins on the Sparkfun adapter would have achieved the same result as the null modem cable, but apparently not.
If anybody can point out why the null modem cable made the difference, that would be something good to know for the future.

Your HDMI switcher, and your USB to RS-232 converter speak RS-232.  The Arduino speaks TTL UART.
While the concept behind them, and the overall format of the data, is the same there are major differences:

RS-232 uses a ±10V NRZ signalling method, TTL UART uses a 0-5V signalling method
RS-232 uses inverse logic compared to TTL UART

That means that you need to convert the Arduino's TTL UART to ±10V NRZ with inverse logic in order to communicate with the IOGear.
Fortunately that's a simple enough task using a special interface chip. These are readily available and can be bought for tiny amounts as a breakout board or even a full shield if you like (such as this one from Sparkfun).  The chip is known as a MAX232 in its most common form, though other manufacturers may use different letters.
If you pop on eBay (or your favourite budget seller site) and search for "Arduino MAX232 DB9" (the DB9 is the type of plug on the board - the 9-pin D connector) you will get lots of hits to choose from.

Majenko, did you read the “SparkFun RS232/TTL Shifter connected to Galileo UART” part of the question?

Nope. Missed that.

@jwpat7 and Majenko, I edited the description above to include how I connected everything for each scenario. Let me know if I need to be more clear on anything. Thanks!


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

void loop() {

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

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

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

    break;

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

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

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

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

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

  }
  currpos=degree;

*/

}

Thanks.

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

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

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


text:
Uploading code to Arduino wirelessly
I have been working on a project watch which would work best if it is entirely sealed (to waterproof it). The watch may need future updates, but I will be unable to send code to it using a usb connector or isp programmer without opening the case. What is the best way to connect my PC with this watch wirelessly?
I gather that the serial ports are usually used to send code via the usb, and that most Bluetooth modules use serial coms to communicate with the Arduino.
The Arduino that I am using is an Arduino Pro Mini clone.
Any help will be greatly appreciated.

Go simple, and use light. IR-receiver or photo-transistor.

There actually exists an Arduino BT board. (https://www.arduino.cc/en/Main/ArduinoBoardBT) which should be extremely easy (virtual bt COM-port as if it was connected to a cable). I'm not sure how up to date or available the board is though.

Alternatively, you could push a pin header through the box/casing, connect it, and cover it in hot glue. Which may be waterproof to some point.

You could use ESP8266 and ESP-LINK firmware to update the arduino firmware over the wire. Its also enables you to debug it wirelessly. What it does is provide a serial link but over wifi. Just like connecting it via cable.


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

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

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

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

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

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

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

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

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

}

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

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

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

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

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

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

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

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

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

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

The problem I'm having is that

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

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

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

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

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


text:
Instantiating bounce library inside a class
I am trying to get my head around how to instantiate objects from existing libaries inside a class object. Specifically I am trying to get the bounce2.h debouncer working.
At the moment my code compiles but i think the debounce function is not working as the button is filling my array with lots of random numbers (even from setup) whereas it works fine on a non-class based sketch, so I think that I am probably not instantiating the bounce object correctly. If anyone can help I would be very grateful!
My header:
#ifndef CandleRack_h
#define CandleRack_h

class CandleRack
{
  public:

    CandleRack(byte candleRackStatus);
    void begin();
    void pushButton();
    void selectRandomCandle();
    void turnOnCandle(byte candlePosition);
    void burnCandlesForMs();
    void fadeOutCandle(byte candlePosition);

  private:
    Bounce _debouncePushButton;
    byte _pushButtonPin;
    byte _candleRackStatus;
    byte _candlePosition;
    byte _candleStatus[];
    elapsedMillis _candleTimeElapsed;
    unsigned int _candleOnForMs;
};
#endif

My cpp
#include "Arduino.h"
#include <FastLED.h>
#include <elapsedMillis.h>
#include <Bounce2.h>
#include "CandleRack.h"

#define NUM_LEDS 50

CandleRack::CandleRack(byte candleRackStatus)
{
  _candleRackStatus = candleRackStatus;
}

void CandleRack::begin()
{
  randomSeed(analogRead(0));

  _debouncePushButton = Bounce();
  _pushButtonPin = 3;
  _candleOnForMs = 20000;
  pinMode(_pushButtonPin, INPUT_PULLUP);
  _debouncePushButton.attach(_pushButtonPin);
  _debouncePushButton.interval(10);

  for (byte b = 0; b < NUM_LEDS; b++)
  {
    _candleStatus[_candlePosition] = 0;
  }

  Serial.println("Candle Array: ");       // Debug ************************
  for (byte b = 0; b < NUM_LEDS; b++)     // Debug ************************
  {                                       // Debug ************************
    Serial.print(_candleStatus[b]);       // Debug ************************
    Serial.print(", ");                   // Debug ************************
  }                                       // Debug ************************
  Serial.println("");                     // Debug ************************
  Serial.println("Begin Complete");       // Debug ************************
}

void CandleRack::pushButton()
{
  // Look for a button push
  if (_debouncePushButton.update())
  {
    if (_debouncePushButton.fell())
    {
      selectRandomCandle();
    }
  }
}

void CandleRack::selectRandomCandle()
{
  byte randomCandlePosition;
  do
  {
    randomCandlePosition = random(0, NUM_LEDS);
  }
  while (_candleStatus[randomCandlePosition] != 0);

  turnOnCandle(randomCandlePosition);
}

void CandleRack::turnOnCandle(byte _candlePosition)
{
  // leds[_candlePosition] = CRGB::Red;
  _candleStatus[_candlePosition] = 1;

  Serial.println("Button Pushed: ");      // Debug ************************
  Serial.println(_candlePosition);        // Debug ************************
  Serial.println("Candle Array: ");       // Debug ************************
  for (byte b = 0; b < NUM_LEDS; b++)     // Debug ************************
  {                                       // Debug ************************
    Serial.print(_candleStatus[b]);       // Debug ************************
    Serial.print(", ");                   // Debug ************************
  }                                       // Debug ************************
  Serial.println("");                     // Debug ************************
}

void CandleRack::burnCandlesForMs()
{
  // See if it is time to turn the candle off
  for (byte b = 0; b < NUM_LEDS; b++)
  {
    if (_candleTimeElapsed > _candleOnForMs && _candleStatus[b] == 1)
    {
      CandleRack::fadeOutCandle(b);
      _candleTimeElapsed = 0;
    }
  }
}

void CandleRack::fadeOutCandle(byte _candlePosition)
{
  _candleStatus[_candlePosition] = 0;
}

My sketch:
#include "Arduino.h"
#include <FastLED.h>
#include <elapsedMillis.h>
#include <Bounce2.h>
#include "CandleRack.h"

CandleRack MyCandleRack(0);

void setup() {
  delay(3000); // sanity delay

  Serial.begin(9600);
  while (!Serial);

  Serial.println("Setup Starts");  // Debug ************************

  MyCandleRack.begin();

  Serial.println("Setup Complate");  // Debug ************************
}

void loop() {

  MyCandleRack.pushButton();
 // MyCandleRack.burnCandlesForMs();

  FastLED.show();
}

edit - added the code from the original debounce example for a single sketch
// Detect the falling edge

// Include the Bounce2 library found here :
// https://github.com/thomasfredericks/Bounce-Arduino-Wiring
#include <Bounce2.h>

#define BUTTON_PIN 2
#define LED_PIN 13

int ledState = LOW;

// Instantiate a Bounce object :
Bounce debouncer = Bounce();

void setup() {

  // Setup the button with an internal pull-up :
  pinMode(BUTTON_PIN,INPUT_PULLUP);

  // After setting up the button, setup the Bounce instance :
  debouncer.attach(BUTTON_PIN);
  debouncer.interval(500);

  // Setup the LED :
  pinMode(LED_PIN,OUTPUT);
  digitalWrite(LED_PIN,ledState);

}

void loop() {

  // Update the Bounce instance :
   debouncer.update();

   // Call code if Bounce fell (transition from HIGH to LOW) :
   if ( debouncer.fell() ) {

     // Toggle LED state :
     ledState = !ledState;
     digitalWrite(LED_PIN,ledState);

   }
}

Your main issue (the cause of your symptoms) is the fact that you have no size for your _candleStatus array.  Without specifying a size you end up with no memory allocated to the array, and hence no valid content.
In your class definition the line:
byte _candleStatus[];

should be modified to:
byte _candleStatus[NUM_LEDS];

and NUM_LEDS should be defined in the header, not in the CPP file. (By specifying it in the header file, since the header file is included in the CPP file, the definition ends up in both files).
Aside from that this line doesn't do what you think it does:
_debouncePushButton = Bounce();

You are copying the content of an anonymous bounce object created just for the occasion into a pre-existing Bounce object.  You don't want that line to exist since the Bounce object has already been instantiated by the construction of your CandleRack object.
However there is something you need to be aware of known as the Static Initialization Order Fiasco which can bite you on the rear end if you are not aware of it.  This is basically when you use objects in other objects and those objects haven't yet been properly created since you cannot predict the order in which objects are initialized. This may or may not be an issue in your system - it all depends on how the other classes you use behave.
One way around the issue, if you find it does become a problem (or if you just want to avoid the problem altogether) is to use pointers and what is known as Construct On First Use.  This is where you don't instantiate any objects in your constructor or the class definition - instead you just have pointers to them and use the new keyword to construct the object from within a member function (such as begin()).
For this you change your class definition object entries to be pointers, such as:
Bounce *_debouncePushButton = NULL;

(Note that not all versions of the compiler will support that assignment in the class definition. It's a modern addition to C++ and depending on your version of the Arduino software may or may not work. If it doesn't you can move the assignment into the constructor by removing the = NULL from the definition and adding _debouncePushButton = NULL; into the constructor.)
Then construct a new object in the begin() function (if it hasn't already been created):
if (_debouncePushButton == NULL) {
    _debouncePushButton = new Bounce();
}

Now you have to access the _debouncePushButton as a pointer to an object not an object, so change all your accesses to use the pointer dereference operator ->:
_debouncePushButton->attach(_pushButtonPin);
... etc ...

In case the class should ever go out of scope or be used in a dynamic way you really should create a destructor to delete any objects that have been created:
CandleRack::~CandleRack() {
    if (_debouncePushButton != NULL) {
        delete _debouncePushButton;
    }
}

Note that you should only ever try and delete objects that have actually been created - hence the test to see if it's not null.
Excessive use of new and delete though is discouraged, so it is best to use objects in a static context if possible. Too much new and delete or malloc and free can cause heap fragmentation which can lead to you running out of memory and all the associated stability problems that come with it.
Of course, all this is optional and chances are it won't be needed if the other classes behave well.

Thanks. It is still giving me the same issue though, it is adding lots of random numbers to the array. I can post the code for using the debounce object in a single sketch if it helps?

See my edit. You have a second completely unrelated problem with your code.

Agh, OK. one issue is that #define NUM_LEDS comes from my FastLED array and I need that in the main sketch I think. I'm not sure how to reference/point to a #define though (which it needs to be).

If it is in CandleRack.h then it is also in CandleRack.cpp since CandleRack.h is included in CandleRack.cpp.

Great. Just tried it and it's sorted the problem! Huge thanks :) Now for the tricky bit which is using FastLED in the object :)

one question... I had read that it wasn't good to use new in arduino sketches. Is this old adivce?

I've been reading up on new and should i be using delete somewhere as well as per http://arduino.land/FAQ/content/4/24/en/mixing-malloc-and-new.html ?

Only if you ever delete the CandleRack object, and since you statically create that it never gets deleted.  You can make a destructor for CandleRack if you really want and delete the Bounce object (if it has been created) but if you are always going to statically create it there's not really any need.

And it's not the use of new that is bad - it's the repeated new and delete that causes heap fragmentation - and when you only have a tiny heap fragmentation is very very bad. Using new in a static way (never using delete and never wanting to use delete) never causes heap fragmentation.

Should I also be using pointers for my other library object - elapsedMillis? it works fine at the moment but thinking about your last advice, there might be an advantage in using a pointer there as well?

You can do, yes. It is possible to do the whole thing statically and not use new at all - just revert back to how it was and remove the line that assigns a Bounce object in the begin function - however there is risk of static initialization order problems then if you don't know what the constructors of the other objects are doing. By using pointers for your objects you are getting what is called "construct on first use" from them which means that they will always be constructed after the system has completely initialized.

Makes sense - I understand now that error I was having from the beginning of the thread was with the randomNumber array issue - the rest is more 'best practice'. So all I need to do is change (in the header) elapsedMillis _candleTimeElapsed[NUM_LEDS]; to elapsedMillis *_candleTimeElapsed[NUM_LEDS];? as I can't use the -> notation in this case as now I look more closely it doesn't actually instantiate an elapsedMillis object to reference in this case. Is that right?

Personally I'd fix this answer, since it is misleading. You should definitely remove the pointer (and new) part, since it is not related to the actual problem. If, on the other way, you want to keep it, change the words around (it is not a mandatory thing to do, it's just something you suggest) but, then, you will need to 1) initialize the pointer to NULL 2) check if the pointer is null (protect against multiple begin calls, or there will be memory leaks) before making a new 3) explicitely delete it (otherwise there are memory leaks if the object is used in a reduced scope)

@frarugi87 yes, I wrote it just before bed. It's not a wonderful answer.

Thanks for the updated answer, it makes a huge difference to my understanding. Especially as I assumed before that using new would be the preferred way to instantiate an object.

@Majenko now THIS is a good answer.. +1


text:
Options for communicating between Arduinos
I'm looking to communicate between ~5-10 Arduinos to send commands and data between them. By "Arduino" I mean the ATmega328 programmed using the Arduino programming framework.
Each of the devices would be on the same PCB.
I know I2C and SPI can communicate to some degree, but that they're really meant for peripherals devices connected to a micro controller rather than connecting multiple micro controllers to each other, and that they usually only send a few bytes of data at a time. On the other hand I know LCD displays can be driven using them, and I'd imagine there's a lot of data being transferred in those cases.
Is there a something like I2C (multi-master, multi-slave, single-ended, serial computer bus) for communicating between micro controllers? Allowing each device to send data to each other device unsolicited. For example, if a switch was pressed on device A, it would tell device B, without having device B ask A all the time if a switch was pressed. and vice versa.
Edit: I found some libraries that may do what I want with RS-485. Is this the only viable option for ~1k bps transmission between 5-10 devices? I would imagine TCP/IP over Ethernet would work as well, but that seems like too much. Are there any I2C libraries that allow sending that amount of data between only master devices?

https://github.com/MichaelJonker/HardwareSerialRS485
https://github.com/MajenkoLibraries/ICSC

Have you looked at serial connection?

do you mean RS-485?

There is a very similar question here: How to interconnect multiple Arduinos with a Rpi to control home-lights/switches - ignoring the Rpi part (it wasn't really relevant to the question) I count that as virtually identical to what you want to do. I made a lengthy response there about doing a "rolling master" system. Please read the other question/answer and see what you think.

You need a physical layer (cabling or board), electronical "standard" like RS-485 but 5V TTL is also good. Then you'll have to choose what type of bus arbitration (round-robin, master-slave or broadcast messages) and probably implement some addressing or error checking.

On a breadboard, I wouldn't use RS485, since it needs transceivers. Just 5v for a logic 1 and 0v for a logic 0. But from that point, possibilities are endless. It will also depend on speed requirements etc.

You haven't stated why you want to create such a thing. If you're short on IO pins, you might use IO-expanders. There might be better solutions. If it's a hobby/proof of concept, you might check out other projects like it and try to "enhance/adjust it".

@Paul I want to have a separation of concerns. I know I could just get a bigger controller with more interrupts and I/O, but I'd rather keep things simple at the device level. It also helps when collaborating with others, as each subsystem can be designed and even constructed independently and connected together later. Also can be easier to unit test and replace/upgrade.

Maybe I did not just find it, but I did not read the fundamental question, which is "what is the topology you need"? Do you need everybody talking to everybody? Centralized access (i.e. everybody speaking to one)? A mixed solution?

@frarugi87 I think a bus topology would work best, with any device communicating with any other device and initiating the connection. So no slaves.

Well, ok for bus topology, but I highly suggest you to make one bus master and all the other slaves. Otherwise you will have collisions, and detecting/preventing collisions is a "difficult" task. If you just have one master you can avoid this, since just him can give permission to talk. You can make a serial (UART) bus, with one wire connecting master's TX to each slave RX, and one wire connecting slaves TX (maybe with a 3-state buffer) to the masters RX. Otherwise you can make a daisy-chain: TX1 connected to RX2, TX2 to RX3... TXn to RX1. This is a bit less efficient, since to talk to

another micro you have to make n hops, but it works. The last solution is what you said, so everybody speaking on the same bus, but you will need collision detection. In this case I suggest you the CAN bus, since it already handles the collisions (but you will have to implement it in your code).

There are a number of concepts that can help you realize your dream. I can't, in the space of this answer, tell you exactly how to implement what you want, but I can show you the concepts that will help you to implement it.
First off there's the concept of the bus master.  This isn't necessarily the device that instantiates communication - instead this is the device that owns and controls the bus.
When a device that isn't the bus master wants to communicate on the bus it first asks permission from the bus master.  The old Z80 (well, I say "old", but they are still in use in many forms today) used this concept to allow other chips to use the data and address buses. It consists of two signals - BUSRQ and BUSACK.  A device first looks to see if either of BUSRQ or BUSACK are active, and if neither are it then activates BUSRQ. If the bus master is willing to give up the bus to the other device (it's not using it at that moment) it activates BUSACK and the other device then knows that it can use the bus.  Nothing else can use it until BUSRQ and BUSACK have both been released.  Nice and simple and elegant.
But not perfect. If two devices both decide to ask for the bus at the very same instant you get a collision.  This is a common problem amongst shared bus systems like this, and causes untold problems unless you know how to handle it properly.
Enter the concept of listen-while-you-talk.  This involves the device that is sending on the bus also listening to what is being sent on the bus through a separate receiver.  It then can know if what it sent on the bus is what actually ended up on the bus.  For instance if two devices talk at the same time and one sends 10011001 and the other sends 11001100 the result that appears on the bus might actually end up as something else, such as 11011101 or maybe 10001000 depending on how the bus signals are created.  So if you know what you sent got corrupted you can now do something about it.
Next concept: backing off.  This is where both the senders wait for a short period and try and send again. As long as they both delay for a different amount of time the first one to try will get the bus and be able to communicate. But how do you guarantee that they will both delay for different times?  You may think the answer is simple: use a random number, like rand() or random().  But that is also problematic:
Another concept: The pseudo random number generator
The Arduino doesn't generate random numbers.  It just uses a complex mathematical formula to create a sequence of numbers that, to us, look random.  They aren't though.  Write a small program to print 10 random numbers through serial and run it multiple times (press the reset button).  You will find the same "random" numbers in the same order every time.  Try it on another Arduino and you get the same numbers again. Always the same.
So what to do?  The answer is called seeding the random number generator.  The next number generated by rand() et al depend on the number that had been generated last.  So change the first number and all the rest of the numbers will change.  However, you have a catch-22 situation. You need a random number to seed the random number generator to make it random to be able to generate a random number to seed the random number generator... ad infinitum.  You see where that's going? You can't seed from rand() since rand() isn't random until you have seeded from a random source. So you need to find a random source.
And that's not an easy task.  The best source of entropy as it's known is white noise. This can be generated in a number of ways with a number of different circuits - from the breakdown of a diode junction to very high gain amplification of the thermal fluctuations in a resistor.
All are quite complex for what you want really, but there is a simpler, if slightly less random, method - read an analog input that isn't connected to anything.  It won't have as much of a range as a proper entropy generator, but it should provide enough randomness to give a reasonable chance of each device getting a different seed.
Another useful concept is the interrupt.
This is good in a situation where you don't want the complexity of a multi-master bus with all the collisions etc. You have a single master that does all the work on the bus, and when a slave device has something important to say it nudges the master with an interrupt. The master then goes "Yes? What do you want?" to which the slave replies "Someone pressed my button".
That way the master isn't constantly polling the slave to see if the button has been pressed.  It is often used in bus arrangements like SPI and there are many chips, such as IO expander chips, that can assert an interrupt when one of their input pins changes state.
But if you have 20 devices does that mean you have 20 interrupt pins?  Not necessarily. New concept: wired OR.
It's perfectly possible to have multiple different slaves all using the same interrupt pin.  The pin is normally held HIGH with a resistor (it could be an internal pullup resistor) and each slave has an open drain output connected to that pin.  An open drain output, when "off", is not connected to anything - it's like the pin is in input mode (in fact it can be emulated on chips that don't have open drain by switching between input and output mode).  When the output is "on" it connects the pin to ground, pulling down the IO pin, just like a button would.
It's then up to the master to make its way round the slaves that it knows are attached to that interrupt to see who needs attention.  You can of course implement a number of different interrupt pins with different groups of slaves on each one - maybe a high priority one with just one device, and lower priority ones with multiple devices on each, for example.
The same concept of wired OR and open drain can be used for allowing multiple devices to all share the same physical wires.  That is exactly how I2C works - the two bus lines are pulled up by resistors and the devices on it use open drain outputs to pull the line low to release it back to high to create the different logic levels. If two devices both pull it low together it will just be low.  Without the open drain method if you had one device outputting a 1 and another outputting a 0 you would basically get a short circuit between the two and you would end up damaging chips.
And then of course you have the concept of synchronous versus asynchronous communication, but that is an entirely different kettle of fish. Simply said though, protocols with a clock, like SPI and I2C, which have a master generating that clock, are synchronous. Protocols like the UART and RS-232, RS-485, etc are asynchronous - they rely on both ends agreeing on how fast data is being sent (baud rate) so they know how to interpret the signals as they arrive.

I would just want to add that I2C is theoretically multi-master capable, and has an arbitration scheme that does not need random numbers. However, there seems to be an issue with Atmel's implementation. C.f. for example TWI module seems buggy in multi-master communications and Multiple Master Problem with Atmel AVR Microcontrollers. Single master + interrupts seems to me like the easiest solution.

@EdgarBonet Pretty much all protocols can be made multi-master if some form of bus arbitration system is implemented. Some are more suited to this than others, and some, such as I2C, have "official" ways of doing it, some of which work better than others. The most reliable way, of course, is to not need a multi-master system at all :)

@EdgarBonet do you know if the wire library supports multi-master? Is it as easy as this https://michael.bouvy.net/blog/en/2013/05/25/arduino-multi-master-to-master-i2c/

@waspinator: I cannot tell, as I have never tried. It would seem the Wire library handles bus arbitration, but I don't know whether it can cope with the issues I pointed to before.

Check out PJON - https://github.com/gioblu/PJON. It's a one-wire alternative.

Please can you elaborate on your answer possibly an example of usage or pros and cons,, as this is really a link only answer at the moment.

Please add some information on why it's better than the alternatives/what makes it stand out. Thanks!

PJON has been made available for multiple platforms, not just Arduino. It's   simpler than I2C/one-wire. It handles noise better. It has multi-master support. Read the wiki from the link.

In addition to @Majenko's excellent answer, you need to have a think about what you are communicating.
It sounds like you want to communicate a single bit - perhaps you can get away with individual pins? If you have a master, and up to 13 slaves, you could have one pin on the master connected to one pin on each of the slaves (via a resistor). If slave A wanted to signal it's signal, it would raise the pin; the master would then be able to poll each pin in turn, to work out who said what.

sorry, that last bit was just an example of how I'd like devices to be able to "push" data to each other instead of polling for it. I, in fact, do want to send more data. ~100 bytes 10 times a second.

Another option is SPI.
SPI can be used with any number of devices, in a ring. It was explained to me as follows: any participant can toggle the clock line 8 times, to move the byte in it's own buffer, into the next device's buffer, in a ring; the device gets a byte from the previous device. If someone else toggles the clock 8 times, you get notified that the new byte is ready (this is done in hardware).
You need to think carefully about a protocol for this - an "address", "length", "command", and then any number of parameters. The sender sends the "address" byte, sets the "length" byte in the buffer, and holds the rest ready. The next device has received the "address" byte, and sees if it is the intended recipient. If it is not, it notes this down, and pushes the chain round, notes the length, and waits until someone ELSE has pushed that many bytes around. If it IS yours, read the rest of the data, pushing the data around, and blanking it as you go (to stop it coming back). A blank address (e.g. 0) would be reserved, meaning "don't do anything with this, wait for someone else to push it around, and read the next byte as the next address". All devices would need to initialize to 0 on startup.
If you need to set addresses dynamically, set a special byte "all stations", with a command which means "your device number is X, and tell the next device it's device number is X+1". Someone would need to initiate this, of course.
You also run the risk of collisions, if two devices start sending at the same time, or if something doesn't relay what it's supposed to (e.g. a chip is powered down). You need to think about how you're going to detect/recover from this.