text:
Relay switching problem with ATmega328P + 10 relays
I am trying to switch ON/OFF 10 relays connected to ATmega328P via Bluetooth HC-06 module. The problem I am facing is that when I try to Switch ON more than 3-4 relays, some of the previously ON relays switch OFF and the ATmega328 restarts.
I am using a 12V 2A power supply.
I have set up my circuit as shown below

My code
int r1 = 4, r2 = 5, r3 = 6, r4 = 7, r5 = 8, r6 = 9, r7 = 10, r8 = 11, r9 = 12, r10 = 13;
char state;
String msg;
int r = 0;

void setup()
{

    pinMode(r1, OUTPUT);
    pinMode(r2, OUTPUT);
    pinMode(r3, OUTPUT);
    pinMode(r4, OUTPUT);
    pinMode(r5, OUTPUT);

    pinMode(r6, OUTPUT);
    pinMode(r7, OUTPUT);
    pinMode(r8, OUTPUT);
    pinMode(r9, OUTPUT);
    pinMode(r10, OUTPUT);

    Serial.begin(9600);
}

void loop()
{

    while (Serial.available())
    {
      state = Serial.read();

      if (state == '\n')
        break;

      msg += state;

    }

    if (msg.length() > 0)
    {
      /*Serial.print("Data: ");
      Serial.println(msg);*/

      if (msg == "on1")
      {
          digitalWrite(r1, HIGH);
          Serial.print("O1");
      }
      else if (msg == "on2")
      {
          digitalWrite(r2, HIGH);
          Serial.print("O2");
      }
      else if (msg == "on3")
      {
          digitalWrite(r3, HIGH);
          Serial.print("O3");
      }
      else if (msg == "on4")
      {
          digitalWrite(r4, HIGH);
          Serial.print("O4");
      }
      else if (msg == "on5")
      {
          digitalWrite(r5, HIGH);
          Serial.print("O5");
      }
      else if (msg == "on6")
      {
          digitalWrite(r6, HIGH);
          Serial.print("O6");
      }
      else if (msg == "on7")
      {
          digitalWrite(r7, HIGH);
          Serial.print("O7");
      }
      else if (msg == "on8")
      {
          digitalWrite(r8, HIGH);
          Serial.print("O8");
      }
      else if (msg == "on9")
      {
          digitalWrite(r9, HIGH);
          Serial.print("O9");
      }
      else if (msg == "on10")
      {
          digitalWrite(r10, HIGH);
          Serial.print("O10");
      }

      //off---------------------------------------------------------

      else if (msg == "off1")
      {
          digitalWrite(r1, LOW);
          Serial.print("F1");
      }
      else if (msg == "off2")
      {
          digitalWrite(r2, LOW);
          Serial.print("F2");
      }
      else if (msg == "off3")
      {
          digitalWrite(r3, LOW);
          Serial.print("F3");
      }
      else if (msg == "off4")
      {
          digitalWrite(r4, LOW);
          Serial.print("F4");
      }
      else if (msg == "off")
      {
          digitalWrite(r5, LOW);
          Serial.print("F5");
      }
      else if (msg == "off6")
      {
          digitalWrite(r6, LOW);
          Serial.print("F6");
      }
      else if (msg == "off7")
      {
          digitalWrite(r7, LOW);
          Serial.print("F7");
      }
      else if (msg == "off8")
      {
          digitalWrite(r8, LOW);
          Serial.print("F8");
      }
      else if (msg == "off9")
      {
          digitalWrite(r9, LOW);
          Serial.print("F9");
      }
      else if (msg == "off10")
      {
          digitalWrite(r10, LOW);
          Serial.print("F10");
      }
      else if (msg == "offall")
      {
          digitalWrite(r1, LOW);
          digitalWrite(r2, LOW);
          digitalWrite(r3, LOW);
          digitalWrite(r4, LOW);
          digitalWrite(r5, LOW);
          digitalWrite(r6, LOW);
          digitalWrite(r7, LOW);
          digitalWrite(r8, LOW);
          digitalWrite(r9, LOW);
          digitalWrite(r10, LOW);
      }

    }

    msg = "";

    delay(1000);
}

