text:
FTDI Breakout with additional ISP connector
TL;DR - Can the six yellow ISP pins be used as a normal ISP?

The usual USB-TTL FTDI breakout board looks like this:

Recently, I came across a variant of the board shown below. However, what are the additional yellow header pins on this board for? They are labelled ISP.

Here is a view of the rear:

So can they really be used as a standard ISP/ICSP?

However, according to the diagram below, which labels the 6 pins in question, I am not sure that there is a valid correlation of signal lines.

That is to say, would CTS to MISO, RI to RST, DSR to SCK and DCD to MOSI work? Or is that why a special version of avrdude is required, as alluded to in FT232RL: USB to Serial 232 TTL Adapter –?and ISP? - post #6:

As a new feature there is a 6-pin ISP header available. With it, avrdude and avrftdi you can program Atmels and Arduino bootloaders. A special version of avrdude with compiled FTDI driver is neccessary.

However the provided link to that version of avrdude, with the compiled FTDI driver, is dead.
It is also said, in post #7, that these pins are actually equivalent to an X3 connector, as found on the older Arduino Dicimila/NG/Duemilanove boards.

and those can (evidently) be used like so, as a bit banged SPI,

It should be noted that the RI, CTS, DCD and DSR (labelled RSD) pins are available, along the sides of the original FTDI breakout board. So, does the breakout board with the ISP header just provide access to these same signals using a different header?
I am a little confused - have I just over thought this, and this breakout board is simply an ISP/ICSP header and an FTDI connector rolled into one board (when used with the appropriate version of avrdude)? Or is it not a usual ISP header? I can not find any specific documentation relating to this type of breakout board, as stated in post #4.
Can anyone say, definitively, what these six pins are for? If they are not a normal ISP header, could you provide a detailed way of using it? A schematic would be helpful.

I have the same product, did you figure out how to get 3.3V? The output is fixed on 5V and the switch seems to be useless.

@TeoMaragakis - No sorry, I don't think that I ever tried, and I'm not even sure if I still have it (not used it for a long time). Try checking the switch's solder points (with a DMM) for a bad contact. Try spraying contact cleaner onto (into) the switch. Check the PCB traces to and from the switch for a broken trace (again with a DMM set on continuity mode). Worst case scenario, you could desolder the broken switch and either solder in a replacement switch or put in some header pins to manually link yourself (with a jumper link or jumper cables)

There's a thread about that on the Arduino Forum - someone had a similar question.

I found a schematic (below) which is not for that board, however the header pins are labelled the same as you found, so it is plausibly similar.

It appears that header is used for "Synchronous Bit Bang mode" as documented here: Bit Bang Modes For The FT232R and FT245R (Application Note AN_232R-01, Document Reference No.: FT_000339)

You can in fact configure that header to be an SPI programmer, as described for example, in FT232R Bitbang Programmer.

I made up a test as I had a similar board in my parts drawer:

It had provision for a 6-pin header similar to yours. Turning the board over we can see that they were labelled exactly the same as yours:

I soldered on a header (in yellow, to be consistent) giving me this:

I added a white dot to indicate pin 1 (visible on the edge) so I plug the cable in the right way around.

When I attempted to use the board I got this message from avrdude:

avrdude: error: no libftdi or libusb support. Install libftdi1/libusb-1.0 or libftdi/libusb and run configure/make again

So, it had to be compiled from scratch! I am using Ubuntu 14.04 if you are trying to follow along. :)

Download avrdude
Go to the site http://www.nongnu.org/avrdude/
I downloaded version 6.3 source: http://download.savannah.gnu.org/releases/avrdude/avrdude-6.3.tar.gz
Install libusb and libftdi
Before compiling I had to grab libusb and libftdi:
sudo apt-get install libusb-1.0-0-dev
sudo apt-get install libftdi-dev

Compile avrdude
Now we make avrdude after extracting the archive and navigating to its folder:
./configure --enable-libusb --enable-libftdi
make

Find correct configuration
Inside the avrdude.conf file which comes with avrdude I found (after some pondering) this seems to be the correct entry:
# see http://www.geocities.jp/arduino_diecimila/bootloader/index_en.html
# Note: pins are numbered from 1!
programmer
  id    = "arduino-ft232r";
  desc  = "Arduino: FT232R connected to ISP";
  type  = "ftdi_syncbb";
  connection_type = usb;
  miso  = 3;  # CTS X3(1)
  sck   = 5;  # DSR X3(2)
  mosi  = 6;  # DCD X3(3)
  reset = 7;  # RI  X3(4)
;

The mapping of pins to numbers works like this... From the PDF about bit bang mode mentioned above we have this table, with annotations in blue by me:

The numbers refer to the bit number (i.e. in the range 0 to 7) in the "bit banged" data byte. We can see from the earlier schematic that, for example, MISO on the ICSP header is wired to CTS on the FT232RL. Thus MISO is data bit 3, which we tell avrdude in the above configuration. Similarly SCK is data bit 5, and so on.
I attempted to test like this:
./avrdude -C avrdude.conf -carduino-ft232r -pm328p  -v

Fix permissions
I got a permissions error which was fixed by creating a file in the folder /etc/udev/rules.d/ called 71-FTDI.rules. Inside this is:
SUBSYSTEMS=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", MODE:="0666"

The numbers may vary for your board. You need to find the vendor and product ID. In Ubuntu you can do lsusb and see (amongst other things):
Bus 003 Device 061: ID 0403:6001 Future Technology Devices International, Ltd FT232 Serial (UART) IC
                       ^^^^ ^^^^

Note the two hex numbers, which get copied into the rules file.
After doing that, tell the system to reload the rules:
sudo udevadm control --reload-rules

Then unplug and replug the FTDI board to get it to notice the new permissions.
Test board detection
Finally, the avrdude line above works and reads the chip:
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: safemode: hfuse reads as DE
avrdude: safemode: efuse reads as FD

avrdude: safemode: hfuse reads as DE
avrdude: safemode: efuse reads as FD
avrdude: safemode: Fuses OK (E:FD, H:DE, L:FF)

avrdude done.  Thank you.

I had mine plugged into an ATmega328P.

Example connected to a Diavolino

Once we have got this far you just connect the FTDI board to your target board with a straight-through cable.

Summary
The FTDI board you have (and the one I have) can be used as a ICSP programmer for the AVR chips, as described above. Thus a simple board can be both a USB to serial converter, and also an ICSP programmer.
I see similar boards selling on eBay for around $5 so that is probably quite a cheap programming option.

Thanks Nick. Yes, that thread on the Arduino forums is the one that I referenced in my question, but it wasn't really clear as to how to use it - but it usefully pointed to the X3 header blog. The second link you provide seems to expand upon that topic even further, excellent, thanks. However, there still isn't any blog specifically written for this particular board, which is odd.

I believe that if you do this, you would be talking to the FTDI as a USB device and no longer using the operating system's serial port API, so there may be additional setup/driver/permission issues depending on what system one is using to host it.  FTDI's more capable FT4232H/FT2232H/FT232H parts are often used this way as JTAG interfaces to more advanced processors.

See amended answer. I got my board to work as an ICSP programmer.

Fantastic, great work. That is the documentation that I was after.

would it be possible to repeat the experiment in windows? I find it a very interesting topic

Yes, basically the same development files are part of the IDE downloaded for Windows.

Arduino IDE:
Additional programmers.txt entries to use  "FT232R as ISP"
ftdi232rasisp.name=FT232R as ISP
ftdi232rasisp.communication=usb
ftdi232rasisp.protocol=arduino-ft232r
ftdi232rasisp.program.tool=avrdude
ftdi232rasisp.program.extra_params=

avrdude.exe with FTDI bitbang support
https://github.com/mariusgreuel/avrdude


text:
Which Timer can I use to control a servo with Arduino Uno

I would like to control 2 motors using Timer2 @ 200Hz. The frequency of the timer is printed in the main loop every second. I'm using an Arduino Uno with two interrupt used for the encoders connected to pin 2 and 3.
The problem
The timer runs at 200Hz as expected but the motors are shaking even if I ask them not to spin. The Timer2 is not required by the servo library.
How can I solve this problem? How do you handle Timer interrupts and servo routines?
CODE
#include <Servo.h>
Servo motorDx, motorSx;
[...]

void setup()
{
  // Setup Timer2 @ 200Hz
  cli(); // Stops interrupts

  TCCR2A = 0;// set entire TCCR1A register to 0
  TCCR2B = 0;// same for TCCR1B

  // set compare match register for 200 Hz increments
  OCR2A = 77;// = (16*10^6) / (200*1024) - 1 -> 200 Hz

  // turn on CTC mode
  TCCR2A |= (1 << WGM21);
  // Set CS10 and CS12 bits for 1024 prescaler
  TCCR2B |= (1 << CS20) | (1 << CS21) | (1 << CS22);
  // enable timer compare interrupt
  TIMSK2 |= (1 << OCIE2A);

  sei(); //enable global interrupts

  attachInterrupt(0, MSencVel, RISING);
  attachInterrupt(1, MDencoder, RISING);
  motorDx.attach(10, 1000, 2000);
  motorSx.attach(11, 1000, 2000);
}