else if (msg == "off")        {           digitalWrite(r5, LOW); perhaps missing a 5 in text?

I can see lot of problems.

No decoupling capacitors on ATMega.
Capacitors on both sides voltage regulators are usualy essential for regulator stability.
Big voltage drop on regulator - if it's overheating, thermal shutdown might happen. For example 7V drop @ 350mA (about four relays) results into 2.45 Watts turned into heat.
Bare HC06 doesn't like 5 Volts on its 3.3V logic level input
Xtal oscilator usualy requies two capacitors (22pF) for better stability.

Where do the switching transistors get their +5v? The dropouts and shutdown suggest that the "+5v" is sagging as more relays try to draw off of it. Try supplying the relay current from a more capable supply, possibly a voltage regulator off the +12v supply - it will be wasteful but if it works, you'll know that was the problem.

The asker has never stated that they are using an Arduino board.

True - fixed it.


text:
Multiway Relay Dimmer
I am looking for something like a multiway "relay dimmer".
Which lets me dim a light using an Arduino and a manual dimmer.

(The manual dimmer should work without any computer!)

The big black 'dimmer' symbol - are you intending to build this too? If so, what load is it driving - AC? DC? Mains (230V/110V)?

@CharlieHanson yes. It's a 230V

Then first look at how AC dimmers work. Using a triac as the dimming device (the simplest form) requires the controller (Arduino, rotary potentiometer, cycle-of-the-moon detector, etc.) to send a pulse at a specific time to the triac to make it conduct. Typically the power for each controller is drawn from the AC itself, so you'll have to consider this for your 'manual' controller, assuming the Arduino is powered via USB.

You could use a rotary encoder for that purpose!
Basically the rotary encoder is a knob that, for every "tick" you give it, it returns a different value to your Arduino. With a bit of programming you can sense the direction of the turn, if it is positive then you lighten up the LED, and vice versa.
I used that to control a RGB led, it works very well! here some more information on the rotary encoder and the code needed to use it.

But then the manual device would have to be connected to the Arduino and wouldn't work without it.. Right?

Yes, I was thinking that Arduino itself can act as your dimmer. Maybe I got your question wrong though, so you need the whole system to be able to work without an Arduino?

Correct - the Arduino is just a needed feature.. That's why I called it "multiway"

I don't quite understand this. You may or may not have the Arduino there? Why not? Will someone open up the wall plate and remove it? Is the general idea that you turn a knob if you want to manually change the lighting, but under Arduino control (eg. at night) the Arduino will dim the lights on its own?

I know this is somewhat redundant, but maybe you could create the dimmer with a smaller version of arduino (like a mini or so), that would be the "dimmer" of your block diagram. This would work on its own or connected to another Arduino using I2C or maybe something easier like TX/RX ports.

@NickGammon : correct. I chose this way in order to be save in case of an Arduino failure.

Yes ... but it shouldn't fail. I mean it might, but I've had light dimmers fail before, and they didn't have Arduinos in them.

I add another answer because I think I found something. After a few days searching on various sites that sell arduino stuff I found this http://www.dx.com/p/8-channel-5v-relay-module-extension-board-for-arduino-avr-arm-51-140703 that might be what you're looking for. One of the customers in the review states it can be used even without Arduino.
I know it's a relay, not a dimmer, but maybe you could add something to your circuit...

source: Stack Exchange

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

sort: votes


text:
Best way to implement score board logic using Arduino and Shift Registers?
I am from a mobile development background and very new to Arduino. I am trying to make an electronic cricket score board. The logic is simple.
Score - 888 (3 Digits) - I have implemented this logic using shift registers.  Three pin used from Arduino Uno and this is working fine.
Overs - 88 (2 Digits) - Need to find a best way to implement it
Wickets - 8 (1 Digit) - Need to find a best way to implement it
Now I need to add Wickets and Overs to the logic. I think there are two ways to do it.

One is passing data from Score shift registers. I think this way is a bit complicated in logic level. But if this is a good way, then great.
The other is, connect to Arduino Uno pins directly rather than getting information from score shift registers.  There are only few pins.

Please Note: I need to print this design in PCB
This might be a basic question. But I would like to the know which way is efficient, and its advantages. If both are not, I would like to the know the best one.

Are you saving pins on the Uno for something else?

I'd just daisy chain them all together. I code, you can have 3 variables (score,overs,wickets), and something like an update function that converts the values in the 3 variables, into bytes to send to the shift registers. I don't see any real advantage to using separate pins for the three different chains of shift registers. I'd suggest using the SPI pins to connect to the shift register, in case you ever need super fast update rates (e.g. for smoothly fading digits on/off).

@Gerben Thanks for your suggestion. It makes sense. I thought passing information via all serial registers may cause delay. Now i am clear with it.

There isn't really a best way (and such questions are usually discouraged as they can easily descend into argument).
Personally I would go for chaining all of the '595s together so you only ever use the 3 pins; it gives you the opportunity to use a smaller MCU like the ATtiny when you put it all on a board later which makes it (slightly) cheaper and (potentially) smaller.
From a software point of view, it doesn't make a huge amount of difference - doing it the way I have suggested means you send the 3 values out in the correct order every time one of them updates. Separating the 3 scores with their own dedicated pins means juggling which one needs to be updated each time. Neither option is particularly complicated and with this sort of application efficiency of code is mostly redundant because the entire MCU is dedicated to the (simple) task.

Thanks for your suggestion and your answer. It helps me to decide which way to go.

You could use a 16x2 LCD to display the information; then you wouldn't need so many separate lines from the Arduino, the PCB would be simple and compact, etc.
However, if you need a big high-power display that is not multiplexed, you could use one 74HC595 per digit, assigning one bit per segment with 7-segment LED displays, with a driver transistor on each output.
The six '595s would be in series, which would use only two output lines from the Arduino: clock and data.
Another approach is to build your display from 84 or 126 WS2811 or WS2812B LEDs (2 or 3 per segment, and 7 segments times 6 digits).  About $10 to $15 on Ebay.  This would use one data pin from the Arduino to drive the whole display and would supply bright RGB light.

Thanks for your suggestion. Actually i am doing the same.Using 74HC595 per digit which works fine. But my question is there are three different logics for leds. I asked what is the best way to implement it. Did you get my question?

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


text:
How to interconnect multiple Arduinos with a Rpi to control home-lights/switches
While planning the lightning infrastructure (wall-switches and lights) of my new home (it's still under-construction) I choosed to go through the "automated route" way and due to my background (I'm an "old" system/network administrator with programming skills and plenty of Open-Source "passion" and "advocacy") I'm seriously trying to implement it with three Arduinos and one RPi2.
Due to number/location of wall-push-buttons and lights, I'd like to use three MEGA interfacing both wall-push-buttons and lights of surrouding rooms. Furthermore, a RPi2 (or similar) will be used as a "controller" to properly programs MEGAs, when needed, and interfacing some other equipments (touch-screen; wifi tablet/smartphone; remote-controls; etc.) via the IP-network.
The schema I'm trying to implement is similar to this one:

where you see:

9 lights (L1 to L9) each one controlled by its own dedicated relay (R1 to R9);
7 wall push-buttons (WPB1 to WPB7), to be used to turn on/off one or more lights;
3 MEGAs interfacing wall-push-buttons and lights;
1 RPi2, acting as "supervisor" and "Internet/Ethernet gateway".

My main architectural problem relates to the interconnection between RPI2 and MEGAs. As each device will be located several tens of meters aways from each other, I ended with two only option (please, correct me if I'm wrong):

Ethernet
RS485

(BTW: I'm explicitely excluding "wireless connections", as I've already placed all the electrical pipes in a "compatible" way. In other words: I'd like to avoid wireless technologies within the "controlling network")
As for Ethernet, I'll choose it as a 2nd option, due both to a slightly higher cost and complexity (need a switch to be powered on; additional cabling issues; etc.).
I've extensively researched the "RS485 bus" and found that it's relatively easy --from a physical point of view-- to implement it with two wires in a multidrop configuration.
Unfortunately, from an "application point of view", things are more complex as it supports only "half-duplex" communications and, even worse, there is no provision to avoid "collisions" when communicating (that's why, probably, the MODBUS protocol --tipically employed on RS485 bus-- provides a "single-master; multiple-slaves" scenario).
Before the questions, I need to add another constraint: I want the infrastructure to be "as much fault-tolerant as possible", expecially towards problems with the BUS and/or with the "controller" (the RPI2). In other words:

each MEGA should allow to turn on its own lights when one of its own push-button requires this. For example:

if WPB1 controls L2 and L3, it need to be working even if the BUS is broken or the RPI2 is powered off;
if WPB3 controls L4 and L9, then should the bus/RPI2 have problems, only L4 will be powered on when WPB3 is pressed;

So, after all of the above, here are my questions:

is a two-wire RS485 multidrop bus, a suitable choice for my scenario?
if not, which (possibly cheap and simple) other solutions may I investigate?
if yes, which is the logic that I need to implement on MEGAs, as:

a) they need to act as "slave", with respect to RPI2 when turning on lights commanded by push-button connected to other MEGAs or when the RP2 decide to turn-on some lights (for example, due to remote/Internet access);
b) they need to act as "master", when one of their push-buttons is pressed and... this need to be communicated to RPI2 so to send commands to other MEGAs so to turn on "hosted" lights;

as for 3b), insted of having MEGAs acting as master when a WPB is pressed, may I implement a "frequent-polling" logic on the RPI2? If yes, which is a reasonable value for such a polling (1 poll per second? 5 polls per second? too much? too low?)

I understand that this is a too-wide question, but I really did lots of researches and despite lots, and lots, and lots of on-line documentation, I've been unable to find an answer to those questions.

Update 1

in terms of total numbers, I'll have 31 lights to be controlled by 46 wall push-buttons, more or less equally distributed in 4 distinct panel-boards;
As for the choise of MEGA (vs. UNO), I've choosed MEGA due to the bigger number of I/O PINs. I simply choosed the board with the maximun number of PINs;
As for the RPI2, I choosed to employ a proper "computer" (vs. an additional microcontroller), 'cause I want a sort of "decoupling" between the "physical controlling network" and the "User Management Interface". In other words, I want the management of physical buttons/relais to be handled by PLC-like device (Arduino: very quick power on; sort of real-time performance; very reliable; minor/no external "computing" factors introducing delays/problems); while, at the same time, all the user-interface be handled by a real-computer where I can easily write powerful HTTP web-services and/or really complex "logics", using technologies and languages that doesn't fit well with Arduino (later on --much later on--, I plan to add several 150$ full-HD 10.1" android tablets allaround the house, that will act as wireless "clients" towards what need to be a "powerful" (in terms of computing capacities) web-server; Also I plan to add various sensors [temperature; humidity; contacts; power-meters; etc.] whose data need to be stored for trending/archiving reasons). Hence, I tought about RPi2, than can easily be replaced with something more powerful, should it be needed.

You'll probably want something connected to the RPi that can do 9-bit communications on RS-485. Linux doesn't support 9-bit UARTs so you'd have to play ugly tricks with the parity bit without it.

What if I'll connect, via RS485, only ARDUINOs? I mean, the problem you're mentioning is strictly introduced by connecting RPI to RS485, right? I'm asking, 'cause based also on @nick-gammon answer below, I'll probably terminate the RS485 bus on ad additional Arduino, and having the interconnection between RPI and Arduino using Ethernet (and not RS485). In such a case, RPI will not need to speak RS485 and problem shoud disappear, right?

I just wanted to note that the chance of packet collisions is rather low. You only send packets when a switch is pressed, or when a light needs to turn on. Unless you live inside a disco, this only happens a few times a day per light/switch.

@Gerben: with my two young sons (2,5 and 5,5), I can assure you that such a probability is NOT so low as you might expect under "normal" conditions :-). Jokes aside, consider that should everything runs smoothly, I plan to add LOTS of additional sensors/devices to be queried via "bus traffic" (temperature/humidity sensors [one per room]; open/close contacts for doors/windows [at least two for each windows]; electricity-power-meters and water-usage-meters probably generating "pulses" to be collected in some way. So, again, when "collision" will happen, will my MEGAs "survive"? Or they'll burn?

I did a lengthy post about RS485.

First, your use of Megas seems an overkill, unless you already have them to hand. A Uno, or one of the smaller form-factor boards would seem to be perfectly adequate to monitor a few switches and turn on a couple of lights.
Even the Rpi seems unnecessary. Another Uno could easily monitor your RS485 lines and connect via Ethernet (an Ethernet shield) to the rest of your house or whatever you are doing.

... there is no provision to avoid "collisions" when communicating ...

Well, you build that in. You give each Mega an address (eg. stored in EEPROM) and then you "address" the one you want, and then wait for a response. For example, in the code from my page above:
Master
#include "RS485_protocol.h"
#include <SoftwareSerial.h>

const byte ENABLE_PIN = 4;
const byte LED_PIN = 13;

SoftwareSerial rs485 (2, 3);  // receive pin, transmit pin

// callback routines

void fWrite (const byte what)
  {
  rs485.write (what);
  }

int fAvailable ()
  {
  return rs485.available ();
  }

int fRead ()
  {
  return rs485.read ();
  }

void setup()
{
  rs485.begin (28800);
  pinMode (ENABLE_PIN, OUTPUT);  // driver output enable
  pinMode (LED_PIN, OUTPUT);  // built-in LED
}  // end of setup

byte old_level = 0;

void loop()
{

  // read potentiometer
  byte level = analogRead (0) / 4;

  // no change? forget it
  if (level == old_level)
    return;

  // assemble message
  byte msg [] = {
     1,    // device 1
     2,    // turn light on
     level // to what level
  };

  // send to slave
  digitalWrite (ENABLE_PIN, HIGH);  // enable sending
  sendMsg (fWrite, msg, sizeof msg);
  digitalWrite (ENABLE_PIN, LOW);  // disable sending

  // receive response
  byte buf [10];
  byte received = recvMsg (fAvailable, fRead, buf, sizeof buf);

  digitalWrite (LED_PIN, received == 0);  // turn on LED if error

  // only send once per successful change
  if (received)
    old_level = level;

}  // end of loop

You configure the RS485 transceiver to either send or receive. Normally it is in receive mode, and you switch to send mode to send a "packet" of data. (See "enable sending" above).

Now the addressed device turns its transceiver into "send" mode and replies. The code in the library I wrote has a time-out, so if that particular slave is dead, the receive times out. You might remember that at the master end and try to communicate with it less often. Or you may not care if the time-out is short.
Slave
#include <SoftwareSerial.h>
#include "RS485_protocol.h"

SoftwareSerial rs485 (2, 3);  // receive pin, transmit pin
const byte ENABLE_PIN = 4;

void fWrite (const byte what)
  {
  rs485.write (what);
  }

int fAvailable ()
  {
  return rs485.available ();
  }

int fRead ()
  {
  return rs485.read ();
  }

void setup()
{
  rs485.begin (28800);
  pinMode (ENABLE_PIN, OUTPUT);  // driver output enable
}

void loop()
{
  byte buf [10];

  byte received = recvMsg (fAvailable, fRead, buf, sizeof (buf));

  if (received)
    {
    if (buf [0] != 1)
      return;  // not my device

    if (buf [1] != 2)
      return;  // unknown command

    byte msg [] = {
       0,  // device 0 (master)
       3,  // turn light on command received
    };

    delay (1);  // give the master a moment to prepare to receive
    digitalWrite (ENABLE_PIN, HIGH);  // enable sending
    sendMsg (fWrite, msg, sizeof msg);
    digitalWrite (ENABLE_PIN, LOW);  // disable sending

    analogWrite (11, buf [2]);  // set light level
   }  // end if something received

}  // end of loop

Note: The example code from my linked page does not read the address from EEPROM, however that is trivial to implement.

I can't see any particular reason why you could not interrogate the slaves quite frequently. What else would the master be doing? You could also set up the master as a HTTP server so you could talk to it from your laptop, or some other part of the house.

My wiring:

To demonstrate the idea, I set up two Unos, connected via about 8 m of bell-wire (not even twisted pair, and certainly not shielded).

One Uno was running the standard ASCII table sketch (at 9600 baud), its Tx pin went into the LTC1480, and then the A/B pins went to the bell wire.
The other Uno was connected as a USB interface (Reset connected to ground) and it was just echoing whatever arrived on the Tx pin to the USB.
As far as I could see, it worked perfectly.

I will not need any poll at all, as with your approach I can implement a "single-master/multiple-slave" context... but with a "moving" master. Is this right?

My answer above assumed that the slaves were more likely to fail than the master (can't quite think why this would happen, but perhaps based on the fact that there are more slaves than masters, and the master doesn't control things like lights).
I find my Arduinos extremely reliable when doing simple things (like unlocking a door when a RFID card is presented).
You could conceivably build a fall-back position into the slaves. After all, if they get polled every second, and then no poll arrives, they could conceivably attempt to take over as master, perhaps in ascending order of device number, to avoid conflicts. Part of this polling by the "new master" could be to check the "original master" to see if it was ready to resume its duties.
The library I described on my linked page has error checking built into it, the idea being that by checking a CRC on the packet you ensure that you don't come in half-way through a packet and misinterpret the data in it.
You could also build in some randomness of poll times to resolve a deadlock if two slaves attempted to become master at once. If a slave failed it could wait for a random (and increasing) time before trying again to give another slave a chance to do it.

I just wanted to note that the chance of packet collisions is rather low. You only send packets when a switch is pressed, or when a light needs to turn on.

Gerben is right, but I would be worried that a notification about a switch had gone unnoticed. One possible work-around here is rather than the slaves replying with state changes to a query, they reply with the current state. So it might go:
Master: Slave 3, what is your status?
Slave 3: Lights 1 and 4 on, lights 2 and 3 off.

I will not need any poll at all, as with your approach I can implement a "single-master/multiple-slave" context... but with a "moving" master. Is this right?

I've been thinking about this a bit, and I think now you could make a system that is basically master-free. It could work like this:

Each device has its own address, which it gets from EEPROM (or DIP switches). eg. 1, 2, 3, 4, 5 ...

You choose a range of addresses you are going to use (eg. maximum of 10)

When the device powers up it first listens for other devices "talking" on the bus. Hopefully it will hear at least one other (if not, see below).

We decide on a fixed "message packet", say of 50 bytes including address, CRC, etc. At 9600 baud that would take 52 ms to send.

Each device gets a "slot" of time, and waits its turn to talk to the bus.

When its timeslot arrives, it goes into output mode, and broadcasts its packet which includes its own address. Therefore all the other devices can now read its status (and act upon it if necessary). Eg. device 1 might report that switch 3 is closed, which means device 2 must turn a light on.

Ideally, you know your timeslot has arrived because your device address is one greater than the packet you just listened to. Eg. You are device 3. You just heard device 2 announce its status. Now it's your turn. Of course, you wrap around at the maximum number, so after device 10 you go back to device 1.

If a device is missing and does not respond, you give it (say) half a timeslot to respond, and then assume it is dead, and every device on the bus now assumes the next timeslot has started. (eg. You heard device 2, device 3 should respond, after 25 ms of inactivity, device 4 can now respond). This rule gives a device 25 ms to respond, which should be plenty even if it is servicing an interrupt or something like that.

If multiple devices in sequence are missing you count a 25 ms gap for each missing device, until it is your turn.

Once you get at least one response the timing is resynchronized, so any drift in clocks would be cancelled.

The only difficulty here is that upon initial power-up (which might happen simultaneously if the power to the building is lost and then restored) there is no device currently broadcasting its status, and thus nothing to synchronize to.
In that case:

If after listening long enough for all devices to be heard (eg. 250 ms) and hearing nothing, the device tentatively assumes it is the first one and makes a broadcast. However possibly two devices will do that at the same time, and thus never hear each other.

If a device has not heard from another device, it staggers the time between broadcasts randomly (perhaps seeding the random-number generator from its device number, to avoid all devices "randomly" staggering the broadcasts by the same amount).

This random staggering by additional amounts of time won't matter, because there is no-one listening anyway.

Sooner or later one device will get exclusive use of the bus and the other ones can then synchronize with it in the usual way.

This random gap between attempts to communicate is similar to what Ethernet used to do when multiple devices shared one coaxial cable.

Demo of master-free system
This was an interesting challenge, so I put together a demo of doing this without having any specific master, as described above.
First you need to set up the current device address, and the number of devices, in EEPROM, so run this sketch, changing myAddress for each Arduino:
#include <EEPROM.h>

const byte myAddress = 3;
const byte numberOfDevices = 4;

void setup ()
  {
  if (EEPROM.read (0) != myAddress)
    EEPROM.write (0, myAddress);
  if (EEPROM.read (1) != numberOfDevices)
    EEPROM.write (1, numberOfDevices);

  }  // end of setup

void loop () { }

Now upload this to each device:
/*
 Multi-drop RS485 device control demo.

 Devised and written by Nick Gammon.
 Date: 7 September 2015
 Version: 1.0

 Licence: Released for public use.

 For RS485_non_blocking library see: http://www.gammon.com.au/forum/?id=11428
 For JKISS32 see: http://forum.arduino.cc/index.php?topic=263849.0
*/

#include <RS485_non_blocking.h>
#include <SoftwareSerial.h>
#include <EEPROM.h>

// the data we broadcast to each other device
struct
  {
  byte address;
  byte switches [10];
  int  status;
  }  message;

const unsigned long BAUD_RATE = 9600;
const float TIME_PER_BYTE = 1.0 / (BAUD_RATE / 10.0);  // seconds per sending one byte
const unsigned long PACKET_LENGTH = ((sizeof (message) * 2) + 6); // 2 bytes per payload byte plus STX/ETC/CRC
const unsigned long PACKET_TIME =  TIME_PER_BYTE * PACKET_LENGTH * 1000000;  // microseconds

// software serial pins
const byte RX_PIN = 2;
const byte TX_PIN = 3;
// transmit enable
const byte XMIT_ENABLE_PIN = 4;

// debugging pins
const byte OK_PIN = 6;
const byte TIMEOUT_PIN = 7;
const byte SEND_PIN = 8;
const byte SEARCHING_PIN = 9;
const byte ERROR_PIN = 10;

// action pins (demo)
const byte LED_PIN = 13;
const byte SWITCH_PIN = A0;

// times in microseconds
const unsigned long TIME_BETWEEN_MESSAGES = 3000;
unsigned long noMessagesTimeout;

byte nextAddress;
unsigned long lastMessageTime;
unsigned long lastCommsTime;
unsigned long randomTime;

SoftwareSerial rs485 (RX_PIN, TX_PIN);  // receive pin, transmit pin

// what state we are in
enum {
   STATE_NO_DEVICES,
   STATE_RECENT_RESPONSE,
   STATE_TIMED_OUT,
} state;

// callbacks for the non-blocking RS485 library
size_t fWrite (const byte what)
  {
  rs485.write (what);
  }

int fAvailable ()
  {
  return rs485.available ();
  }

int fRead ()
  {
  lastCommsTime = micros ();
  return rs485.read ();
  }

// RS485 library instance
RS485 myChannel (fRead, fAvailable, fWrite, 20);

// from EEPROM
byte myAddress;        // who we are
byte numberOfDevices;  // maximum devices on the bus

// Initial seed for JKISS32
static unsigned long x = 123456789,
                     y = 234567891,
                     z = 345678912,
                     w = 456789123,
                     c = 0;

// Simple Random Number Generator
unsigned long JKISS32 ()
  {
  long t;
  y ^= y << 5;
  y ^= y >> 7;
  y ^= y << 22;
  t = z + w + c;
  z = w;
  c = t < 0;
  w = t & 2147483647;
  x += 1411392427;
  return x + y + w;
  }  // end of JKISS32

void Seed_JKISS32 (const unsigned long newseed)
  {
  if (newseed != 0)
    {
    x = 123456789;
    y = newseed;
    z = 345678912;
    w = 456789123;
    c = 0;
    }
  }  // end of Seed_JKISS32

void setup ()
  {
  // debugging prints
  Serial.begin (115200);
  // software serial for talking to other devices
  rs485.begin (BAUD_RATE);
  // initialize the RS485 library
  myChannel.begin ();

  // debugging prints
  Serial.println ();
  Serial.println (F("Commencing"));
  myAddress = EEPROM.read (0);
  Serial.print (F("My address is "));
  Serial.println (int (myAddress));
  numberOfDevices = EEPROM.read (1);
  Serial.print (F("Max address is "));
  Serial.println (int (numberOfDevices));

  if (myAddress >= numberOfDevices)
    Serial.print (F("** WARNING ** - device number is out of range, will not be detected."));

  Serial.print (F("Packet length = "));
  Serial.print (PACKET_LENGTH);
  Serial.println (F(" bytes."));

  Serial.print (F("Packet time = "));
  Serial.print (PACKET_TIME);
  Serial.println (F(" microseconds."));

  // calculate how long to assume nothing is responding
  noMessagesTimeout = (PACKET_TIME + TIME_BETWEEN_MESSAGES) * numberOfDevices * 2;

  Serial.print (F("Timeout for no messages = "));
  Serial.print (noMessagesTimeout);
  Serial.println (F(" microseconds."));

  // set up various pins
  pinMode (XMIT_ENABLE_PIN, OUTPUT);

  // demo action pins
  pinMode (SWITCH_PIN, INPUT_PULLUP);
  pinMode (LED_PIN, OUTPUT);

  // debugging pins
  pinMode (OK_PIN, OUTPUT);
  pinMode (TIMEOUT_PIN, OUTPUT);
  pinMode (SEND_PIN, OUTPUT);
  pinMode (SEARCHING_PIN, OUTPUT);
  pinMode (ERROR_PIN, OUTPUT);

  // seed the PRNG
  Seed_JKISS32 (myAddress + 1000);

  state = STATE_NO_DEVICES;
  nextAddress = 0;

  randomTime = JKISS32 () % 500000;  // microseconds
  }  // end of setup

// set the next expected address, wrap around at the maximum
void setNextAddress (const byte current)
  {
  nextAddress = current;
  if (nextAddress >= numberOfDevices)
    nextAddress = 0;
  }  // end of setNextAddress

// Here to process an incoming message
void processMessage ()
  {

  // we cannot receive a message from ourself
  // someone must have given two devices the same address
  if (message.address == myAddress)
    {
    digitalWrite (ERROR_PIN, HIGH);
    while (true)
      { }  // give up
    }  // can't receive our address

  digitalWrite (OK_PIN, HIGH);

  // handle the incoming message, depending on who it is from and the data in it

  // make our LED match the switch of the previous device in sequence
  if (message.address == (myAddress - 1))
    digitalWrite (LED_PIN, message.switches [0]);

  digitalWrite (OK_PIN, LOW);
  } // end of processMessage

// Here to send our own message
void sendMessage ()
  {
  digitalWrite (SEND_PIN, HIGH);
  memset (&message, 0, sizeof message);
  message.address = myAddress;

  // fill in other stuff here (eg. switch positions, analog reads, etc.)

  message.switches [0] = digitalRead (SWITCH_PIN);

  // now send it
  digitalWrite (XMIT_ENABLE_PIN, HIGH);  // enable sending
  myChannel.sendMsg ((byte *) &message, sizeof message);
  digitalWrite (XMIT_ENABLE_PIN, LOW);  // disable sending
  setNextAddress (myAddress + 1);
  digitalWrite (SEND_PIN, LOW);

  lastCommsTime = micros ();   // we count our own send as activity
  randomTime = JKISS32 () % 500000;  // microseconds
  }  // end of sendMessage

void loop ()
  {
  // incoming message?
  if (myChannel.update ())
    {
    memset (&message, 0, sizeof message);
    int len = myChannel.getLength ();
    if (len > sizeof message)
      len = sizeof message;
    memcpy (&message, myChannel.getData (), len);
    lastMessageTime = micros ();
    setNextAddress (message.address + 1);
    processMessage ();
    state = STATE_RECENT_RESPONSE;
    }  // end of message completely received

  // switch states if too long a gap between messages
  if  (micros () - lastMessageTime > noMessagesTimeout)
    state = STATE_NO_DEVICES;
  else if  (micros () - lastCommsTime > PACKET_TIME)
    state = STATE_TIMED_OUT;

  switch (state)
    {
    // nothing heard for a long time? We'll take over then
    case STATE_NO_DEVICES:
      if (micros () - lastCommsTime >= (noMessagesTimeout + randomTime))
        {
        Serial.println (F("No devices."));
        digitalWrite (SEARCHING_PIN, HIGH);
        sendMessage ();
        digitalWrite (SEARCHING_PIN, LOW);
        }
      break;

    // we heard from another device recently
    // if it is our turn, respond
    case STATE_RECENT_RESPONSE:
      // we allow a small gap, and if it is our turn, we send our message
      if (micros () - lastCommsTime >= TIME_BETWEEN_MESSAGES && myAddress == nextAddress)
        sendMessage ();
      break;

    // a device did not respond in its slot time, move onto the next one
    case STATE_TIMED_OUT:
      digitalWrite (TIMEOUT_PIN, HIGH);
      setNextAddress (nextAddress + 1);
      lastCommsTime += PACKET_TIME;
      digitalWrite (TIMEOUT_PIN, LOW);
      state = STATE_RECENT_RESPONSE;  // pretend we got the missing response
      break;

    }  // end of switch on state

  }  // end of loop

As it currently stands, if you close a switch on A0 (short to ground) it will turn off a LED (pin 13) on the next highest device in sequence. This proves that the devices are talking to each other. Of course in practice you would have something more sophisticated in the packet which is being broadcast.
I found in testing that the LED appeared to come on and off instantly.
With all devices disconnected the first one connected will "hunt" for other devices. If you have debugging LEDs connected as I did you can see the "search" LED come on at random intervals as it broadcasts its packet with randomly-varying gaps. Once you have a second one connected they settle down and just exchange information. I tested with three connected at once.
It would probably be more reliable with HardwareSerial - I used SoftwareSerial to help with debugging. A few small changes would accomplish that.

Amended schematic

Screen-shots of the code in action
These images show the code working. First, with only one device connected:

You can see from the pulses there that the device is broadcasting its data at randomly-varying intervals, to avoid continuing to clash with another device that powered up at the same moment.

Now we see blocks of data from two devices, with roughly the same size gaps in the middle. I configured it for four devices, but only two are present, so we see two blocks of data, and two gaps.

Now with three devices online, we see three blocks of data, and one gap, as the missing device is bypassed.

If you are checking the figures, these were taken with the baud rate doubled, as a test, to 19200 baud.

Cable run test
For a proper hardware test, I connected the devices up to my in-house UTP cabling. I have cat-5 cable running from various rooms to a central plug-board. Going from one end of the house to another (a reasonable length run) it still works fine. There is 5 m cable between the Arduino and the wall socket, for a start. Plus another 5 m cable at the other end. Then there are about 2 x 15 m runs from the rooms to the switch room, and inside that there is a short bridging cable to connect them together.
This was with the boards still programmed to run at 19200 baud.

1st) Thanks VERY MUCH for your answer and RS-485 tutorial. I'll surely use it ; 2nd) as for MEGA and RPIs involvement, I've updated the OP. Please, refer to it for details; 3rd) as for "I can't see any particular reason why you could not interrogate the slaves quite frequently", is a 10-polls per second, on a 9600 baud rate,  a reasonable choice? And finally: if I understood correctly, I will not need any poll at all, as with your approach I can implement a "single-master/multiple-slave" context... but with a "moving" master. Is this right?

See updated answer.

See amended answer which demonstrates a moving master concept.

is a 10-polls per second, on a 9600 baud rate, a reasonable choice? - in my current test (see screenshots) I am testing 4 devices repeatedly in 75 ms at 19200 baud, so that is 13 status reports a second. Basically that means one device should react to a status change (eg. a switch closure) from another device in 1/10th of a second. Your initial question mentioned 4 devices, so you should be able to get similar results.

could you please tell me where you got the white wire clip that is in the picture with the red background (the clip is attached to the wire bundle)

Ebay: https://www.ebay.com/itm/400846299509 . Search for 10x 2p Spring Connector wire no welding no screw.

Remember RS485 is not a protocol, it is a definition of a physical transport layer.  With the Mega as you chose you can use serial 1,2,3 and run them in full duplex mode over the RS485 network e.e. you can receive what you send.
I have it operating in a multi master configuration.  Each mega when it transmits it also receives what it just sent and can determine on a byte by byte basis if it needs to back off.  The delay before coming back on line is determined by the node address and when the bus becomes available.
The code will use the write function instead of the print function allowing each byte to be checked. (In time I probably will do it via software and emulate CAN or just use a can controller). Yes 8 bits works just fine, the ninth bit is a parity bit or other uses depending on who is defining it.
My test system is operating with packets and sends in this format:
|Length|Target|Source|Sequence|Command|Flags|Data|Check
and expects an ACK in response.  This is relative simple first pass and has no illegal codes. All bytes are Hex but you can use what you want.
This gives me Carrier Sense, multiple access but with destructive arbitration.  If you want CSMANDA just use a CAN physical layer or bit bang the data you send then you can arbitrate on a bit by bit basis.  It won't be that much different in software other then the transmit portion.
I am planning on using the RPi with Linux as the main node. With 8 bit data it will work just fine.  I just started about two weeks ago on this configuration and so far it is going well. I am operating at 9600 baud and have a lot of free time.
Gil