void loop()
{
  if(micros()-tOld >= 50000)
  {
    tOld = micros();
    count += 1;
    if(count >= 20) // Runs @ 1 Hz
    {
      count = 0;
      serialRoutine();
      // prints number of ISR/sec
      Serial.println(contIsr)
      contIsr=0;
    }
  }
}

ISR(TIMER2_COMPA_vect)
{
  //sendValuesToMotors();
  motorDX.write(90);
  contIsr++;
}

What motors exactly are you attempting to control?

DC motors with a fully working H bridge.

Don't H-bridges just use steady state or PWM signals? servo uses its own interrupts to generate the PPM signal used by hobby servos, ESC's, and RC radios.

source: Stack Exchange

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

sort: votes


text:
Change select pin of USB Host library
TL;DR
With regards to the USB host library:

Which is the correct file to modify the Arduino pin used for the USB Host slave select (SS) line?

I would like to add USB host functionality, to a particular Arduino setup, whilst, also, being able to use an Ethernet/SD (or just SD) shield.
As both the Ethernet shield and USB Host shield use pin 10 to select the W5500 and MAX3421E respectively1, obviously I can not use a standard USB Host shield. However, I could employ one of the small form factor boards, such as the USB Host Shield 2.0 Arduino UNO MEGA ADK Compatible Google Android ADK which I found on eBay:

As this board is not in the usual shield "shape", one would not be constrained by which pin to connected to which MAX3421E input/output, in particular the chip select (SS) input. So, one could use a pin (or pins) that is not reserved by the Ethernet shield.
However, it does not appear to be possible to simply specify the "select pin" (i.e. the Arduino pin connected to the SS line) when using the USB Host shield library (or any of the pins used by the library), in setup().
Therefore, I wondered if it was possible to modify the library, so that the pin used to select the USB/MAX3421E could be changed, either by:

"Hardcoding" a different "select" pin number into a header file;
Adding an argument to the Init() method, or;
Adding a method to the USB class, such as Usb.DefineSelect().

The latter two options, I could work through, given the time. However, as a quick and dirty hack, where would I hardcode in a change from pin 10 to a pin of my choosing? Does anyone know? Has anyone had to do this?

Nitty-gritty
I have had a look through the library to see where pin 10 is defined as the chip select, and avrpins.h looked like a possible candidate for modification, although it would be rather "rude" (for want of a better word) and probably mess up the other boards.
usbhost.h seems a much better proposition. Looking at usbhost.h, the lines 88-91:
#if defined(__AVR_ATmega1280__) || (__AVR_ATmega2560__) || defined(__AVR_ATmega32U4__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
typedef SPi< Pb1, Pb2, Pb3, Pb0 > spi;
#elif  defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
typedef SPi< Pb5, Pb3, Pb4, Pb2 > spi;

Looking at the statement
typedef SPi< Pb5, Pb3, Pb4, Pb2 > spi;

the last argument appears to be the pin used for select. For the Uno (ATmega328P), in avrpins.h (line 535) Pb2 is P10 (pin 10), so I could substitute Pb2 for some other pin definition, i.e. Pd5 for P5 (pin 5) (line 529 in avrpins.h).
However, what I don't understand is that for the statement
typedef SPi< Pb1, Pb2, Pb3, Pb0 > spi;

which deals with the Mega (ATmega2560), in avrpins.h (line 512) Pb0is P53 (pin 53). As Pb4 is actually P10 (pin 10) (line 466), why is Pb0 en lieu of Pb4 used? That doesn't tie up with the fact that Pin 10 is used for both the Uno and Mega boards. It seems to suggest the pin 10 is used on the Uno and pin 53 is used on the Mega. Unless I have misinterpreted the typedef.

Footnote
1 For the USB host shield, from Arduino USB Host Shield

Arduino communicates with the MAX3421E using the SPI bus (through the
ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno
and pins 10, 50, 51, and 52 on the Mega. On both boards, pin 10 is
used to select the MAX3421E. Pins 7, 8 and 9 are used for GPX, INT and
RES pins.

The key piece of information here is that pin 10 is used by both the Uno and Mega boards.
For the Ethernet shield, from Arduino Ethernet Shield V2

Arduino communicates with both the W5500 and SD card using the SPI bus
(through the ICSP header). This is on digital pins 10, 11, 12, and 13
on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10
is used to select the W5500 and pin 4 for the SD card. These pins
cannot be used for general I/O. On the Mega, the hardware SS pin, 53,
is not used to select either the W5500 or the SD card, but it must be
kept as an output or the SPI interface won't work.
Note that because the W5500 and SD card share the SPI bus, only one at
a time can be active. If you are using both peripherals in your
program, this should be taken care of by the corresponding libraries.
If you're not using one of the peripherals in your program, however,
you'll need to explicitly deselect it. To do this with the SD card,
set pin 4 as an output and write a high to it. For the W5500, set
digital pin 10 as a high output.

Here, yet again, the key piece of information here is that pin 10 is used by both the Uno and Mega boards to select the Ethernet.

It look like you are correct, and that you should edit the usbhost.h file.  Not sure what you mean in the second question. The library uses the Arduinos SS pin. It does have to use this pin, but this prevents the pin from being an input and accidentally putting the atmega into SPI slave mode. The library also prefers to have all the pins on Port B.

@Gerben - Thanks for the confirmation of the first question. I have edited my post to try to clarify what my second question is, which is "shouldn't the last argument to the typedef for the Mega board be Pb4 and not Pb0?" Maybe I need to recheck my understanding of the code, in the morning.

Trying to put both an Ethernet adapter and USB host adapter on an ATmega based Arduino is evidence of bad hardware selection.  You should probably either consider something that does both natively (for example some of the STM32F4's, and likely choices from other vendors) or unless your needs are very narrow and never expected to change, more likely a more sophisticated system capable of running an actual operating system.

Like I said, pin PB0 is the SS of the ATMega. When using SPI you shouldn't use this pin as an INPUT. It's therefor a good idea of the library maker to choose that pin, so it's always an OUTPUT. Also pin 53 is close to the other SPI pins. Using pin 5 would be at the other side of the board, which make wiring messy pretty quick. No big reason to choose PB0, just a few small reasons.

@Gerben - Thanks for pointing me in the right direction. At first I couldn't understand what you meant, but after re-reading SPI library, I see that the source of my confusion is that P53 (Mega) and P10 (Uno) are the Arduino's SS pin, which obviously must be set as an output, to maintain them as the SPI master. I was looking for the point in the code where pin 10 is set to select the USB shield's SS line, not the Arduino's SS line, if that makes sense... So the typedefs that I found in usbhost.h are not what I should be looking at.

@Gerben - After trawling most of the source files, I have found the point where P10 is set as the USB SS line. It is, in fact, at line 43 in UsbCore.h. It seems at bit ruthless to modify this file, but that is where the change needs to be made. See my posted answer.

I don't get it. The Arduino has a SS pin, but you can ignore this if you aren't using the the Arduino as an SPI slave. If you don't use the Arduino as a slave, the SS pin is just a regular input/output pin.

@Gerben - I think that we have our wires crossed, so to speak... :-) My answer below will hopefully clarify what I mean. If not, then I will need to reword my answer. The Arduino is the SPI Master, and the small USB host device, that I show in my question, will be the SPI slave. With my suggested modification to the code, Pin 5 would go to the USB Host SS line and then there would be no conflict with the Ethernet board that uses Pin 10 for its SS line.

In order to change the Arduino pin used to select the USB Host board, in order words, where the device's SS line is assigned to an Arduino pin (with the Arduino as the SPI Master and the USB host is the SPI slave), the line to change is at line 43 in UsbCore.h:
typedef MAX3421e<P10, P9> MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo, Due etc.), Intel Edison, Intel Galileo 2 or Teensy 2.0 and 3.x

So to use pin 5, for example, en lieu of pin 10, the line would become:
typedef MAX3421e<P5, P9> MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo, Due etc.), Intel Edison, Intel Galileo 2 or Teensy 2.0 and 3.x

The clue was in the comment on line 27 in UsbCore.h
/* shield pins. First parameter - SS pin, second parameter - INT pin */

With this suggested modification to the code, Pin 5 would go to the USB Host SS line and then there would be no conflict with the Ethernet board that uses Pin 10 for its SS line.

This issue, I have subsequently discovered, is covered by the USB Host Shield Hardware Manual, under the Interface modifications section. I guess I should have just read the manual first! RTFM...

Clarification of the issue
I must be honest that my question was somewhat confused. After having read the SPI library, it states that

Note about Slave Select (SS) pin on AVR based boards
All AVR based boards have an SS pin that is useful when they act as a
  slave controlled by an external master. Since this library supports
  only master mode, this pin should be set always as OUTPUT otherwise
  the SPI interface could be put automatically into slave mode by
  hardware, rendering the library inoperative.
It is, however, possible to use any pin as the Slave Select (SS) for
  the devices. For example, the Arduino Ethernet shield uses pin 4 to
  control the SPI connection to the on-board SD card, and pin 10 to
  control the connection to the Ethernet controller.

With respect to the first paragraph, the Uno uses pin 10 and Mega uses pin 53 as the Arduino SS line - so that must be set as an output in order for the Arduino to be the Master. Are realising this as being my source of confusion, it became apparent that the typedef statements, in usbhost.h, were not where I should have been looking to change the device's Slave Select pin.
With respect to the second paragraph,  I want to use pin 5 (for example) to control the Slave Select (SS) for the USB Host device, instead of the default pin 10.

The link seems to have died and this google site search finds nothing seemingly related

See section Interface modifications in the USB Host Shield Hardware Manual. Address updated.

So, it is the same link as was in my answer?

Yes, that is the only surviving link I can find. It is linked from the README of the library repo on GitHub.

Ah, ok. Thats a shame. I never got around to seeing the original link that you posted. I wonder if it was dramatically different.

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

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


text:
Computer to multiple arduino bluetooth modules
Im going to take part in a competition called IEEE Very Small Soccer and I need to set up a communication between my computer, that will run visual and strategy algorithms, and send some commands to 3 Arduinos, which will be the players. Most people use the Xbee module to send data to the Arduinos, so I was wondering why not use the Bluetooth module instead, once it is so much cheaper and the difference in power consumption isn't so big, the only drawback would be the working range, which is 10m, if Im correct... However, if the distance is really 10m, not 5m It will be ok, because the computer is always close to the robots.
Summing up, my questions are:

Can I use a computer to send data to 3 Arduinos at the same time?
What is the real working range of the Bluetooth module?
Any suggestions or tips? =D

?

yes, you can, this is what happens normally in a crowded area where multiple people use their phones with bluetooth headsets, for example.
if you believe the claims typical 10m max 100m but in practice there are a number of factors:

Quality of the HW design of the antennas
Signal to noise ratio due to other radios operating in the same area
Obstacles in the path
Responsiveness and throughput required by your application
etc.

you could consider other options, like this module, which is basically the same, from the perspective of transferring data. Also wifi could work, if you are allowed to setup your own access point.


text:
PROGMEM on Arduino Due (ARM Cortex M3)
I've been working with the PROGMEM function on my Arduino Uno and I'm thinking about changing to the bigger Arduino Due which is based on a ARM Cortex M3 processor instead of the AVR processor on the Uno.
The Arduino Reference now says:

PROGMEM is part of the pgmspace.h library that is available in the AVR architecture only.

My question now is: Is it possible to store constants in program memory instead of flash on the Due?
If found this post on the Arduino forums, suggesting that this is done automatically. Does anyone know something about that?
EDIT: Arduino IDE doesn't give stats about RAM usage after compiling, so I can't just try.

I guess you have already looked at the source code for the Arduno-SAM core. There is a port of the AVR program memory functions (pgmspace.h); https://github.com/arduino/ArduinoCore-sam/blob/master/cores/arduino/avr/pgmspace.h. The actual answer is that const data is stored in the program flash and loaded to RAM by the program startup code.

Thank you @MikaelPatel. But doesn't that dissent from what Majenko wrote in his answer?

@MikaelPatel That's not a port of them - that's creating aliases for them for backwards compatibility. It just removes all _P suffixes and ignores all PROGMEM, etc.

@Majenko "port" ;)

There is no PROGMEM required on ARM. There is no memory bus separation between Flash and RAM, so it doesn't copy constants from flash to RAM which PROGMEM is used to prevent.


text:
Space needed for local String variable
I tried to run this code on my Arduino Uno clone (which has no function so far and is a shortend version of my programm):
String rules [16][5] ={
   {"B0 B5", "", "", "cs S0", "", },
   [...]
};

void setup() {
  Serial.begin(9600);
  String foo = "bar";
  Serial.println(foo);
}

void loop() {
}

I left the rules array out, but it is quite big. It isn't used yet, but it contains rules how to react on certain situations (which should be used later).
As the Arduino IDE gives the following after complilig:
Sketch uses 4316 bytes (13%) of program storage space. Maximum is 32256 bytes.
Global variables use 1174 bytes (57%) of dynamic memory, leaving 874 bytes for local variables. Maximum is 2048 bytes.

When I run this sketch there is nothing on the serial monitor. If it works, there should appear bar, but it does not. The Arduino sends only a linebreak over the serial, but no text.
When I remove some characters from that array so that there are about 900 bytes the script works and prints bar to the serial monitor.
So, aren't 874 bytes not enough to store a three-character string? Why does it need 900 bytes to store such a short string?

Because String instances are more than just their characters.

You are requesting 80 String objects.
Each String object allocates memory to store its data. When you provide a string constant that string constant data's length is used for the allocated data size (including the NULL character at the end), and the string constant data copied in.
On top of that you have a bunch of other data that is needed for the String class to do its work. The total size of a String object is 6 bytes.
So the memory you need for your array of Strings can be calculated as:

Let C be the total number of characters in all the string constants
Let N be the number of String objects in the array
Let T be the total number of bytes.
T = N * 6 + C + N

With no string constant data that would be:
T = 80 * 6 + 80

That's 560 bytes already, before you even start thinking about putting in the string constant data.
Also you may like to add to that the fact that the compiler may (though I am not certain on this) be also copying the string constants into RAM first because they aren't forced into PROGMEM with the F() macro.
So since you only have 2KiB of RAM to begin with, and a quarter of that is instantly gobbled up with your array, you can see how things might not be too happy.
Oh, and the String's internal storage is allocated at run time, not compile time, so the compiler can't know that it'll overflow - only when you run the program will it overflow and things go horribly wrong.
So you need to ask yourself "Why do I even want an array of String objects?" and the answer is most certainly: "Under no circumstances do you ever want an array of String objects". In fact I am a strong advocate of never using String objects ever, for any reason whatsoever.
If your data is constant there is absolutely no reason to store it as String objects. It's constant. It should remain constant. Copying it into a String object means it's no longer constant and wastes many many resources.

fwiw, i find the String interface to result in much more semantic and readable code ex: response.endsWith(token) compared to gibberish-ladden alternatives. my $0.02 as a JS dev.

Thank you. One Mord question: Would it be possible to use char arrays instead of String objects (as I don't really need their functionality). Would that (if possible) save space?

Absolutely. If they are constants then you need to learn about PROGMEM, the F() macro, PSTR, etc.

Would declaring the array with char[][16][5] also work?

That would probably end up wasting as much memory. First decide what you want this array to do. Then relate that to what different types of array can do. Then code using that kind of array.


text:
Max length of char arrays?
I'm running the following Sketch on my Arduino Uno:
const boolean verbose = true;

void debug(const char *s){
    if(verbose){
      char buf[8 + sizeof(s)] = "[DEBUG] ";
      strcat(buf, s);
      Serial.println(buf);
   }
}

void setup() {
  Serial.begin(115200);
  char str[] = "Lorem ipsum dolor sit amet, consetetur sad";

  Serial.print("Size of String: ");
  Serial.println(sizeof(str));
  debug(str);
}

void loop() {
}

The debug() function should be used to print debugging information to Serial. The Sketch like I posted it works wuite fine and prints the following to Serial:
    Size of String: 43
    [DEBUG] Lorem ipsum dolor sit amet, consetetur sad
But when I add one more character to the string (43 chars excluding null terminator) I get the only follwoing on Serial:
Size

This problem does not appaer when defining str as a global varaible. What does cause this issue and how can it be fixed?

The main issue with your code is:
sizeof(s)

That doesn't return the string length - it returns the size of the char pointer - which is two bytes (on an 8-bit system, 4 on a 32-bit system).
Instead you need to use strlen(s) and add one to it for the NULL character at the end.
if(verbose){
  char buf[8 + strlen(s) + 1] = "[DEBUG] ";
  strcat(buf, s);
  Serial.println(buf);
}

However, what you are doing is pointless. Just print twice:
if(verbose){
  Serial.print(F("[DEBUG] "));
  Serial.println(s);
}

Note the use of the F() macro to ensure that [DEBUG] doesn't waste RAM.

sizeof(s) does not do what you thing it does. All it does is take the sizeof of the pointer.
So you end up with Undefined Behavior when you concatenate the strings which means than anything is allowed to happen.
Instead you can do 2 print statements to concat on the serial stream:
void debug(const char *s){
    if(verbose){
      Serial.print(F("[DEBUG] "));
      Serial.println(s);
   }
}

Beat by 11 seconds... :P


text:
Store 3-dimensional char array in program memory with PROGMEM
I'm running a sketch whith a quite big, constant three dimensional char array (or simply, a table of strings). As this takes lots of RAM I'd like to store it in programm memory in order to keep the RAM free. This is the Sketch I'd like to run (my first idea):
const char *rules [16][5] PROGMEM ={
 {"1Lorem ipsum dolor sit amet, consetetur sadipscin0g elitr", "sed di7am nonumy 8eirmod tempor invidunt"},
 {"2Lorem ipsum dolor sit amet, consetetur sadipscing2 elitr", "sed diam nonumy 9eirmod tempo5r invidunt"},
 {"3Lorem ipsum dolor sit amet, consetetur sadipscing 4elitr", "sed0 diam nonumy 1eirmod tempor invidunt"},
 {"4Lorem ipsum dolor sit amet, consetetur sadips3cing elitr", "sed diam nonumy 2eirmod tempor in5vidunt"},
 {"5Lorem ipsum dolor sit amet, consetetur 3sadipscing elitr", "sed 7diam nonumy 3eirmod tempor invidunt"},
 {"6Lorem ipsum dolor sit amet, conset9etur sadipscing elitr", "sed diam n8onumy 4eirmod tempor invidunt"},
 {"7Lorem ipsum dolor sit amet, consetetur sadipsc3ing elitr", "sed diam nonumy 5eirmod tempor inv4idunt"},
};

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(115200);
  for(int i = 0; i < 16; i++){
    for(int j = 0; j < 5; j++){
     Serial.println(rules[i][j]);
    }
  }
}