How do you have things set up to sense collisions? Does the particular chip you're using for the RS-485 interface return the sensed data on the link on the RX line at the same time as you send it data on the TX line and it transmits that?

I think the CDBUS protocol for RS485 is exactly what you want, it introduce an arbitration mechanism that automatically avoids conflicts like the CAN bus. I can even transfer video stream through it:

Full video:
https://youtu.be/qX5dh4wcfSk
The Raspberry Pi can output preview video and control command at the same time. We can monitor the recognition process on the PC. When problems are encountered, it is convenient to know the reason and adjust the parameters, and disconnecting the PC will not affect the demo operation.

In addition, the Raspberry Pi can access the internet at any time through the PC, and it is easy to update software and for remote control.
Details about the CDBUS:

https://github.com/dukelec/cdbus_doc (Introduction)
https://github.com/dukelec/cdbus_ip (Protocol details & FPGA IP core)

Update:
Connect the CDCTL-Bx controller to an Arduino:

The mention of video is irrelevant to the question asked and the Arduino subject of this site, and so a bit distracting from it.  Such a volume of data could well cause problems for resource constrained systems unless elegantly handled.  If you want to propose this scheme, you should explain how it is suitable for the problem of the question, and for an Arduino... if it actually is.

It's the same for Arduino, replace the Raspberry Pi Zero in my diagram to an Arduino, in other words, add an external shield board of RS485 controller for Arduino, communicate through I2c or SPI interface.

If you want to use Nick Gammon's protocol you might find this useful: https://github.com/Sthing/Nick-Gammon-RS485
It is my implementation of the protocol in Python (for use on a RaspberryPi).
I have only tested python-to-python yet, testing against Nick Gammon's code is next on my to do list.
/Thing

I've been succesfull, lately, in testing Nick Gammon's RS485 non-blocking protocol, between three MEGAs in a "one master, two slaves" scenario. I've encountered several problems, mainly introduced by the usage of physical serials (and not SoftwareSerials). Luckily, I've been able to fix everything. I've published the running code (with some other details) here: https://github.com/verzulli/arduino-smart-home - I'm currently actively working on such project, and plan to update it during upcoming weeks.

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


text:
Unexpected output form Serial.println
So I have a teensy and an arduino uno connected together via I2C, however some very odd behavior is occurring, when monitoring the serial connection for shorter data sent over I2C I receive the expected serial output. However if the data is longer I only receive 2 characters. More strange even is that if I send the longer data again I receive none, but if I send the shorter data I receive the expected output. After sending the shorter data again sending the longer data will result is the odd 2 characters.
Uno code
     //#include
 #include <Wire.h>

boolean pinout = 0;
byte current[512];

void setup() {
  // put your setup code here, to run once:
  Wire.begin(1);
  Serial.begin(115200);
  Wire.onReceive(data);
  //DmxSimple.usePin(3);
  //DmxSimple.maxChannel(30);
}

void loop() {

}

void data(int numBytes){
//Serial.println("DATA RECIVED");

 delay(500);

 char input[20];
 int pos = 0;

 while(Wire.available()){
   input[pos++] = Wire.read();
  }
  input[pos++] = '\0';

  Serial.print("Recived \"");
  Serial.print(input);
  Serial.println("\"");

  char* next = strchr(input, ',');
  while(next != 0){
  *next = 0;
  next++;
  char* splitter = strchr(next, ':');
  if(splitter != 0){
  *splitter = 0;
  splitter++;
  int channel = atoi(next);
  int value = atoi(splitter);
      //DmxSimple.write(channel,value);
      Serial.print(channel); Serial.print(":"); Serial.println(value);
    }
  }
}

Teensy code
            #include <i2c_t3.h>
            //#include <ArduinoPebbleSerial.h>

     /*
    static const uint16_t SERVICE_ID = 0x1001;
static const uint16_t UPTIME_ATTRIBUTE_ID = 0x0002;
static const size_t UPTIME_ATTRIBUTE_LENGTH = 4;
static const uint16_t LAMP_ATTRIBUTE_ID = 0x0003;
static const size_t LAMP_ATTRIBUTE_LENGTH = 20;

static const uint16_t SERVICES[] = {SERVICE_ID};
static const uint8_t NUM_SERVICES = 1;

static const uint8_t PEBBLE_DATA_PIN = 1;
static uint8_t buffer[GET_PAYLOAD_BUFFER_SIZE(4)];

typedef struct __attribute__((packed)){
  uint8_t channel;
  uint8_t value;
} DMXP;*/

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Wire.begin();
  Serial.begin(9600);
  /*
 #if defined(__MK20DX256__) || defined(__MK20DX128__)
  // Teensy 3.0/3.1 uses hardware serial mode (pins 0/1) with RX/TX shorted together
 ArduinoPebbleSerial::begin_hardware(buffer, sizeof(buffer), Baud57600, SERVICES, NUM_SERVICES);
#elif defined(__AVR_ATmega32U4__)
 // Teensy 2.0 uses the one-wire software serial mode
 ArduinoPebbleSerial::begin_software(PEBBLE_DATA_PIN, buffer, sizeof(buffer), Baud57600, SERVICES,
                                  NUM_SERVICES);
#else
#error "This example will only work for the Teensy 2.0, 3.0, or 3.1 boards"
#endif
*/
/*for(int i = 1; i < 8; i++){
  sendChannel(i,0);
}
*/

}

/*
void handle_dmx_request(RequestType type, size_t length) {
if (type != RequestTypeWrite) {
  return;
}

DMXP cmd = *(DMXP*)buffer;
sendChannel(cmd.channel, cmd.value);

// ACK that the write request was received
ArduinoPebbleSerial::write(true, NULL, 0);
ArduinoPebbleSerial::notify(SERVICE_ID, UPTIME_ATTRIBUTE_ID);
}
*/