void loop() {
}

But this fails with the following error:
variable 'rules' must be const in order to be put into read-only section by means of '__attribute__((progmem))'

According to Arduino's FAQ this can be solved by changing the array's declaration to
const char * const rules [16][5] PROGMEM ={

The sketch compiles now without errors, but the global variables (here only the array) still need lots of RAM:
Sketch uses 2484 bytes (7%) of program storage space. Maximum is 32256 bytes.
Global variables use 880 bytes (42%) of dynamic memory, leaving 1168 bytes for local variables. Maximum is 2048 bytes.

I'm not sure what causes this, but is it possible that only the pointers to the strings are stored in program memory, while the strings theirselves are still copied to RAM?
How do I put the whole arary in programm memory?
There has already been a question like this on StackOverflow, but the answer recommends using prog_chars, which are according to the AVR documentation deprecated.

See http://www.nongnu.org/avr-libc/user-manual/pgmspace.html and also use the special program memory access functions to get the string pointers.

Can you use fixed length data ? That would make it very easy. In that case, don't use a pointer, declare the array with data completely in PROGMEM with "const char rules[16][5][50] PROGMEM = {". The Arduino can not run code from ram and can not read data from program memory. As @MikaelPatel wrote, you need special functions. Read this https://www.arduino.cc/en/Reference/PROGMEM and this http://www.gammon.com.au/progmem Don't rush through those pages, read them. They explain how to use data and a table with pointers in PROGMEM to optimize memory usage.

Fixed data length would be wasting space as the data I really want to store has different lengths. What causes this issue? Is what I described in the question (pointers in PROGMEM, strings in RAM) correct?

Yes, you describe in the question pointers in PROGMEM and strings in RAM. Actually the strings are loaded from PROGMEM to RAM by the program startup code (init).

Maybe wasting a few hundred bytes is acceptable.


text:
Arduino hangs after less than a minute, but not on USB
I have arduino uno + ethernet shield + 9V/200mA adapter. I am trying to send some data with HTTP connection. When it's connected to USB it works perfectly, but when I plugged out USB, hangs (after less than a minute, it stops pinging).
I have tried this:
EthernetClient.cpp

int EthernetClient::connect(IPAddress ip, uint16_t port) {
  if (_sock != MAX_SOCK_NUM)
    return 0; // i changed to -1  as suggested on previous link

  for (int i = 0; i < MAX_SOCK_NUM; i++) {
    uint8_t s = socketStatus(i);
    if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT || s == SnSR::CLOSE_WAIT) {
      _sock = i;
      break;
    }
  }

and also example from library Examples-library-WebClientRepeating, but I get the same problem as in my code.
Is my adapter too weak?
This code is from Example WebClientRepeating:
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED    };

// fill in your Domain Name Server address here:
IPAddress ip(193, 77, 60, 66);
IPAddress subnet(255, 255, 255, 0);
IPAddress gateway(193, 77, 60, 7);
IPAddress myDns(193, 77, 60, 213);

EthernetClient client;

char server[] = "www.arduino.cc";
//IPAddress server(64,131,82,241);

unsigned long lastConnectionTime = 0; // last time you connected to the server, in millisecond
const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers

void setup() {
  // start serial port:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // give the ethernet module time to boot up:
  delay(1000);
  // start the Ethernet connection using a fixed IP address and DNS server:
  Ethernet.begin(mac, ip, myDns, gateway, subnet);

  // print the Ethernet board/shield's IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  if (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if ten seconds have passed since your last connection, then connect again and send data:
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the WiFi shield
  client.stop();

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connecting...");
    // send the HTTP PUT request:
    client.println("GET /latest.txt HTTP/1.1");
    client.println("Host: www.arduino.cc");
    client.println("User-Agent: arduino-ethernet");
    client.println("Connection: close");
    client.println();

    // note the time that the connection was made:
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
  }
}

EDIT 1:
Also when I plug USB in its start working with 9V power adapter.

Is the voltage regulator on the Arduino very hot, or the external 9V adapter very hot, when it stops pinging? Maybe it is likely one or the other failing. Are the LEDs on the Arduino and shield still on? It might be worth blinking a LED to ensure you can see what is working.

Arduino voltage regulator is not so hot, it's touchable. Leds on arduino are ok but on ethernet shield is only first one on, data lights are off.

Then it is probably not power a power problem. Can you measure the voltage on the Arduino's 5V pin? For example, have you a multi-meter? That would confirm or disprove the power supply theory.

I'm pleased it's working and stable, even if my answer was wrong :-) Merry Christmas!

The problem is that when you are using the external 9V power supply, you are relying on the Arduino's on-board regulator to provide the 5V power supply to both the Arduino and the Ethernet shield. This regulator has very limited current capacity — much less than the 500 mA that's available from a PC's USB port — and you're overloading it.
To avoid this problem, you should use a 5V plug pack with a USB connector to power your system.

I think your description of the cause is slightly incomplete, and so may be misleading for others. Tests show the Arduino UNO's on-board regulator can supply 500mA at 9V, see the Arduino UNO temperature vs current graphs FTDI NerO. It should be easy for the OP to diagnose this as the voltage regulator should be very hot. If this is the case, I agree your solution should work.

Arduino voltage regulator was hot, it was in box. When i get Arduino out, it starts working. So i change 9V adapter With 5V 1A and now is working fine. I'll test it over night. Thanks

It may be that, for some reason, the library thinks Serial communication is working, but when the buffer of unsent characters gets full, it hangs waiting to complete a Serial.print() or Serial.println().
So, try commenting out all use of Serial.
For example change
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

to
  /*
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  */

and Serial.println(...); to // Serial.println(...);
This might happen if the system is started with USB working, and then USB is unplugged.


text:
Current Arduino STL Libraries
I was going to update this question but I thought that this was different.
I have been trying to get std::vector to work with the latest Arduino. I have tried downloading several libraries found online but I can not get one of them to compile correctly. So here is my question, does anyone CURRENTLY know of a Arduino STL Library that is working?
StandardCplusplus: As stated above I tried to use this library but run into problems with the new/delete functions.
Andy Brown's AVR-STL Library doesn't even seem to come close to compiling.
If anyone has a working copy of these two I would love to have a copy or if you can tell me how to get them to compile. Otherwise I really need to find a way to get Vectors working, does anyone have any ideas?
Edit
I didn't want to answer this question so it is still active as I am sure there will be additions to this. Anyways I FINALLY got a library to work (for now, so far). I downloaded the StandardCplusplus library and found that in order to get any of the stl functions to work you have to add an include to the "StandardCplusplus.h" file before EVERY use, not just in the first file as stated in the Wiki on the Project page.
So I was able to get vectors to work using the following:
#include "StandardCplusplus.h"
#include <iterator>
#include <vector>

vector<int> test;

void setup(){
   Serial.begin(57600);

   test.push_back(1);
   test.push_back(2);
   test.push_back(3);
   test.push_back(4);
}

void loop(){
   for (int i = 0; i < test.size(); i++){
      Serial.println(test[i]);
   }
}

I would still like to know of other working STL Libraries as it seems that there are tons of outdated and old libraries out there.

I was wondering the same. At school, we once used the "GNU-GCC" toolchain to cross-compile for AVR targets.
We could use all fancy vector & queue things, but I'm uncertain if it required any additional steps (which I forgot).

You may try the original C++ libraries? They would be poorly optimized though, but I'm curious if they will perform reasonable. C++ should be portable to other platforms, though, microcontrollers do have their limits.

@Paul I really am not sure were to start trying to port the original libraries, I am pretty new to Arduino and AVR Programming and I am still feeling out the limitations. I do know however that other people have been successful in using vector and other STL functions. I just have to figure out how to do it repeatably. Another thing I noticed when using the above library I get intermittent compiler errors so I am thinking that there are still issues.

You are probably having a hard time finding good libraries because dynamic memory is rarely used on micro controllers with such small amounts of RAM

@BrettAM I realize that there are issues when dynamic memory is used incorrectly but at the same time they did have CAD systems on the old 286 processors and these AVR's are not too far from those ;-) I am not looking to run streams I am only looking for vectors

pay you attention which kind of arduino do you use. it can compile for Mega but not for Leonardo for example

I maintain an Arduino plugin that's a port of uClibc++ (just like the defunct StandardCplusplus library). It's available in the Arduino library manager for Arduino versions 1.6.10 and higher. It's called ArduinoSTL.

Thank you for the suggestion but I am running into a problem with your library. I simply tried to include the "ArduinoSTL.h" file into a blank sketch but I receive a error in iterator.cpp "The system cannot find the file specified.". Any idea what file might be missing from my setup? I am using Eclipse Neon

You must include it via Arduino's GUI Sketch -> Include Library -> ArduinoSTL. If it's not in the list you can install it from the built-in library mager: Sketch -> Include Library -> Manage Libraries...

Pity there's no C++11. Your <type_traits> header is lacking great many functions.

It's a pity it doesn't compile, at least with PlatformIO 5.0.2 and Atmel megaAVR 1.3.0.
I get an error that In file included from .pio/libdeps/nano_every/ArduinoSTL/src/ArduinoSTL.h:12:0,                  from .pio/libdeps/nano_every/ArduinoSTL/src/ArduinoSTL.cpp:1: .pio/libdeps/nano_every/ArduinoSTL/src/serstream:307:9: error: '::Stream' has not been declared


text:
How to perform action if two rfid tag UIDs have been detected?
I'm using an rfid-rc522 and I want to print to the serial a string of text if two rfid tags have been read in a given time period.
Essentially this:
 1. First tag is read (print to serial: Tag 1 has been read)
 2. Wait 2 seconds
 3. Second tag is read (print to serial: Tag 2 has been read)
 4. Print to serial: Tag 1 and Tag 2 has been read)
 5. Bonus: Keep this state - and then when a button is pressed (print to serial: Tag 1 and Tag 2 are finished)
I know how to read the UID and print to the serial if one is read.
Thank you so much for your help, it's greatly appreciated.
Here is my code so far:
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>
#include <MFRC522.h>

// For the breakout, you can use any 2 or 3 pins
// These pins will also work for the 1.8" TFT shield
#define sclk 4  // SainSmart: SCL
#define mosi 5  // SainSmart: SDA
#define cs   6  // SainSmart: CS
#define dc   7  // SainSmart: RS/DC
#define rst  8  // SainSmart: RES

Adafruit_ST7735 tft = Adafruit_ST7735(cs, dc, mosi, sclk, rst);

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);

float p = 3.1415926;

void setup(void) {
  Serial.begin(9600);
  SPI.begin();
  Serial.print("Starting cornhole leaderboard...");
  mfrc522.PCD_Init(); // Init MFRC522 card
  Serial.println("Scan PICC to see UID and type...");
  // Use this initializer if you're using a 1.8" TFT
  tft.initR(INITR_BLACKTAB);   // initialize a ST7735S chip, black tab

  // Use this initializer (uncomment) if you're using a 1.44" TFT
  //tft.initR(INITR_144GREENTAB);   // initialize a ST7735S chip, black tab

  Serial.println("Initialized");

  uint16_t time = millis();
  tft.fillScreen(ST7735_BLACK);
  time = millis() - time;

  Serial.println(time, DEC);

  // large block of text
  tft.fillScreen(ST7735_BLACK);
}

void loop() {

  // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }

    if (mfrc522.uid.uidByte[0] == 0xA4 &&
       mfrc522.uid.uidByte[1] == 0xB8 &&
       mfrc522.uid.uidByte[2] == 0xB8 &&
       mfrc522.uid.uidByte[3] == 0x96) {
          Serial.println("Nate has checked in to the game.");
          tft.fillScreen(ST7735_BLUE);
          tft.setTextSize(2);
          tft.setCursor(0, 0);
          tft.setTextColor(ST7735_YELLOW);
          tft.print("Nate ");
          tft.setTextColor(ST7735_WHITE);
          tft.println("has checked in ");
          tft.setTextSize(2);
          tft.println("to the game.");
          delay(2000);
          tft.fillScreen(ST7735_BLACK);
    }

    if (mfrc522.uid.uidByte[0] == 0x03 &&
       mfrc522.uid.uidByte[1] == 0xFD &&
       mfrc522.uid.uidByte[2] == 0xBC &&
       mfrc522.uid.uidByte[3] == 0x02) {
          Serial.println("Ted has checked in to the game.");
          tft.fillScreen(ST7735_RED);
          tft.setTextSize(2);
          tft.setCursor(0, 0);
          tft.setTextColor(ST7735_CYAN);
          tft.print("Ted ");
          tft.setTextColor(ST7735_WHITE);
          tft.println("has checked in ");
          tft.setTextSize(2);
          tft.println("to the game.");
          delay(2000);
          tft.fillScreen(ST7735_BLACK);

    }

}

What you can do is store the current time whenever a card is swiped, and then when another card is swiped check how long it's been since the last card was swiped
first create a couple of variables
unsigned long swipedTime;
int tag1 = 0;
int tag2 = 0;
int swipeTimeOut = 10000; // how much time in MS you have to swipe both cards

Next we'll jump down to where where you read the cards.
      if (mfrc522.uid.uidByte[0] == 0xA4 &&
           mfrc522.uid.uidByte[1] == 0xB8 &&
           mfrc522.uid.uidByte[2] == 0xB8 &&
           mfrc522.uid.uidByte[3] == 0x96) {

               ........

               if (tag2 == 1 && millis() - swipedTime < swipeTimeOut ){
                   // both tags have been swiped, print serial message here
                }

                tag1 = 1;
                swipedTime = millis();
        }

        if (mfrc522.uid.uidByte[0] == 0x03 &&
           mfrc522.uid.uidByte[1] == 0xFD &&
           mfrc522.uid.uidByte[2] == 0xBC &&
           mfrc522.uid.uidByte[3] == 0x02) {

               ........

               if (tag1 == 1 && millis() - swipedTime < swipeTimeOut ){
                   // both tags have been swiped, print serial message here
                }
                tag2 = 1;
                swipedTime = millis();

         }

You'll also want to come up with a system for resetting tag1 and tag2 to 0 or "checking them out".

You could try:
byte tag1[] = {0xA4, 0xB8, 0xB8, 0x96};
byte tag1_read = 0;    // flag is set when tag 1 is read
byte tag2[] = {0x3, 0xFD, 0xBC, 0x02};
byte tag2_read = 0;    // flag is set when tag 2 is read

int BUTTON = 3;

void setup(){
    pinMode(BUTTON, INPUT_PULLUP);  //set button as input pulled high
    .... // the rest of your setup()
}

void loop() {

  // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }

    if (tag1_read == 0 && memcmp(mfrc522.uid.uidByte, tag1, 4) == 0){
          Serial.println("Tag 1 has been read.");
          tag1_read = 1;   //tag 1 has been read
          //delay(2000);   //not sure why u need the delay
    }

    if (tag1_read && tag2_read == 0 && memcmp(mfrc522.uid.uidByte, tag2, 4) == 0) {
          Serial.println("Tag 2 has been read.");
          tag2_read = 1;    // tag 2 has been read
          Serial.println("Both tags have been read.");
    }

    if (digitalRead(BUTTON) == LOW && tag1_read && tag2_read){
        Serial.println("Both tags are finished.");
        tag1_read = 0; tag2_read = 0;
    }
}

This code assumes the cards must be presented and read in order.


text:
Does an I²C IO Expander needs additional resistors for outputs?
I have following setup (see also schematic in the end)
Arduino Nano is connected via I²C to the PCF8575C (link) IO Expander.
Both, SCL and SDA have 10kOhm pull-ups to 5V.
The Expander pins are connected to a MOSFET-driver that turns on/off 12V LED stripes.
The Expanders Bus address is set via Expanders A0-A2 pins to 0 (0x20).
The MOSFET driver pins have to be pulled to logic 1 (above 2.2V) in order to turn on the stripe.
Currently Arduino runs an blink example, that turns all Expander IO pins on/off every second (using Arduino Wire Library), but the MOSFET-driver does not turn on/off any Stripe.
I can manually turn on Stripes by connecting MOSFET-driver pins to Arduinos 5V (or 3.3V)
The power supply to the IO Expander is O.K.
By measuring the resistance between GND and IO pins of the Expander, I can see that it alternates every second (so I²C communication to the Expander works also)
Curious thing: While measuring this resistance (holding the multimeter test leads) to GND and to the IO pin of Expander, the MOSFET-driver turns the Stripes on and off! When I take the test leads away it stops working! Magic?!
What am I missing? Do the output pins of the PCF8575C need some extra pullup/pulldown resistors or something else?
Thank you in advance!
Schematics:

What does the datasheet for the chip tell you? (hint: table on page 3...)

@Majenko oh, I see – I need for each output a 1kOhm pullup (to 5V), right?

You need a pullup - the actual value depends on your application. 10KΩ is probably better than 1KΩ since it will reduce current wastage.

Yes, according to the datasheet (which should always be your first port of call for any chip) the outputs are Open Drain. That means you require a pullup resistor, exactly as if the outputs were simple buttons.

I need a pullup resistor? So one and not 15 (for each output)?
Does that mean, I can use single common resistor for all outputs?

No, one pullup resistor per pin you use as an output.

okay, thank you, I'll test that today! But anyway, how can this "mysterious" behavior with the Multimeter be explained?

When you measure resistance you are applying a voltage. That voltage is acting like a pullup resistor.

Adding of missing pullup resistors to the outputs did the trick. Thank you!

Think of the oped drain output (or open collector) as a pin that connects to ground when the device is on. If you connect the anode of an LED to plus and connect the kathode to the open drain pin, then you do not need a pull-up resistor (you may need a current limiting resistor though)
The test leads of the Ohmmeter produce a current to masure resistance, it also provides a current path to ground if the that's where you placed one of the leads. This would explain the Magic
More here about open collector outputs.