void loop() {

  /*
  if (ArduinoPebbleSerial::is_connected()) {
  digitalWrite(13,true);
} else {
  digitalWrite(13,false);
}

uint16_t service_id;
uint16_t attribute_id;
size_t length;
RequestType type;
if (ArduinoPebbleSerial::feed(&service_id, &attribute_id, &length, &type)) {
  // process the request
  if (service_id == SERVICE_ID) {
    switch (attribute_id) {
      case LAMP_ATTRIBUTE_ID:
        handle_dmx_request(type, length);
        break;
      default:
        break;
    }
  }
}
*/

}

void serialEvent(){
  if(Serial.read() == 't'){
  digitalWrite(13,true);
  Serial.println("Starting Controller");
  int chans[8] = {1,2,3,4,5,6,7,8};
  int vals[8] = {2,4,6,8,16,32,64,128};
  sendChannel(chans,vals,4);
  } else {
    sendChannel(1,1);
  }
  while(Serial.available()){
    Serial.println(Serial.read());
  }
}

void sendChannel(int chan, int val){
 char chno[8];
  itoa(chan,chno,10);
  char vano[8];
 itoa(val,vano,10);
 char message[20];
 int messagei = 0;
 for(int i = 0; i < 7; i++){
 if(chno[i] == '\0'){
   break;
  }
 message[messagei++] = chno[i];
}
 message[messagei++] = ':';
 for(int i = 0;i < 7; i++){
 if(vano[i] == '\0'){
  break;
 }
 message[messagei++] = vano[i];
 }
  //message[messagei++] = '\n';
//message[messagei++] = '\r';
message[messagei++] = '\0';

Serial.println(message);

Wire.beginTransmission(1);
Wire.write(message);
Wire.endTransmission();
}

void sendChannel(int chan[], int val[], int num){
 char message[20*num + 1];
 int at = 0;

 for(int i = 0; i < num; i++){
char chno[8];
itoa(chan[i],chno,10);
char vano[8];
itoa(val[i],vano,10);
for(int i = 0; i < 7; i++){
  if(chno[i] == '\0'){
    break;
  }
  message[at++] = chno[i];
}
message[at++] = ':';
for(int i = 0;i < 7; i++){
  if(vano[i] == '\0'){
    break;
  }
  message[at++] = vano[i];
  }
  if(i+1!=num){
  message[at++] = ',';
  } else {
  message[at++] = 0;
 }
 }

 char finalMessage[at+1];
 for(int i = 0; i <= at; i++){
finalMessage[i] = message[i];
 }

 Serial.println(finalMessage);

Wire.beginTransmission(1);
Wire.write(message);
Wire.endTransmission();

}