text:
OOP vs Inline with Arduino
I have been programming for quite a while now but I am new to Arduino and AVR Programming. The main question I have about programming these Micro-controllers is are there major differences in designing code in Object Orientated Classes vs the more traditional inline programming I have seen in many examples?
In other words in the world of Arduino/AVR Controllers are there any savings with Memory and Performance utilizing classes or visa versa?
Say for example we have a Class:
class SomeClass(){

private:
   int x;
   int y;

public:
   void foo();
   void bar();
}

SomeClass thisClass;
thisClass.foo();
thisClass.bar();

Would there be any performance or memory gains designing the program in a more inline fashion like:
int x;
int y;

void foo(){ /*** Do something ***/};
void bar(){ /*** Do more stuff ***/};

I tried doing some searches on Stack Exchange and Google but couldn't find quite the answer I am looking for the closest thing I was able to find was this Stack Exchange Question.
The reason I am asking about this is I have a project that needs to be as light as possible and I am not clear how I should be designing my program in this environment.

Edit
Thank you for the answers, this has shed light on things. There is one thing that I am not quite clear about.
Say you have a class that you are designing that utilizes the u8glib as follows:
class UserInterface{
private:
   U8GLIB_ST7920_128X64 Display;

public:
   UserInterface();
}

How would you get around using "Dynamic Memory" like:
UserInterface::UserInterface(){
   UserInterface::Display = U8GLIB_ST7920_128X64(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE);
}

The main question I have about programming these Micro-controllers is
are there major differences in designing code in Object Orientated
Classes vs the more traditional inline programming I have seen in many
examples?
...
In other words in the world of Arduino/AVR Controllers are there any
savings with Memory and Performance utilizing classes or visa versa?

Yes, there is a great difference between using C or C++ for small scale embedded systems such as Arduino/AVR. C++ allows more information to be provide for compiler optimizations.
If you are implementing an OOP framework, platform or runtime C++ and classes can also help with software architecture and reuse. In Cosa a number of OOP design patterns are used to achieve interfaces for both application programmers and device driver programmers. The most common is delegation.
Using abstract classes, virtual member functions, inlining, and templates can help achieve lower foot-print and higher performance than traditional implementations. As an example the Cosa Pin classes are X5-X10 faster than the Arduino core and at the same time smaller in foot-print. Please see the benchmarks.
One thing to "unlearn" from traditional C++ programming is the usage of new/delete (malloc/free). With SRAM size of only a few Kbyte using a heap is very much a risk. The answer is static classes and stack based data.
There is much more to be said about OOP framework architecture but I hope this helps answer your initial questions.
Cheers!

Nice Answer! I updated my question asking about how to get around the dynamic memory (new/delete/malloc/free). Do you have any input on not using dynamic memory allocation? Should everything that needs to be shared throughout the classes be global? That doesn't sound right to me, I was always taught not to use globals if you can help it.

A short comment on your UserInterface example above. The Display is actually object composition (not reference/pointer) so you do not need new. You do need to initiate the Display. The UserInterface construction should look something like this. UserInterface::UserInterface() : Display(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE) { ... }. The necessary Display constructor parameters should be passed to the UserInterface constructor.

OOP is all about encapsulation, hiding data, so sharing should be a minimum (zero). The goal is to more or less only have a number of global static objects that interact. They hold and hide the global state. For the objects the member data is a non dynamic local state. To achieve the goal you need again a set of tricks; program transformations.

An example; Consider the design of a BitSet class that may have variable number of members. The obvious solution is to calculate the number of bytes required and use new/malloc. An alternative is to pass the storage as a parameter to the BitSet constructor. A third alternative is a template class with number of elements as parameter. This allows a member variable that is the necessary number of bytes. Please see Cosa/BitSet.hh for more details on this variant of program transformation. There are more transformations.

I updated my UserInterface example, is that more or less the correct approach? I think I now have a very good understanding on how to implement what I need to.

The Cosa library sounds like it contains many of the features that I am inquiring about. I went to the website and noticed that it is a complete replacement of the Arduino Library. Is the overhead and footprint of Cosa comparable to the Arduino Library?

Cosa is (according to benchmarks) has higher performance and lower memory foot-print. For instance, the Cosa Pin classes are X5-X10 faster than Arduino/Wiring functions, Cosa UART (Serial) can run at up to 2Mbps and 100% bandwidth up to 1Mbps. There is support for events, timed/queued functions (jobs), fsm, proto-thread, threads, etc. But the most important issue is that the classes are designed to work together.

Your update was not correct. The Display should not be static.

I updated my question again, I was thinking that the Display should be static since I only wanted one instance in memory since there is really only one display.

The reason you can't find the answer is because the answer is both Yes and No.
For basic class stuff - defining your class with methods etc and instantiating objects from it - there's little difference in the end result compared with "vanilla" C.  The compiler's optimizations are so good now that performance is just the same. Yes, there may be slight increases in memory use since you're passing an extra pointer with each method call (instead of foo(int x) you have foo(MyClass *this, int x)) but that's so small as to not be noticeable.
The big differences come when you start playing with polymorphism and other advanced topics.  When start doing these complex programs the compiler is not always unable to work out which functions are required and which aren't, and it's not able to cut out the unused functions ("garbage collection"). So you may well end up with bigger code.
That doesn't mean slower code, just chunks of code that are hanging around that never do anything.
Of bigger importance is managing your dynamic memory better than you are used to.  Since there is such a small amount of memory the heap is very small, and as a result it gets fragmented very easily.  Dynamic creation and destruction of objects (new myClass, delete myClassObject, etc) is very bad.  Class objects really need to either be statically defined (in global scope is the most common) or temporarily allocated on the stack (local instances).  Otherwise you're asking for trouble - and the first you will know of it is strange things happening (no error reports or exceptions, you see...).

Alright so if I understand this correctly in this world of programming, classes are used for more of a organizational and portability role than true OOP and that things should be allocated statically and explicitly rather than dynamically. Great thank you, this makes allot of sense and explains why I have been seeing examples and what not written the way they are.


text:
If I put a shield on an Arduino, can I use the Arduino for anything else?
I did some basic Arduino examples in the recent past, but I have never actually seen a shield for Arduino firsthand.
So I wonder: If I put a shield on an Arduino (for example, the Adafruit Motor Shield), does it "block" the entire Arduino, including all input and output pins?
Is it possible to use a shield, and still connect additional components that would usually connect directly to the Arduino (say, a potentiometer, or anything similar)? Does this depend on the type of Arduino, or on the type of the shield, or is it not possible at all?

Normally, yes, you may plug other components to your setup after you plug your shield, but it depends on the shield exposing the unused Arduino pins through additional female headers.
Some shields even provide a little protoboard or perfboard to make it convenient for plugging or soldering additional components. Below are some examples:

Arduino shields are normally designed to be stackable, so you can plug one on top of the other. See more on Arduino shields from this WikiPedia article. See below one example of stacked shields, shamefully stolen from this great answer by RedGrittyBrick.

Photo by John Boxall
But note that you need to study carefully what pins each of the shields use to avoid conflicts between the boards. Such conflicts may lead to damages.

There are several distinct concerns to consider:

Physical interference: are headers provided to make it possible to stack the two shields on top of one another?  Do any protruding components block stacking?  Do any components have metal shield cans (for example the USB connector on the Uno itself) which can short out an adjacent PCB?
Pin assignments: generally you cannot use the same pin for two different purposes.  Many shield provide a way to alter the pins used in order to avoid those used by another shield.  Sometimes you can share a pin, for example two SPI devices can usually share their clock and data lines provided they have separate selects, and you may be able to even use those signals for other purposes while the SPI select is de-asserted.  Sometimes you can move a part from an unavailable hardware peripheral to a software emulated one, for example using software serial, bitbang SPI, or interrupt based PWM.
MCU resources: Not specifically the shields themselves, but driver libraries may end up consuming large amounts of program memory or RAM, using up timer channels, needing interrupts frequently services with low latency, etc, so combinations may not be possible or may require alterations to library code.

As long as the shield uses stackable headers (or provides alternate headers) it doesn't block any (broken out) pins, either input or output. It is possible to add more shields or components, but the circuit must still be "valid" (all inputs must be either be connected to an output or have the pullup enabled, no more than one push-pull output connected together, etc.), otherwise components may be damaged.

Yes, but sometimes it interferes with the output and the input pin, and most shields use up the
CS, MOSI, MISO, SCK pin. Even through on some shields like wireless SD shield you can switch from USB to MICRO, this is going to interfere with your program. Say, when you want to access
the info on your SD card to run your Motor Shield.


text:
Zigbee Relay board communication with Arduino
I have bought this wireless ZigBee relay board.
I was wandering about an arduino sketch to get started, I have searched for 2 days now but with no results.
What I was thinking of is to have an Arduino with ZigBee module to send signal to another ZigBee device on top of the relay, to be able to open/close relay.
So, can anyone share a sample sketch for that board?

Take a look at this library : https://code.google.com/p/xbee-arduino/
This is the XBee Library for Arduino, you will find simple sketch that are perfect bases for the application you're trying to do.


text:
Programming Arduino
I'm new to electronics. Professionally I'm a software developer. I want to know whether it is possible to program Atmel AVR 8-bit and 32-bit Microcontrollers using Arduino IDE. If yes could any one guide me on the process or direct me to any site where I can learn about it.

You can Google AVR. There are tons of tutorials. Google is your friend.

Yes I do have winavr to program it but I would like to know whether Aurdino programming language can be used.

Understood. Just to be clear, there is no such thing as an Arduino programming language. You can program an Arduino with c or cpp with the Arduino library.

"Arduino" is not a programming language. It's C++ with an IDE that does most of the drudge work of dealing with hardware and libraries.

Downvoted because, well, it's a lousy question. You need more detail. This is not the kind of question I would expect from a software developer with professional experience.

Yes, it is possible. In fact, this is how the whole 'Arduino' concept works - programming 8/32 bit AVR microcontrollers with the Arduino IDE.

program Atmel AVR 8-bit and 32-bit Microcontrollers using Aurdino IDE

This has two parts actually:
1. Generate compiled HEX targeting AVR
Using the Arduino IDE you could utilize the Arduino libraries (aka working with assist utility functions like digitalWrite for example), which are built on top of the AVR tool-chain. The official Arduino IDE comes with pre-built support for several 8-bit/32-bit Atmel AVR micro-controllers, the full list of supported boards can be found on the Arduino official website or in this Wikipedia page.
You did not specify a specific MCU, therefor you should check if the MCU you would like to work with is in that list.
2. Uploading an Arduino sketch to a compatible AVR
Arduino IDE uses avrdude under the hood. avrdude is

an utility to download/upload/manipulate the ROM and EEPROM contents
  of AVR microcontrollers using the in-system programming technique

(From their website).
The best place to start is the official Arduino.cc website, in the 'Getting Started' section. If you haven't picked any specific Atmel AVR chip yet, consider that each has slightly different features, size, I/O pins etc. so make sure to research a bit before purchasing one (reference the table in the Wikipedia link above to compare between the different kinds).

http://arduino.cc/ is good place to start. It includes articles about how to get started, library references, and user forums. The Arduino IDE will certainly get you started, but as an experienced developer you'll most likely hit its limitations pretty quickly.
Later, or quite possibly sooner(!) you can use same toolset (compiler, loader, libraries) in several less limiting environments: Eclipse IDE, edit/make at the command line, and Atmel's AVR Studio. C and C++ are mainstream; I've seen references to the existence of (but never tried) AVR Forth and AVR python.
Though you'll see occasional references to an 'Arduino language' it's really nothing more than C++ with some attempt to be smart about detecting references to library packages and auto-inserting the relevant #includes.
You probably won't want to take advantage of such shortcuts, and keep to good programming practices, if you think you'll ever want to move up from the Arduino IDE.
I personally use Eclipse (supplementing with a few command line tools) and I'd recommend it once you've tried the Arduino IDE.

Just to complement the other responses. You can program some AVR chips using the Arduino IDE, but for it to work out-of-the-box just by using a USB cable it needs to be an Arduino or "Arduino compatible" board, mostly because these come with the Arduino Bootloader.
The bootloader is a small piece of software that runs at power-up and is responsible to load your program into the chip (as well as other configuration stuff, for more info read the previous link). If the AVR chip does not have the bootloader already flashed, then you will have to use a programmer (connected to its ISP pins) to burn it first.
So, it's not like you can just buy random AVR chips or development boards online and start using them. But taking in consideration the wide selection of official boards and "Arduino compatible" ones, you should be able to find something to fit your needs.

Although if you have a programmer there's no need to have a bootloader at all, since the IDE supports uploading the code via programmer.

Also, you can also buy bootloader-loaded chips, and you can program a chip with another Arduino or your homemade-duino.

Thanks  Ignacio Vazquez-Abrams just for clarification if I have Arduino programmer I can program my Atmel Avr MCU without a bootloader.


text:
Setting time frame in Arduino Uno
I have built the circuit below using mux ICs. In a particular interval the respective selector pins get selected and analog signal from hall sensors are read and give a particular analog value out. There is a total of 30 hall sensors which are represented by HS0 to HS31.

Now I wanted to set time as in the table below. After 8000ms I would like it to reset the time automatically and start reading. Can someone tell me which timer example would let me achieve this?
TIME IS ms  OUT1    OUT2    OUT3    OUT4
  0-1000    HS0     HS8     HS16    HS24
1000-2000   HS1     HS9     HS17    HS25
2000-3000   HS2     HS10    HS18    HS26
3000-4000   HS3     HS11    HS19    HS27
4000-5000   HS4     HS12    HS20    HS28
5000-6000   HS5     HS13    HS21    HS29
6000-7000   HS6     HS14    HS22    HS30
7000-8000   HS7     HS15    HS23    HS31

Could you tell us which multiplexer IC you are using? This way, we can help you better. Also, why do you need the 8 second cycle? Does it matter if it's a little shorter or longer? If timing does not have to be very precise it would make things a lot easier.
By the way: you say there are 30 sensors, but your table has 32...
The following pseudocode will not work on your Arduino, but you can use the same structure.
int sensorArray[32] // we will store our 32 sensor values here

// these pins control the multiplexer chips
int selectPinZero = 8;
int selectPinOne = 9;
int selectPinTwo = 10;

// these pins will receive the sensor values from the multiplexer chips
int inputPinOne = 0;
int inputPinTwo = 1;
int inputPinThree = 2;
int inputPintFour = 3;

void setup(){
    // make sure the correct pins are inputs and outputs
    pinMode(selectPinZero, OUTPUT);
    pinMode(selectPinOne, OUTPUT);
    pinMode(selectPinTwo, OUTPUT);

    pinMode(inputPinOne, INPUT);
    pinMode(inputPinTwo, INPUT);
    pinMode(inputPinThree, INPUT);
    pinMode(inputPinFour, INPUT);
}

// all done, now keep reading the sensors
void loop(){

    // set selectPins so that each Multiplexer will output its first channel
    digitalWrite(selectPinZero, HIGH); // or low, depending on your Multiplexer IC
    digitalWrite(selectPinOne, HIGH); // or low, depending on your Multiplexer IC
    digitalWrite(selectPinTwo, HIGH); // or low, depending on your Multiplexer IC

    // start reading sensors

    int i = 0;
    while(i<32){
        sensorArray[i] = analogRead(inputPinOne);
        i++; // variable i was 0, now 1

        sensorArray[i] = analogRead(inputPinTwo);
        i++; // variable i was 1, now 2

        sensorArray[i] = analogRead(inputPinThree);
        i++; // variable i was 2, now 3

        sensorArray[i] = analogRead(inputPinFour);
        i++; // variable i was 3, now 4

        /*
        use digitalWrite() on all the selectPins to make the Multiplexer IC output the next channel
        */

        delay(1000); // wait 1000 milliseconds
    }

    /*
    this will repeat until all 32 sensors are read and stored in the array
    */

}

This code is by no means optimized, but written to make it easy for you to understand. Good luck!


text:
Is it possible to transmit using an NRF24L01+ without an Arduino?
I have two NRF24L01+ modules which are transceivers, but for my project I would like to send a very simple signal from one of these modules to the be read by the other.
That would've been very simple if I had an Arduino on each side but due to power consumption constraints as well as size, cost and practicality, the transmitting side won't have one. Would it still be possible to do this?
To clarify, the message itself is not important and can be set in stone, it will never change. I really just want to detect on the receiving side (which will have an Arduino) that the transmitter is in fact transmitting. Transmission will be triggered by a push-button.
Ideally I would have a way of identifying my particular transmitter from others on similar frequencies but I am not too precious about that.

You don't need an "Arduino" but you do need a microcontroller core as that particular chip does not have a user-programmable one.  To stay with something that can be treated Arduino-style you could probably make do with an attiny85 (or even the 45 or 25), in a tiny surface mount package, and have it only active a tiny fraction of the time and in negligible-power sleep the rest.

Thank you, Chris, that actually answers my question so if you'd like to post it as an answer I can vote it up.

Also, would you then suggest another approach to doing what I intend with a different transceiver or transmitter / receiver pair that does not need a programmable microcontroller?

Not sure why the question was voted down?

is there a difference between the nrf24l01 and nrf24l01 + libraries?