(If modifying the teensy code to run on a second arduino replace the line #include <i2c_t3.h> with #include <Wire.h> no other changes should be necessary)
To use the Teensy code open a serial terminal to access it, press 't' to send a long packet, or any other character to send a shorter one.

In future please use "code quoting" for referencing include directives. As you can see from your post (unless it is fixed now) things in angled brackets are treated as HTML and don't render properly.

Your code is short enough to include in the post. Please post it rather than sending people of to GitHub for short amounts of simple code. Use "code formatting" - select the code and hit Ctrl+K to indent if four spaces and then it should be very readable.

Your code which I will reproduce here as it wasn't in the question has a major issue:
//#include <DmxSimple.h>

#include <Wire.h>

boolean pinout = 0;
byte current[512];

void setup() {
  // put your setup code here, to run once:
  Wire.begin(1);
  Serial.begin(115200);
  Wire.onReceive(data);
  //DmxSimple.usePin(3);
  //DmxSimple.maxChannel(30);
}

void loop() {

}

void data(int numBytes){
  //Serial.println("DATA RECIVED");

  delay(500);

  char input[20];
  int pos = 0;

  while(Wire.available()){
    input[pos++] = Wire.read();
  }
  input[pos++] = '\0';

  Serial.print("Recived \"");
  Serial.print(input);
  Serial.println("\"");

  char* next = strchr(input, ',');
  while(next != 0){
   *next = 0;
   next++;
    char* splitter = strchr(next, ':');
    if(splitter != 0){
      *splitter = 0;      Wire.onReceive(data);
  //DmxSimple.usePin(3);
  //DmxSimple.maxChannel(30);
}

Your function data does Serial.prints. It is called as an interrupt service routine effectively, and thus should not do serial prints:
      Wire.onReceive(data);
    }

    void loop() {

    }

    void data(int numBytes){

...

      Serial.print("Recived \"");
      Serial.print(input);
      Serial.println("\"");

More strange even is that if I send the longer data again I receive none, ...

Yep, that will definitely happen. The serial printing "blocks" if you print a lot, and thus the code will hang indefinitely.

  delay(500);

You definitely should not use delay in an interrupt routine. It will almost certainly hang because the timer interrupts which are needed for delay to work are not being serviced.

  Wire.begin(1);

You should not be choosing to use I2C address 1. It is reserved. See:
7-bit, 8-bit, and 10-bit I2C Slave Addressing and I2C specification (pdf)
Slave Address   R/W Bit     Description
000 0000    0   General call address
000 0000    1   START byte(1)
000 0001    X   CBUS address(2)
000 0010    X   Reserved for different bus format (3)
000 0011    X   Reserved for future purposes
000 01XX    X   Hs-mode master code
111 10XX    X   10-bit slave addressing
111 11XX    X   Reserved for future purposes

(1) No device is allowed to acknowledge at the reception of the START byte.
(2) The CBUS address has been reserved to enable the inter-mixing of CBUS compatible and I2C-bus compatible devices in the same system. I2C-bus compatible devices are not allowed to respond on reception of this address.
(3) The address reserved for a different bus format is included to enable I2C and other protocols to be mixed. Only I2C-bus compatible devices that can work with such formats and protocols are allowed to respond to this address.


text:
Can I automatically loop inside a library?
I want to write a little library;
the unlibrarized functionality does:
checking in every loop-cycle some inputs,
doing some calculations with it
and finally setting a boolean to either true or false.
How do I periodically check the inputs inside the library?
I know that I could add a function-call  to the library in the loop()-function. But I would prefer to just check the boolean in the loop.
Is there a way, to instantiate a class and start an periodically function by doing so? And if, how does this constant checking affect/coexist with my 'normal' loop()-function?

Generally speaking, no, you can not take control of the processor away from the main "thread" in a library. The normal solution is to provide an update method or something like that. you could do the calculations in a function that returns your boolean answer, then the loop code is basically the same with or without asynchronous updating.
If you can use interrupts to read your input, either as an external interrupt or on an internal timer interrupt, then what you want could be achieved because the interrupt would take control away from the main execution context and give it to you.
Interrupt routines need to be fast and simple though, and it makes the "cost" of using the library higher, since there is a limited number of interrupts/timers and other libraries may require the one you code yours to use.
Of course, the more powerful arduinos that actually run an os will have support for multiprocessing which you could leverage to get the behavior you want. This answer is intended for a standard AVR based arduino (uno, mega, etc.)

I know that I could add a function-call to the library in the loop()-function. But I would prefer to just check the boolean in the loop.

What's the difference?
In the loop you can call something like:
void loop ()
  {
...
  if (mylibrary.ready ())
    {
    // it's time to act!
    }
...
  }

You can make a function, that returns a boolean type, which tells you if the thing you need to do is ready. That function does the checking before returning true or false.
After all, you are planning to check the boolean periodically, presumably often enough to notice it changing, why not have that be the point of noticing whatever-it-is you need to notice?

Yes, your are right! That's also the way I decided to go. Though, I tried to achieved this to have a more convenient implementation of the library: This if(ready==true) could theoretically be somewhere in loop(). But my periodically checking is VERY time-sensitive. If I call the function to check in the if(), I have to be sure, that there is no delay which alters the result.

Now it is like:
void loop()
{
freqdetec.checkFreq();
if (freqdetec.freqChanged()) {
// do stuff
}
}
The benefit from separating it into two calls is first, that it is more obvious what the single calls are doing, and second, I can place the checkFreq() in the beginning of the loop(), to avoid having it cluttered somewhere.

As another person answered, if it is highly time-sensitive you could use an interrupt (if this is a switch you are checking), or a timer firing periodically (if you need to test something like an analog reading).


text:
Long Distance Shift Register
I am using a Mega to control some relay boards. I have a 16 relay board near the mega, and I want to put an 8 relay board about 40 ft. away. So I figured I could use a shift register - instead of running 9 wires (8 relays and gnd) I could just run 4 (gnd, latch, clock, and data). I had some cat5e cable so I ran that from the Mega to the shift register. (I have an external 5V power supply so that does not come from the mega).
Problem is that is works, but inconsistently. I wrote a test program to turn on the relays in sequence. Sometimes it goes in order as it should but other times it skips relays or goes out of order.
I think there might be 4 sources of the problem:
1  The cat5e cable is too thin. Would a bigger wire help? Will twisting one pair together and using it like it was one wire help?
2 The shift_out code timing is off. I tried inserting some delay statments and that seemed to help a little. But I'm not sure where to insert them.
 void shift_out() {
     DigitalWrite(latch_pin, LOW);
     for (i = 0; i < 8; i++)  {
         DigitalWrite(data_pin, !!(bits & (1 << i)));
         DigitalWrite(clock_pin, HIGH);
         DigitalWrite(clock_pin, LOW);
     }
     DigitalWrite(latch_pin, HIGH);
 }

DigitalWrite is my own function that manipulates the PORTn bits instead of using Arduino's digitalWrite().
3 The shift register is very close to some 110V wires. Maybe interference?
4 The 5V power supply isn't powerful enough to power the relay board and the shift register?
Any suggestions welcome.
Edit: here's a pic of what I've built. The Cat5 cable runs directly back to the Arduino.

Since cant5 has 8 wires, use multiple wires for GND and 5V. Add a large capacitor to the shift register to prevent voltage fluctuations when currents go up or down. Slow down shiftOut so the signal has more time to stabilize.

@Gerben I think I will try the capacitor. This image from the Arduino web site uses one. They use 1uf. Is that "large" enough?

NO! Don't do that. That capacitor shouldn't be there. That one of the many things wrong on the Arduino website. Just add a capacitor between GND and VCC. The largest value you have. As those relays use quite a bit of current when they get energized.

What its the output voltage of that power-adapter? How is that even connected? I was thinking you could use that to power the relays, instead of carrying the 5V over that 40ft cat5 cable.

@Gerben Yes, I am using that to power the relays and the shift register as I was not getting enough power from the Arduino. However, I just added a capacitor and preliminary testing indicates it has fixed my problem. If you write that up as an answer, I will accept it. I added it before I saw your comment about the Arduino web site. I will move it from the latch pin to the VCC pin and see what happens.

This is a very interesting whitepaper from TI describing probably exactly what you need. But there are easier options (under the answers). http://www.ti.com/lit/an/slyt441/slyt441.pdf

SPI is supposed to be used for things in close proximity to each other. See Wikipedia - Serial Peripheral Interface Bus.

The Serial Peripheral Interface (SPI) bus is a synchronous serial communication interface specification used for short distance communication, primarily in embedded systems.

(My emphasis).
At that distance, and at standard SPI speeds you are probably losing signal integrity. The default SPI speed is system clock divided by 4 (that is, 4 MHz). It's not surprising some bits go missing after 40 feet.
See my page about SPI - you can use SPI to transfer to a 595 register (as described here).
(I'm assuming you are talking about a 74HC595 shift register)
I suggest running at a somewhat lower speed - insert delays after toggling the clock pin (each way). Or use the SPI hardware at (say) SPI_CLOCK_DIV128.

The shift register is very close to some 110V wires. Maybe interference

You might also want to look at a balanced line driver (eg. RS485) - I have a page describing that.

The 5V power supply isn't powerful enough to power the relay board and the shift register?

The register won't take much power. I trust the relays are solid-state ones and not coils that you are directly driving from the 595 chip?

Also see How do you use SPI on an Arduino?

I'm not using SPI, just connecting some of the digital outputs to the shift register. I guess I didn't make it clear in my post. I just made a circuit board with a SN74HC595N soldered on it with leads going back to the Arduino and going to the relay board. Sorry if the question wasn't clear - I'm just a hobbyist.

I understand what you are doing. As you can see from my page about the 595 chip you can drive it with SPI so it is effectively equivalent. All SPI is, is a clock and a data line (and another data line in the other direction if you want it). Plus a slave select (ie. the same thing as the latch pin). My suggestion about slowing down the transfer rate still stands.

A good debugging tool in this case is a logic analyzer. It could help understand the timing characteristics for your code (and wiring).
void shift_out() {
     DigitalWrite(latch_pin, LOW);
     for (i = 0; i < 8; i++)  {
         DigitalWrite(data_pin, !!(bits & (1 << i)));
         DigitalWrite(clock_pin, HIGH);
         DigitalWrite(clock_pin, LOW);
     }
     DigitalWrite(latch_pin, HIGH);
 }

For instance, how long is the clock pulse? Does the data signal raise/fall correctly before the clock signal? What is the clock pulse frequency? How is it affected by the RC factor of the wiring.
Given that the signals are within limits you can add micro-second delays to compensate for propagation.
void shift_out() {
     DigitalWrite(latch_pin, LOW);
     for (i = 0; i < 8; i++)  {
         DigitalWrite(data_pin, (bits & (1 << i)));
         delayMicroseconds(T1);
         DigitalWrite(clock_pin, HIGH);
         delayMicroseconds(T2);
         DigitalWrite(clock_pin, LOW);
     }
     DigitalWrite(latch_pin, HIGH);
 }

Cheers!

If nothing else works, consider a RS485 link. Nick Gammons forum has a useful and in depth tutorial on the subject. There is a bit of a hardware penalty - an additional Arduino or some other avr and a couple of RS485 driver chips, which is why I council "if nothing else works" in this case.

Nick posted an answer 2 days ago (from today, fri 23 Dec) also describing this option. This answer seems posted 1 day ago. If you think the same as an answer posted earlier, you can upvote it and if you have anything to add to it (without it being another solution) you can comment and/or edit the question. The problem here is that it's a bit like "spam" if everyone starts posting the same answer. Also, this would mean that votes get spread over good answers and may cause the best answer not to come up on top.


text:
Verify RGB Led Cube equipment
I'm preparing this kit on eBay to create the following instructable - http://www.instructables.com/id/4x4x4-RGB-LED-Cube/
But I have doubts about 0.1uF and 22pF capacitors since the once on eBay are 50v. Also MOSFETs - instructable uses IRF9531 but the ones I found on eBay are IRF9540N.
Is the equipment I added on eBay compatible with instructable?

Capacitor ratings don't really matter in your case, as you are using only 5 volt. Only their values (F) do.
Though the crystal you selected has an indication it needs 20pF load capacitors, not 22pF. 22pF is probably still fine. (Also note the ±20% accuracy, so between 17.6 and 26.4pF)
The IRF9531 and IRF9540N have the same pinout. They are also pretty similar in specs. The IRF9540N is slightly better even.
Note that the ATMega328p doesn't have the bootloader pre-installed. It's not that hard to do yourself though.
The EEPROM you selected is an SMD version. Kind of hard to work with if you are still a beginner. Better use a DIP version instead (that one is a bit more expensive, but 4 times the size)
I'd suggest you add an USB to Serials Adapter to the list, so you don't need the Arduino Uno every time you want to reprogram it, and use the Uno for something more useful.

Thank you very much for the answer, everything is clear now.

For a crystal with 20pF load capacitance you need 40pF capacitors.
The formula used is:

Cx1 = Cx2 = 2(CL - Cpara)

CL is 20pF and Cpara is the parasitic capacitance of the circuitry involved. Under most amateur circumstances that can be ignored.

Possibly that's the reason he uses 22pF capacitor with 20pF crystal, leaving 10% for parasytic capacitance


text:
Board won't show on one of my computers
I have the same problem with these two boards: Ruggeduino (Uno compatible) and DFRobot Romeo 1 (Duemilanove compatible). On one of my Macs (a Macbook Pro running 10.11.4), I can see a new port  /dev/cu.usbmodem641 or /dev/a4005g3t depending on the board. On the other computer (a Mac Mini late 2014), they just won't show. Same cable, same boards, and no hub. I don't know where to look to see an indication of a failure of some sort.
These two ones use a type-b USB socket (printer style)
Also on the Mac Mini that won't see any of those boards, I can connect an EtherMega2560 (Arduino Mega 2560) which happens to use a micro USB socket. I don't know if that is related to the problem.
Both computers run the same OS (OS X 10.11.4) and the latest version of Arduino.
Here is a difference (found in /var/log/system.log):
On the working computer:
Mar  3 22:20:42 pc101 kernel[0]: AppleUSBFTDI: fInBufPool,kMaxInBufPool 8,64
Mar  3 22:20:42 pc101 kernel[0]: AppleUSBFTDI: Version number - 5.0.0, Input buffers 8, Output buffers 16

On the non working one:
cfprefsd[114]: BUG in libdispatch: 15E49a - 1718 - 0x0

..

If OS X has something like dmesg and lsusb (list USB devices) please post the output.

My Ruggeduino stopped showing up as a serial device under El Capitan (10.11.6). I was able to fix this by installing/updating the VCP drivers for Silicon Labs USB devices available here:
https://www.silabs.com/products/mcu/Pages/USBtoUARTBridgeVCPDrivers.aspx
After installing the Mac driver the Ruggeduino shows up as SLAB_USBtoUART and works fine with the Arduino GUI.

That would only help for a board with a silicon labs chip, but the documentation for the Ruggeduino seems to say it uses at ATmega16u for that role.  It's pretty easy to look at a board and read what is on the chip, if it doesn't say SiLabs, this will not help.


text:
Instantiate class in the constructor rather in the top end?
Is there a way to define class variables in the constructor or in a method rather than at the top of the document?
I have the following code in my custom library:
#include "DHT.h"

// DHT settings.
#define DHTPIN 7 // Digital pin connected to the DHT sensor.
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor.

void DhtLib::doSomeStuff() {
  dht.begin();
  float temp = dht.readTemperature();
  ...
}

I would like to be able to set the pins with a function. But for this to work I have to find a way to define the dht variable in a different place than at the top of the document within the // DHT settings.. Best would be in a method such as:
void DhtLib::begin(int dhtPin) {
  DHT dht(dhtPin, DHTTYPE);
}

This works, but only within this function. I need this to be accessible in the entire document, not just a single function.
How can I achieve that?
EDIT 1:
Entire code of the custom DhtLibrary.h file:
#ifndef DhtLibrary_h
#define DhtLibrary_h

#if (ARDUINO >= 100)
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif

class DhtLib {
  private:
    DHT dht;
    float readTemperatureFromDHT();
    float readHumidityFromDHT();
    float calculateHeatIndex(float temperature, float humidity);

  public:
    // Constructor.
    DhtLib(int dhtPin) : dht(dhtPin, DHT22) {}

    // Methods.
    void begin();
    String getHumiTempJson();
};

#endif

The error with this above code is:
In file included from /home/myuser/Documents/Codes/temperature-control/slave2-arduino/slave2-arduino.ino:2:0:
DhtLibrary.h:12:5: error: 'DHT' does not name a type
     DHT dht;

There's numerous ways of doing this. The best is probably to have a DHT object as a class property and set it up with an initializer list:
#include "DHT.h"

class DhtLib {
    private:
        DHT dht;

    public:
        DhtLib(int dhtPin) : dht(dhtPin, DHT22) {}
        void begin();
        void doSomeStuff();
};

void DhtLib::begin() {
    dht.begin();
}

void DhtLib::doSomeStuff() {
    float temp = dht.readTemperature();
}

DhtLib thing(7);

void setup() {
    thing.begin();
}

void loop() {
    thing.doSomeStuff();
}

Thanks for the quick answer! Can you please elaborate the part DhtLib(int dhtPin) : dht(dhtPin, DHT22) {}? I don't quite understand the parts of what it does exactly. Is that still a constructor definition? And don't I have to also declare the DHT dht; from the DhtLibrary.h in the DhtLibrary.cpp file?

That is the "initializer list". Yes it's the constructor. When you construct it passes the variables up to the DHT object you set up in the private section. The DHT dht is declared inside the DhtLib class.

Ok, got it. Well, if I place the DHT dht; in the private: section the compiler is unhappy, giving the error DhtLibrary.h:20:5: error: 'DHT' does not name a type. It expects DHT dht(DHTPIN, DHTTYPE);.

Which library are you using? The one I have here works fine.

I use the DHT sensor library by Adafruit Version 1.3.10.. Which one are you using?

Can you link to it?

Well, the More info link points to this url: https://github.com/adafruit/DHT-sensor-library

Compiles fine for me with that library.

I don't quite get where I would do the error. I put my entire code into the EDIT 1 in my post above. Do you see any error with that?

You have to include the DHT.h library in your header so it knows what a DHT is.

You said that you use another library for the DHT. Which one is it? Is there any particular reason you use a different library for the DHT?

I just happened to have the Grove library on hand that uses DHT.h for the header name, so I just used it. No other reason.

Alright, thanks for the info and for your help!

Say I had another variable that I wanted to take, i.e. DhtLib(int dhtPin, int anotherVariable) : dht(dhtPin, DHT22) {}, how could I make use of it? Having defined private: int privateVariable; in the DhtLibrary.h I tried DhtLib(int dhtPin, int anotherVariable) : dht(dhtPin, DHT22) {privateVariable = anotherVariable}, but I get the error error: 'privateVariable' was not declared in this scope. How can I set privateVariable with anotherVariable?

You would usually just add it to the initializer list: DhtLib(int dhtPin, int anotherVariable) : dht(dhtPin, DHT22), privateVariable(anotherVariable) {}

Ok, so what are the curled-braces for? Is it possible to put logic into them?

Yes, that's just an empty function body where you would put the code for the constructor if you should ever want any.

Do you have any link for a description to this particular syntax?

https://en.cppreference.com/w/cpp/language/constructor

Thanks a lot! You've been a great help!

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


text:
Help making LEDs blink like blinkers in a car
I am trying to make blinkers and hazards lights for a car.  I can get
the left and right blinkers to work. I cannot figure out how to get
the lights to blink simultaneously like hazard lights would.
What I think I want is that when both inputs are HIGH then Both LEDs will
blink together at the same time.
I left the garbage and comments in the code so you can see what I have
tried.
Thanks for your help.
/*
 Blinkers and Hazard Lights

 Simulates a vehicles blinkers and Hazard Lights
 left button connected to pin 2 using a pushdown resister
 right button connected to pin 3 using a pushdown resister
 left LED connected to pin 9
 right LED connected to pin 10
 Hazard LED is Pin 13 At one point I was trying to make pin 13 represent the hazard lights but that is not what I want to do.

 When left button is pushed Left LED will Blink
 When Right Button Is pushed Right LED will Blink

 If this worked the way I wanted it to. when both buttons where HIGH both LED 9 & 10 would blink simultaneously.

 created 2015
 by thomsl41@gmail.com

*/

// constants won't change. They're used here to
// set pin numbers:
const int buttonPinLeft = 2;     // the number of the pushbutton pin
const int buttonPinRight = 3;
const int buttonPinHazard = 2 && 3;
const int ledPinLeft = 9;      // the number of the LED pin
const int ledPinRight = 10;
const int ledPinHazard = 13;

// variables will change:
int buttonStateLeft = 0;         // variable for reading the pushbutton status
int buttonStateRight = 0;
int buttonStateHazard = 0;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPinLeft, OUTPUT);
   pinMode(ledPinRight, OUTPUT);
   pinMode(ledPinHazard, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPinLeft, INPUT);
  pinMode(buttonPinRight, INPUT);
  pinMode(buttonPinHazard, INPUT);
}

void loop(){
  // read the state of the pushbutton value:
  buttonStateLeft = digitalRead(buttonPinLeft);
  buttonStateRight = digitalRead(buttonPinRight);
  buttonStateHazard = digitalRead(buttonPinHazard);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonStateLeft == HIGH) {
    // turn LED on:
  digitalWrite(ledPinLeft, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);              // wait for a second
  digitalWrite(ledPinLeft, LOW);    // turn the LED off by making the voltage LOW
  delay(500);              // wait for a second
  }
 else {
    // turn LED off:
    digitalWrite(ledPinLeft, LOW);
  }

if (buttonStateRight == HIGH) {
    // turn LED on:
  digitalWrite(ledPinRight, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);              // wait for a second
  digitalWrite(ledPinRight, LOW);    // turn the LED off by making the voltage LOW
  delay(500);              // wait for a second

}
  else {
    // turn LED off:
    digitalWrite(ledPinRight, LOW);
  }
}

/*if (buttonStateHazard == HIGH) {
    // turn LED on:
  digitalWrite(ledPinLeft, LOW);
  digitalWrite(ledPinRight, LOW);
  digitalWrite(ledPinHazard, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(2000);              // wait for a second
  digitalWrite(ledPinHazard, LOW);    // turn the LED off by making the voltage LOW
  delay(2000);              // wait for a second
  //}
 //else {
    // turn LED off:
   // digitalWrite(ledPinHazard, LOW);
 }

}
*/

A "state machine" would help here. In a loop where you decide whether or not to turn on the left or right LED, you could turn them both on if you want the hazard flashers. Then a half second later you turn them all off.

It looks like you need to do something like:
if ((buttonStateRight == HIGH) && (buttonStateLeft == HIGH)) {
    digitalWrite(ledPinRight, HIGH);
    digitalWrite(ledPinLeft, HIGH);
}
else if (buttonStateRight == HIGH) {
    digitalWrite(ledPinRight, HIGH);
}
else if (buttonStateLeft == HIGH) {
    digitalWrite(ledPinleft, HIGH);
}
//One delay for all
delay(500);
//Shut anything off that might be on after the delay
digitalWrite(ledPinRight, LOW);
digitalWrite(ledPinLeft, LOW);

Your code is really hard to read but it may mostly be because you need to insert four spaces at the beginning of each line of code to make it look right on this forum.


text:
Arduino: Error: 'PubNub' was not declared in this scope
I'm new to Arduino. When Arduino verifies this sketch https://github.com/MediaTek-Labs/Real-Time-Bicycle-Tracking-Map-using-PubNub throws the following:
Build options changed, rebuilding all
BikeTracker.ino: In function 'void setup()':
BikeTracker.ino:45:5: error: 'PubNub' was not declared in this scope
BikeTracker.ino: In function 'void loop()':
BikeTracker.ino:91:14: error: 'PubNub' was not declared in this scope

I've read most answers are pointing out to www.arduino.cc/en/Guide/Libraries some people say it's common Arduino linking issue (easy to fix) after tried out multiple approaches with no dice.
I've also followed PubNub customer support advice (with list of steps below) but no avail:

OCT 12, 2015  |  10:23AM PDT  PubNub replied: Eduardo,
I got this from our hardware/IoT/embedded engineer:
You are probably not including all the libraries, or has the wrong
  path for them.

When you download the source at
  MediaTek-Labs/Real-Time-Bicycle-Tracking-Map-using-PubNub on GitHub:

Click .ino file and a pop up will ask if you need a new folder for the
  sketch – click Yes.
Then copy the rest of the files from the source to
  this new folder.
Compile it and see if you get any library path errors
  that you need to provide. Let me know if you require further
  assistance.

BTW this is my PubNub.h https://gist.github.com/egomez99/fb1d738ec39913629e9a
Hope someone can shed some lights.

And you're sure you've copied ALL the git files into your sketch folder?

Yes sir, I have.

In BikeTracker.ino, change the reference to PubNub.h to an absolute path.

@CharlieHanson I know you're right. I'm just overlooking something stupid I can't figure it out! lol. This morning tried out to #include <PubNub.h> instead of predefined set up #include "PubNub.h" (as the github repo says). I did also try running this PubNubJsonWiFi PubNub.h already included system directive. When I fixed the #include <../aJson/aJSON.h> library the main issue reappeared (error: 'PubNub' was not declared ...). I'll keep looking at this and post feedback when I have any information. Ty!

It turns out my Arduino IDE could not find PubNub.* files until I manually added them as a Library.


text:
Code for password-activated LED via Bluetooth serial
I have this pretty simple task to light up an LED for 3 seconds when I send the right password from my Android phone to the Arduino via Bluetooth. I am using an HC-05 Bluetooth Module. My LED is connected to Pin 9 of the Arduino I/O. TX and RX of HC-05 is connected to Pins 1 and 0 of Arduino respectively. Here's the code I am using:
int output = 9;         //I will be using to control a DC motor(LED is just for testing).
int output2 = 10;
char final[4];
char correct[4] = {'Q','W','E','R'};
int pass_true;

void setup() {
  pinMode(output, OUTPUT);
  pinMode(output2, OUTPUT);
  Serial.begin(9600);

}

void loop() {
  while(Serial.available()){
    for(int i=0; i<4; i++){
      final[i] = Serial.read();
    }
    for(int i=0; i<4; i++){
      if(final[i]==correct[i]){
        pass_true = 1;
      }
      else{
    pass_true = 0;
    break;
      }
    }
  }

  if(pass_true==1){
    digitalWrite(output, HIGH);
    Serial.println("ON");
    delay(3000);
    pass_true = 0;
  }
  else{
    digitalWrite(output, LOW);
  }

}

I am using Bluetooth SPP Pro Android App to send the 4-byte pass code ("QWER")
The problem is the LED wont light up. I tried replacing the LED thinking that it may be a dead one but it's not. The "TX" LED on the board blinks everytime I press "SEND" in the Bluetooth App, but still Pin 9 doesn't seem to produce the HIGH output at all. Is there a problem with the code?

Read and digest this: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

Please start by verifying that the connection is even working, before trying to parse a message that "should" come in.

Try using the serialLoopback sketch, how can you be sure it is set to 9600 baud anyway?

Try using the following code you need to use String and concatenate that
    String rcev_data="";
bool chk=false;
\#define output 9

\#define output2 10

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

void loop()
{
  // put your main code here, to run repeatedly:
  while(Serial.available())
  {
    char rxx = Serial.read();
    recv.concat(rxx);
    delay(10);
    if (recv == "QWER")
    {
       chk=1;
       break;
     }
    else
     chk=0;
 }

  if (chk)
  {
    digitalWrite(output,HIGH);
    Serial.println("ON");
    delay(3000);
    chk=0;
  }

  else
  {
    digitalWrite(output,LOW);
  }
  recv="";
}

Instead of
while(Serial.available()){

please try
while(Serial.available() >= 4){

Depending on how your transmitting application is buffering the writes, the loop()'s password check may be triggering on a single byte of input each time.
You may also want to make the code a bit more fault-tolerant.  For example what if there's a bit of noise in the line, or the operator pushes [Enter] first before entering the code.  The input buffer will fill up a few characters, then the password will not match because it spans, say input bytes 3,4,5,6.  Maybe throw away any old input based on elapsed time, etc.


text:
Change from using the external crystal to the internal oscillator
BACKGROUND
I have made my own Arduino PCB based on the circuit of the Arduino Pro Mini (below) (including the external oscillator).

I have already written the firmware and the code is stable. The code uses the millis() function which uses Timer 0. I also have changed the frequency of the PWM output on pins 3, 9, 10, 11, using the clock select bits (bits 2:0 in TCCR1B & TCCR2B). See http://playground.arduino.cc/Main/TimerPWMCheatsheet
I have an ISP 6-pin programming port on the board and this is my only method of uploading code.
I want minimize on components (and avoid EMC issues), so I have been considering removing the external 16MHz crystal and instead using the internal 8MHz oscillator.
QUESTIONS

What do I need to change to use the internal oscillator?

I suspect that I need to change the board.txt file, the clock select bits and the fuses to accommodate for the new frequency.

Can I leave the external crystal in place or do I have to remove it?
If I do leave the external crystal in place and set the fuses to use the internal oscillator, will the crystal continue to resonate or does it get powered down somehow?
(I wish to know this for EMC reasons)

Maybe this?? http://www.instructables.com/id/Atmega-Standalone-Running-without-crystal-oscillat/

"internal 8MHz crystal" AVRs don't have one of those. Also, that's not a crystal on that board either.

What do I need to change to use the internal oscillator?

You'll need to change the fuses on the chip, and you probably want a new 8MHz entry in boards.txt so that timing functions still work as expected.

Can I leave the external [resonator] in place or do I have to remove it?
If I do leave the external [resonator] in place and set the fuses to use the internal oscillator, will the [resonator] continue to resonate or does it get powered down somehow?
  (I wish to know this for EMC reasons)

From the datasheet:

If the Internal Calibrated RC Oscillator is used as chip clock source, PB7...6 is used as TOSC2...1 input for the Asynchronous Timer/Counter2 if the AS2 bit in ASSR is set.

Also:

When AS2 is set, pins TOSC1 and TOSC2 are disconnected from Port B. A crystal can then be connected between the TOSC1 and TOSC2 pins to serve as an
  independent clock source for Timer/Counter2. The Oscillator is optimized for use with a 32.768kHz crystal.

Therefore if AS2 is not set, the two pins act as normal GPIOs and the resonator is disabled.


text:
Temperature Controlled fan using arduino project regarding - LCD not displaying anything
I have connected the circuit as per the diagram below and I have got the LCD to display boxes and nothing else. What could be wrong here? Please help!
Circuit diagram below -

Code as follows -
#include<DHT11.h>
#include<LiquidCrystal.h>
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
#define dht11pin 12
dht11 DHT11;
#define pwm 9
byte degree[8] =
{
  0b00011,
  0b00011,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000
};
void setup()
{
  lcd.begin(16, 2);
  lcd.createChar(1, degree);
  lcd.clear();
  lcd.print("   Fan Speed  ");
  lcd.setCursor(0, 1);
  lcd.print("  Controlling ");
  delay(2000);
  analogWrite(pwm, 255);
  lcd.clear();
  lcd.print("Our Project ");
  delay(2000);
}

void loop()
{
  DHT11.read(dht11pin);
  int temp = DHT11.temperature;
  lcd.setCursor(0, 0);
  lcd.print("Temperature:");
  lcd.print(temp);
  lcd.write(1);
  lcd.print("C");
  lcd.setCursor(0, 1);
  if (temp < 26 )
  {
    analogWrite(9, 0);
    lcd.print("Fan OFF  ");
    delay(100);
  }
  else if (temp == 26)
  {
    analogWrite(pwm, 51);
    lcd.print("Fan Speed: 20%   ");
    delay(100);
  }
  else if (temp == 27)
  {
    analogWrite(pwm, 102);
    lcd.print("Fan Speed: 40%   ");
    delay(100);
  }
  else if (temp == 28)
  {
    analogWrite(pwm, 153);
    lcd.print("Fan Speed: 60%   ");
    delay(100);
  }
  else if (temp == 29)
  {
    analogWrite(pwm, 204);
    lcd.print("Fan Speed: 80%    ");
    delay(100);
  }
  else if (temp > 29)
  {
    analogWrite(pwm, 255);
    lcd.print("Fan Speed: 100%   ");
    delay(100);
  }
  delay(3000);
}

I used the default LiquidCrystal.h library for this project. Is that wrong?

The boxes on the display is either a contrast problem or a wrong wire. Keep only the display connected to the Arduino Uno, and remove everything else. Use a sketch that only uses the display. How do you control the contrast ? Compare your project with one of the examples: https://www.arduino.cc/en/Reference/LiquidCrystal

Your constructor doesn't match your wiring:
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

You have:
RS = 7
E = 6
D4 = 5
D5 = 4
D6 = 3
D7 = 2

Yet your wiring has:
RS = 2
E = 3
D4 = 4
D5 = 5
D6 = 6
D7 = 7

I.e., completely backwards.
The constructor prototype is:
LiquidCrystal(rs, enable, d4, d5, d6, d7)

Yet you seem to have chosen to ignore (or misunderstand) that.
Instead you need to specify your pins correctly:
LiquidCrystal(2, 3, 4, 5, 6, 7);

Also, as a side note, you don't have a ground connection to that little 9V circuit off to one side - so you will never be able to control it.  Read this.


text:
Trying to flash ATTiny85 bootloader using FT232R in the Arduino IDE
I have a FT232R that I want to use to flash my ATTiny85 bootloader in the Arduino IDE, can someone help me out on this? I don't want to get a AVR programmer.

This is certainly possible but it's very inconvenient and not commonly done. It's much better to buy a cheap 6 pin USBasp clone off eBay or use another Arduino board as an "Arduino as ISP" programmer. It's possible because the FT232 has a bit bang mode but it's very slow. You can find instructions here: https://learn.adafruit.com/ftdi-friend/programming-the-arduino-bootloader, you just need to adapt the instructions to the ATtiny85 (SPI connections and board selection). I've never done this so I'm not going to write an answer but if you are successful please answer your own question.

It's also not very common to use a bootloader on the ATtiny85 due to the limited flash memory. Usually you will upload sketches to the ATtiny85 using an ISP programmer. For that usage the FT232 is even more inconvenient because it's so slow and you will typically upload more often than you would burn a bootloader.

A bootloader is a program that gets loaded into the bare microcontroller to handle a number of low level tasks. One of those tasks is the ability to load a program over UART (serial).
As such, the bootloader can be loaded into the microcontroller using a AVR programmer. Once this has occurred, you can then easily load in programs with the FT232R.
It is possible to use the bitbang mode on the FT232R to load the bootloader into an Arduino board, hence replacing the AVR programmer. So, it can work but it isn't easy.
As suggested by per1234, there is some instructions on how to do this to an Arduino Diecimila on the Adafruit website: Programming the Arduino Bootloader
In general the full page has a lot of useful information: Full page

Sorry for a late reply!, but can't you run the FT232R in bitbang mode?

@sa_leinad ... "I am sorry to say that what you are trying won't work." ... no, you can bitbang the FTDI and mimic an ISP programmer that way.

@yeti & Pepperrika, You are both correct. However this requires a certain level of expertise. Beginners especially won't be able to do this. However, if a beginner had a ISP then a beginner could easily program the bootloader into the ATTiny85 using the Arduino IDE.

So you agree that "... that ... won't work." is a false statement. And we all had missing expertise on nearly all topics somewhen in the past.
Well... wiring up a FTDI module probably is not more difficult than wiring up an ISP... and avrdude supports them, so it will not be rocket science.
I agree that having an ISP is the easiest way to go but @Pepperrika asked about it being doable with a FTDI and to this the answer only can be: YES!

@yeti, why don't you post your own answer if you have such a problem with mine. I've edited my answer - upvote it if you think it is now worthy.


text:
Arduino digitalWrite not working
I am trying to control this OWI Robotic Arm using the Arduino's digital outputs (I am using pins 12 & 13).
If I wire up the wires to ground and 5V it goes one way, if I switch the wires, it goes the other way. However when I have the pins wired up to the digital pins, it does not work, but the on-board LED does blink.
The code:
int a = 12;
int b = 13;

void setup() {
  // put your setup code here, to run once:
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  //up
  digitalWrite(a, LOW);
  digitalWrite(b, HIGH);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(500);
  //down
  digitalWrite(b, LOW);
  digitalWrite(a, HIGH);
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
}

Why do you think that the pins can supply anywhere near what current the arm requires?

Honestly, I have no idea what I am doing, but I assume the pins can be as powerful as the 5V pin on the Arduino, and that was enough to drive the motor.

Do the datasheet and specifications back up your assumptions?

Assumption IS the mother of all screw ups.  In this business you NEVER assume.  You read and check and find out.  You may have burned up your Arduino by now.

The problem you are seeing here is that the Arduino can provide nowhere near as much current through I/O pins as it can power. Quoting from the Arduino website:

DC Current per I/O Pin: 40 mA

This means that each pin can power maybe a couple of LEDs, and that's it. Additionally, motors provide "back-EMF": When opening (cutting power) an inductive load (e.g. a motor), the current wants to keep going. This will damage whatever just opened unless protection is used. So, I wouldn't be surprised if you damaged your Arduino by attempting to drive a motor with it.
So, what can you do? Use an H-Bridge. This circuit will allow you to easily control a motor & its direction. Many circuits can be found online, but an easy solution is a cheap L298N module, which can be as cheap as $3 a piece. This will safely & easily control the arm. Connecting your Arduino with the following circuit & using your existing sketch will make it work.

simulate this circuit – Schematic created using CircuitLab


text:
How to upload a sketch to an atmega328 via FTDI FT232RL UART and Arduino IDE?
I have a sparkfun AVR Pocket Programmer and have burned the bootloader and uploaded programs using "upload using programmer" via USBtinyISP. It works fantastic.
I have a sparkfun FTDI Basic (as well as another FTDI breakout) that can send and receive bytes via the Arduino IDE serial monitor.
However, I cannot upload a new sketch or modified sketch to the atmega328 via FTDI. The IDE just hangs at the upload till timeout. Here is the list of some of my troubleshooting attempts:

I have tried uploading a plain bootloader, as well as a running program via the ISP programmer before attempting the FTDI.
I have tried direct connecting the FTDI DTR/RTS reset to the Atmega328 pin1.
I have also tried connecting the FTDI DTR/RTS reset to a one side of a 0.1uF cap, and the other side of the cap to the Atmega328 pin1. I assume the cap is to send just a reset pulse instead of a reset constant.
I have tried a different brand of FTDI FT232RL chip. No difference.
I have tried adding 1k resistors on the Tx and Rx lines. No difference.

Being able to program over serial is really the secret sauce that makes Arduino so much easier for beginners than a stock AVR chip. However, I have not been able to locate any detailed information on how this Arduino programming via serial really works. Also, I am not sure how the reset pin works in relation to this process. I remember something that on old Arduino boards you had to press or hold the reset when uploading, but have not be able to find any of this information either as it has been buried by time.
This Building an Arduino on a Breadboard Article and photo from that article below is a good outline of the setup I have right now. But in this configuration it seems that a sketch can not be uploaded. What do I need to add breadboard circuit in order to upload a sketch via serial? Or what procedure do I need to do with the reset button when uploading?

Thanks!
Atmega328 Spec Sheet PDF

Instead of showing a picture of what you attempted, you should show us a picture of what you have actually done.

Your first link in fact provided all the information you need. By default, Atmega328 only support programming via ISP (which is an SPI interface), in order to serial boot loading, you need to upload the bootloader to the chip first. There are plenty of information available on the internet or even on the first link you provided on how to burn a bootloader to Atmega328. For programming via serial, you need the DTR connect RST via a cap, take a look at Pro Mini schematic.

@hcheung, Thanks! I had just figured it out when you posted your comment, but you were right on! Thanks!

@Majenko, I posted my actual breadboards in the answer. Thanks!

Answering my own question; I just got lost in the troubleshooting.

Though I tested it both ways, I evidently overlapped issues, masking the core problem. Upload using programmer works great for transferring your sketch but it does NOT allow sketches to be uploaded via serial later. (Not sure if there is an inherent or logical reason for this, but this is what I have found by experimentation).
And like hcheung mentioned in the comments, a capacitor on the FTDI reset line is required. Connecting it directly will NOT work. I used a 0.1uF and it worked well. I have attached a couple different photos of my setup for someone following this path in the future. Note that the LED I am using has an internal resistor; a normal LED will need an 1k series resistor. Also, leaving the ISP programmer attached while uploading a sketch over serial did not seem to cause any issues.