The nRF24L01+ has a somewhat complex SPI based interface, where many registers have to be configured and tested and timeouts honored.  Therefore it requires some kind of microcontroller to send or receive even the simplest message.
This can be as simple as a 3.3v Arduino Pro Mini (less than $3 with shipping), and there are libraries which simplify the task of interfacing to it - in particular see the RF24 library (there are many variations, see https://github.com/TMRh20/RF24 for a good one).
But many other microcontrollers could work as well.
Once you bite the bullet and accept the need for a microcontroller, yes the code can identify the source of the signal (which pushbutton) and much, much more.
Or you could use a dedicated device like an xBee which can be configured using a Windows utility to send the state of an input pin to another xBee; basically there is already a programmed microcontroller on the module along with the radio (not nRF24L01+ compatible).

Thanks, Zeph, I appreciate the clear answer. I would vote up except I don't have the reputation to do so yet.

An ATTiny85 can drive the NRF24L01+: "nrf24l01+ control with 3 ATtiny85 pins"
At least this is not a "full" Arduino...
Edit 2015-06-06:
Hackaday News: "EMBED WITH ELLIOT: MULTIPLEXING SPI USES FEW PINS"
The referred blog entry is: "nRF24l01 control with 2 MCU pins using time-division duplexed SPI".
(-: Nice countdown... 3 pins, 2 pins, ... ;-)

Note, there is also the NRF24LE1 SoC which has its own ULP MCU - good for transmitting simple data such as sensor readings. If used to Arduino, ARduino Pro Mini 3.3v and the NRF24L01+ is easier and better way to go. (Mod the Arduino to be ULP)

1) Easy way
This transmitter uses only SPI interface so you need to drive it some logic unit, i.e. microcontroller that supports this interface (i.e. AVR atmega8) and is able to use driver for this module as a ready to use set of high level functions to express your intentions in your code.
2) Badly bad way
You can use the SPI to I2C converter as well. Connect it to your computer via serial port - but note that it's a big effort. You will need to port nRF24L01 driver, etc.
http://www.elecrow.com/nrf24l01-wireless-shield-spi-to-i2c-interface-for-arduino-p-737.html


text:
How to refine ultrasonic readings
I am trying to filter ultrasonic readings using averaging technique. I've also used millis() to measure time from start so that I can calculate readings up to 1 second and average them. I've re-initialized the elapsedTime variable each time to zero in the loop but again when the program execution hits this code the time starts from the time it was before. Is there any way to solve this problem?
This is the code:
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

int dist, ctr, filteredDist;
long rawValue = 0;
unsigned long StartTime = millis();

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}
//********************************************************************************************************************
void loop() {
  delay(500);
  unsigned long elapsedTime = StartTime;

  while (elapsedTime < 1000) {
    ctr++;
    dist = sonar.ping_cm();
    rawValue += dist;
    elapsedTime = millis();
  }
  filteredDist = rawValue / ctr;
  Serial.println(filteredDist);
}

You're looking at absolute times (the time since boot). You need to look at time differences. That means performing subtraction.

@Majenko thanks for your reply. It would be great if you would slightly modify the code.

I can't "slightly" modify the code. It needs a complete rewrite. There's not a lot that can be salvaged there except the ping code.

Look at the BlinkWithoutDelay example, and consider using a library for the averaging - such as my Average library.

elapsedTime=millis(); sets elapsedTime equal to the current value of millis(), which in the sketch above is the total time since the Uno powered up.  Thus  elapsedTime will exceed 1000 any time after the first second of execution, in which case the while won't do anything.
Instead say elapsedTime=millis() - StartTime; within the loop.  Whenever you want to start the averaging cycle again, say StartTime = millis();.
If your only use of elapsedTime is to control the while loop, get rid of that variable; instead of  while(elapsedTime < 1000), say while(millis()-StartTime < 1000).


text:
Hall effect sensor
I've taken velocity readings of a wheel using a hall effect sensor. Is it possible to take the acceleration readings corresponding to those velocities as well? Do I just have to divide the velocity by the time taken?

Yes, you can divide speed by time and get acceleration, obviously that will give you the mean acceleration between speed reading.

Cheers Lesto!!!


text:
Controlling two AC devices, device turning on incorrectly
I am making use of the code below to control the speed of an AC fan and the intensity of an AC Lamp with an Uno.
The problem I am having is that, when I set the lamp intensity to low or medium, the fan turns on at a very low speed as well, and I cannot turn it off even when setting the fan to off.
Also if I turn the lamp on and then off, the fan (which is still set as off), will spin slowly for a second or two in random intervals.
For troubleshooting purposes, I did separate this program into two programs, controlling each device and its circuit separately, and it works perfectly, but when I combine them, I get the above problem.
Any assistance in troubleshooting or ideas to solve this would be appreciated.
Haven't attempted AC control before.
int PWM = 3;
int FAN = 4;
int dimming;

void setup()
{
  Serial.begin(9600);
  Serial.println("Serial connection started, waiting for instructions…n0 =     Offn1 = 25%n2 =50%n3 = 75%n4 = 100%");
  pinMode(PWM, OUTPUT);
  pinMode(FAN, OUTPUT);

  attachInterrupt(0, zero_crosss_int, RISING);
}

void zero_crosss_int()
// function to be fired at the zero crossing to dim the light
{
  int dimtime = (75 * dimming);  // For 60Hz =>65
  delayMicroseconds(dimtime);    // Off cycle
  digitalWrite(FAN, HIGH);   // triac firing
  delayMicroseconds(10);         // triac On propogation delay
  //(for 60Hz use 8.33)
  digitalWrite(FAN, LOW);    // triac Off
}

void loop ()
{
  if (Serial.available()) {
    char ser = Serial.read(); //read serial as a character

    switch (ser)
{

  /* Lamp Control  */

  case '0':
    analogWrite(PWM, 0);  //lamp Off
    break;
  case '1':
    analogWrite(PWM, 50);  //lamp low
    break;

  case '2':
    analogWrite(PWM, 130); //lamp medium
    break;

  case '3':
    analogWrite(PWM, 255); //lamp high
    break;

  /* Fan Control  */

  case '4':
    dimming = 128;  //fan off
    break;

  case '5':
    dimming = 90; //fan low
    break;

  case '6':
    dimming = 65; //fan medium
    break;

  case '7':
    dimming = 35; //fan high
    break;

  default:
    Serial.println("Invalid entry");

    }
  }
}

The circuits it controls is based on these :
Lamp

Fan

Also, these circuits and code are based on these post, if it may interest you:
Lamp
PWM AC Lamp
Fan
Dimmer AC Fan

dimming should be volatile.

I was advised that. Tried it and it didn't make a difference.

Suppose you have conditions under which the problem manifests itself. Please tell me what will happen if you disconnect the lamp manually.

If the lamp is disconnected, I still get the same issue . In fact, disconnecting  the lamp circuit completely from the Arduino, I still get the fan randomly spinning for a short burst if I set the lamp to turn on at low or medium with the code. It's almost as if the PWM signal is controlling the fan or interfering

By the end of interrupt processing, all others are blocked. The function zero_crosss_int() takes too much time. This can cause problems with the built-in function and the base code. Try to move the part that specifies the time interval outside the interrupt handler.Or schedule a timer for these purposes.
Also, I wonder why you use two different circuit-based principles for similar tasks in one design?

I simply wanted to attempt to control the AC devices in two different ways, although they are similar. Do you know how I can implement a timer instead?

The design of the zero_crosss_int() ISR is unreliable. After each interrupt it unconditionally turns on the triac, even in the OFF position. Since the dimming value in that case is close to the AC cycle duration, it may miss the current cycle and turn on early in the next cycle. This may happen e.g. due to noise in zero crossing input.
75 us * 128 = 9.6 ms. Assuming 50 Hz AC, cycle duration is 1000 ms / 100 = 10 ms. You only have 4% margin.
You need to avoid turning on the triac close to the end of the AC cycle. Limit the maximum value of dimming variable to, say, 75% of the AC cycle. This will impose a lower limit on the output power. However, you want to do this anyway because motors need a minimum power to start rotating. Adjust the ISR so that in the OFF position it does not send a positive pulse at all.
ADDED: so you just need to add an if statement to you ISR code:
void zero_crosss_int()
// function to be fired at the zero crossing to dim the light
{
  if (dimming > 96) // choose this value experimentally, adding some margin
    return;
  ... everything else goes here ...
}

ADDED2: Blocking for extended duration in the ISR is not a good idea in general. If you happen to need to do anything else in addition to 'dimming' a fan, you will almost certainly need to get rid of this. You could start a timer in the ISR and send the output pulse in the timer ISR, making sure that the timer ISR does not get executed after the next zero-crossing ISR...

I added the if (dimming > 96) condition, and that fixed the problem! The Fan is no longer turning on if I switch the lamp on at low intensity. However, the IFR830 Mosfet used in the circuit to control the lamp is now heating up, just noticed it melting a jumper cable. Did not experience this before.

Well, what wattage is on the lamp?

It is a 70w bulb. And just to correct a typo, it is IRF830 Mosfet.

Yes it is quite strange. It seems like the Drain pin was the one heating up (breadboard melted around it). I really thought I found a solution with the if statement so this is disappointing. Could you explain what is meant by underdriven. Sort of learning all of this along the way.

@Imraan: are you doing 220V on a breadboard? I cannot advise on a circuit that works on the line voltage.

Yes unfortunately I'm using a breadboard because that's the only thing available to me. I'm hoping to take a drive down this week to an electronics store to try and get a circuit board. I was advised a breadboard should be fine for testing purposes and for what its worth I have managed to implement this project safely, apart from the incorrect fan behavior I was experiencing due to the zero cross.

Imraan, you have most definitely NOT build your circuit safely as to do so is impossible on a 'breadboard' when using 220 VAC.  The contacts on these boards are extremely poor not to mention that the separation between the metal contacts is inadequate.  Please read up on track separation for mains voltages on PCB's to get an idea of what is required.
The commonly used 0.1" pitch strip board is also unsuitable for mains voltages.