text:
Override #define statements in libraries
I'm using a library that, by default, wants to use Serial2 as the interface to a display, however, I'm working with an UNO which only has one serial interface, so the compile fails. I'm trying to use a SoftwareSerial instead, but I can't figure out how to override the #define statement in the library without editing the library.
I'm guessing since the software serial port isn't generated at compile time, I can't.
#include <SoftwareSerial.h>
#define nexSerial HMI
#include <Nextion.h>

SoftwareSerial HMI(8,9);

void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}

I haven't started writing code yet, can't get past the attempt to redirect the serial interface to a software serial.

You're allowed to modify the header file.  The version I looked at says
#define USE_SOFTWARE_SERIAL //Comment this line for use  HardwareSerial

...but I think he meant "comment this line out to use HardwareSerial".  Or conversely, "uncomment this line to use SoftwareSerial."
Then you just pass your SoftwareSerial instance into the Nextion constructor:
SoftwareSerial HMI( 8,9 );
Nextion nextion( HMI );

void setup()
{
   HMI.begin( 9600 ); // or whatever speed...

However, because you are using pins 8 & 9, I would strongly recommend using AltSoftSerial instead.  It is much more reliable and efficient.  MUCH.
You would have to modify the Nextion files to either (1) search and replace all occurrences of SoftwareSerial with AltSoftSerial, or (2) add a third choice to the author's #ifdef/#endif sections.  For example:
#define USE_SOFTWARE_SERIAL // uncomment this line to use SoftwareSerial
#define USE_ALTSOFT_SERIAL  // uncomment this line to use AltSoftSerial
                            // comment both above  to use HardwareSerial

#if defined(USE_SOFTWARE_SERIAL)
#include <SoftwareSerial.h>
#elsif definied(USE_ALT_SOFTSERIAL)
#include <AltSoftSerial.h>
#endif

class Nextion{
 private:
  void flushSerial();
#if defined(USE_SOFTWARE_SERIAL)
  SoftwareSerial *nextion;
#elsif defined(USE_ALTSOFT_SERIAL)
  AltSoftSerial *nextion;
#else
  HardwareSerial *nextion;
#endif

Do either one of those things in all files that refer to the Nextion serial member; Nextion.CPP certainly needs it.

Thank you. I'll have to go get the newest version of the library, as the one I have doesn't show a software serial option. I'll also look into AltSoftSerial, as I'm having trouble with baud rates above 19200.

You can't.
All you are doing in your code is providing a #define to the instance of the header file that is included in your sketch file. You have no way of modifying the instance that is included in the library's source files.

I was afraid of that. Fortunately, it looks like a new version of the library will work with software serial.


text:
Error on Uploading Program to ESP8266 via Foca v2.2 (USB to TTL Adapter)
BACKGROUND
To test the capability of uploading program to ESP8266,  I use an empty program with only a blank setup function and a blank loop function. The result showed me that there are a espcomm_sync error and a espcomm_open error. Any idea to solve this problem?

HARDWARE

PIN CONNECTION
  Foca v2.2 <-> ESP8266
        TXD <-> RXD
        RXD <-> TXD
        DTR <-> RST

Arduino UNO <-> ESP8266
        GND <-> GND
       3.3V <-> Vcc

PIN DIAGRAMS
Foca v2.2

ESP8266

ON LINUX UBUNTU 15.04

ON WINDOWS 10

REFERENCE

Bring IoT to Arduino, together [Getting Started] - http://www.arduinesp.com/getting-started

The link you provide describes 3 possible scenarios. None of them corresponds to your pin connections on foca. If problem persists after correcting the DTR and RST connections try to use the manual setup first.

@Personagem - Now I removed the connection RST <-> GPIO0 and got the same result in both windows and ubuntu but the uploading problem is still not solved.

by the comments I think you are not understanding correctly how to connect Reset and GPIO_0 of ESP. To set esp-01 into flash mode (to program) you need to set GPIO_0 Low (GND) and then also apply Low on RST ESP pin.
To debug the things and be certain that there is no hardware problem let just start by doing these connections:
Foca v2.2 <-> ESP =1
      TXD <-> RXD
      RXD <-> TXD
      GND <-> GND
  Arduino <-> ESP 01
     3.3V <-> 3.3V
     3.3V <-> CH_PD
     GND  <-> GND

Now, with a wire, connect GPIO_0 to ground. With another wire, briefly connect RST of the ground to make ESP reset. You should be now in flash mode. Remove the connection on GPIO_0 and make it float. Now upload the code.
Note: this is basically the option C on the link you provide. If you have some buttons you can make it too:

(source: arduinesp.com)
Now, does the code upload in Arduino IDE?
If the answer is still no, try to add a small capacitor between 3.3v and ground.
If the answer is yes, now you can move on and try the other options described in the link you provide. I recommend using the option A:

(source: arduinesp.com)
Any generic npn transistor should work

I had the same problem. I solved connecting GPIO0 to GND and connecting RST to GND a while after uploading and then leave it floating while uploading

source: Stack Exchange

license: 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/

sort: votes


text:
Arduino programming attiny13a
Hello I want to program an Attiny13a with Arduino code. I always have this error  when I add repository "no file board.txt" in path.
How to successfully configure IDE to able burn on it?
I use :
Link 1
And :
Link 2
But nothing changed .
I am using IDE Arduino v1.6.7.
Finally I import ATTiny13 (link) now these errors appear:
Board attiny13:avr:attiny13 doesn't define a 'build.board'
preference.Auto-set to: AVR_ATTINY13

Board attiny13:avr:attiny13at4 doesn't define a 'build.board' preference. Auto-set to: AVR_ATTINY13AT4

Board attiny13:avr:attiny13at9 doesn't define a 'build.board' preference. Auto-set to: AVR_ATTINY13AT9

Warning: platform.txt from core 'Attiny13' contains deprecated compiler.path={runtime.ide.path}/hardware/tools/avr/bin/, automatically converted to compiler.path={runtime.tools.avr-gcc.path}/bin/. Consider upgrading this core.

Warning: platform.txt from core 'Attiny13' contains deprecated tools.avrdude.cmd.path={runtime.ide.path}/hardware/tools/avr/bin/avrdude, automatically converted to tools.avrdude.cmd.path={path}/bin/avrdude. Consider upgrading this core.

Warning: platform.txt from core 'Attiny13' contains deprecated tools.avrdude.config.path={runtime.ide.path}/hardware/tools/avr/etc/avrdude.conf, automatically converted to tools.avrdude.config.path={path}/etc/avrdude.conf. Consider upgrading this core.

Warning: platform.txt from core 'Attiny13' contains deprecated recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{build.path}/{archive_file}" "{object_file}", automatically converted to recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{archive_file_path}" "{object_file}". Consider upgrading this core.

@Gerben Please, give him a break, he's non-native english speaker.

Could you please include the actual error message exactly as it was displayed in the IDE?

I want to apologize Gerben if my english is bad but i write it after 16h in work . I will try to edit post when i sleep a little.

@MichałGałkowski The "errors" (they're warnings) should not matter. It should still compile and upload.

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


text:
Control brightness of 20 watt street LED light using Arduino
I have searched google and I now know that if we change the resistance, we can change the brightness of an LED, but I was wondering how to change resistance by using a micro controller.

Normally you use PWM instead of messing with resistances. It's easier and more efficient.

There are I2C controlled resistors. But I know none that can handle 20W. Most likely a SSR (Solid State Relay) and PWM'ing would work but I don't know how good idea that is.

High power leds don't use resistors, but have special drivers that regulate the voltage going into the led. With streetlights these drivers also handle the AC-to-DC conversion. It's unlikely you can dim these externally.

There are LED drivers that have external regulation options but as OP asked about changing resistance with a microcontroller the answer would be with a I2C pot, but it's unsuitable for dimming a 20W LED.

Did you do a web search? "arduino pwm high power led driver" gives all the info you may need to answer this.
Here is a nice youtube clip, by Julian Ilett that explains how to do this: 60W High Power LED Driver with PWM #2 - Brightness Control.

Mikael, this is basically a link-only answer. Can you expand on it a bit please in case the link goes down?

The video is by Julian Ilett, who has a rather large collection of tutorials on YouTube, so hopefully the link won't go down.


text:
Arduino mega R17 led blink continuously
I have bought 10 Arduino Mega 2560 clones and all of them have the same problem. When I connect the to my PC I get a message that windows cannot recognize that device and the LED at the board in R17 blinks non stop. normally this led stops when the arduino is ready. Also in the Arduino IDE I don't see the port option enable.

Have you installed the drivers?

Yes because i have another arduino mega and a duemilanove and they work

Are they genuine Arduino?

No they are clones and the working one is also clone

You're on your own then. Who know what they might be doing... or even what they might be.

Do you know what the R17 led is for? so i can search for it?

I don't even know what an R17 LED is.

Let us continue this discussion in chat.

Nobody can help you. You have some unknown clone and we don't know what it is. Maybe start with editing your question to include exactly what it is you have bought. Only then can we begin to help you.

This is what i bought        https://www.hellasdigital.gr/electronics/boards/microcontrollers/atmega2560-16au-ch340g-mega-2560-r3-board-usb-cable-for-arduino/

You need to install CH340 drivers!

i have downloaded the drivers and also installed them but in the device manager i dont see it. Windows still sees the arduino as unrecognized

I think the LED you mean is the one marked L which is situated next to resistor R17 (if I can read it on that small image). That is connected to pin 13, and it blinks. It blinks when there is no sketch installed, and it blinks when the default Blink.ino sketch is installed. Either way it blinks until you tell it to do something else. The CH340 chips are next to useless. They kind of work sometimes if you're lucky. Then suddenly they will die out of the blue. They are not good.

The CH340 don't just die actually. Clones get bricked by the drivers. Plus Windows with it's drivers has always been bad. All my Nanos that have the same chips have been working just fine like two years already but under a linux distro always.

Majenko you are correct for the L i didnt see that and i thought it was the R17 resistor. So if i manage to make it work and upload a sketch to it and power it via DC power supply one day will it stop working or if i make a lot of sketch uploads? I want them in order to have 4-5 sensors on them and some push buttons in order to do basic functions

Once the sketch is uploaded the CH340 is not required. Therefore it should keep working. Making a lot of uploads is not a problem, unless you are talking about over 10,000 uploads.

The CH340 is very susceptible to static. They die. They are cheap, and many corners have been cut, including ESD protection and, most notably, drivers.

You need CH340G drivers. CH340G is a chip that basically replaces the usual ATMega 8U2/16U2 that is used for USB to serial interface. As CH340 cannot be reprogrammed it means that you can't emulate other USB devices with your arduino for example a keyboard.

You can download the drivers here.

i have downloaded them before and installed them. Also my concern is that the boot led is not stoping to flash even though  i power it from DC power supply and not USB.

Boot LED? There are three LEDs. The RX, the TX, power and the manual controlled one that blinks on reset and with certain code.
I am also 100% sure you have installed the drivers wrong if Device Manager can't detect the device.

i know the TX and RX leds also in the MEGA there are 2 more leds that blink when you boot it and when it boots the stay ON. In my version now i have one led flashing non stop.

also in the drivers installation process i got the message drivers installed correctly so i dont know why windows still not recognize it. I have Windows 10 64bit

The two more LEDs are power (ON) and LED (L). No boot LED; use the right terms that way people can understand you a bit better. Just a friendly reminder.
Have you rebooted your machine fully? Google how to do that as I don't have Windows, pressing restart won't do it.
Also what pops up if you disconnect and reconnect the Arduino to your PC, does a driver installation window pop up?

Sorry for wrong terms but i am new to the arduino world and i dont know a lot. yes i rebooted it now removed the battery for total reboot again nothing. Also what is that flashing led that blink non stop? next to it is another led that is on permanent. The TX and RX leds are not flasing at all and the are located above those leds that i told you

Usually unprogrammed Arduinos have a Blink sketch uploaded to them as default (just blinking a led). You have to upload something new to it for it to stop but Windows can't detect the CH340G chip, so I'd suggest you'd uninstall the drivers, unplug all Arduinos before and when the uninstall is completed, reboot the machine again. Now reinstall the drivers as it was told and reconnect the Arduino. Now open the "Searching for drivers" window and wait for it to complete, make sure you have internet connection.

Let us continue this discussion in chat.

also i checked my other working arduino mega which has also the CH340G chip so the drivers are in my PC. :S

In device manager when i connect one of the faulty boards i see device descriptor request failed but when i connect the working one i see USB CH340 SERIAL(COM3)

@AgisSoleas Do not connect a single new CH340 based board. It might be that the driver is bricking them. Download an Ubuntu Live ISO and try Arduino IDE there to see if it's actually the drivers.


text:
How should I use an optocoupler to control a 12Vcc load with Arduino?
I am developing a project to operate a load of about 12Vdc.  I considered the use of an optocoupler to avoid mechanical wear of a relay.  The design I have tried is this:

This configuration seems to work OK, but I am a biologist and this is my first attempt with an opto of any kind!!!!  I had a lot of trouble with the transistor until I changed to a PNP.  Is this right?  Can it be done with an NPN or even without any transistor at all?

If your load draws a small amount of current (less than about 30 mA current), your 4N35 optocoupler could drive the load directly on 12 volts.
Ignore my use of 4N28 (similar to 4N35). It is the symbol that I had.
It appears that your PNP transistor circuit is something like this :

The PNP transistor circuit can work well depending upon your load current.  The PNP circuit has some problems with the transistor not turning on fully (and won't be described here).  You may not get the full 12 volts to your Load. But, if it works for your load, then be happy with the PNP circuit.
The circuit below is for a NPN transistor circuit  :

Using the NPN circuit allows (in this case) for the transistor to turn on fully, leaving almost the full 12 volts for your Load.
Important Note :  The NPN transistor circuit produces an output that is the LOGIC opposite of the PNP circuit.   Notice that for the PNP circuit, a logic 1 to the input of the optocoupler (LED on) turns on power to your Load.
On the NPN circuit, a logic zero (0) to the optocoupler LED is required to turn on your Load.
Another variation of the circuit is below, and does NOT have the reverse logic situation.  In other words, it will behave like the PNP circuit. When LED is on, the Load will be on  :

You can experiment with the value of R1 in the NPN circuits. You could experiment with lower value, down to 1K (1000 ohms) if you are using a power transistor to drive high current loads.

Very informative and useful solution to my question Marla.  Thank you very much.


text:
Data changes when working with classes
When I pass an array, and it's len to the constructor of a class. I store the length, and access it later, it's value changes, seemingly at random.
#include "Arduino.h"

#define NUMSENSORS 2
const byte dataPins[] = {A5, A4};

class B {
    public:
        B(byte pin) { _pin = pin; }
        byte getPin() { return _pin; }
    private:
        byte _pin;
};

class A {
    public:
        A(const byte sensorPins[], int len) {
            Serial.print("provided len is: ");
            Serial.println(len);
            _len = len;
            Serial.print("Stored len is: ");
            Serial.println(_len);
            for (int i=0; i<len; i++) { myBarray[i] = new B(sensorPins[i]); }
        }
        B* myBarray[];
        int _len;
        void printLen() {
            Serial.print("Length is: ");
            Serial.println(_len);
        }
};

void setup() {
    Serial.begin(115200);
    A test(dataPins, NUMSENSORS);
    for (uint8_t i=0; i<10; i++) {
        test.printLen();
        delay(100);
    }
}

void loop() {
}

The value of len is fine in the constructor,  but is different when I call it in the function "getLen".
I feel as though it has something to do with pointers. Because if I comment out the for loop in the constructor of A, the value is correct.
Any help would be greatly appreciated, thanks in advance.

B* myBarray[]; has no size, and no memory allocated to it. Where do you think you are copying the data to?

I  thought that the memory would be allocated when I call the new B(sensorPins[i])... am I wrong? And why would that affect the value of A::_len in the later call?

No, B is allocated when you call new B(). The array is not allocated - ever - so it resides at address 0. Any writes to it will overwrite any other variables that have been allocated in that area, such as A.

Okay, fair enough. So how would I fix it? Sorry, but I am fairly new to c++

Either pre-allocate it with a fixed (maximum) size, or use malloc() to allocate the right amount of bytes to the array - that is, _len * sizeof(B) bytes.

Forcing a max length of the array worked! Thanks a lot. I'm going to have to look at malloc () to figure it out. so I can dynamically allocate memory.

There seems to be something missing here. What is the intention of the A and B class? They actually do no add anything as all the info you are using is in the dataPins vector and NUMSENSORS.

Let us do this with a template class and avoid malloc, etc.
#define membersof(x) (sizeof(x) / sizeof(x[0]))

const byte dataPins[] = { A5, A4 };

class B {
public:
  byte getPin() { return (_pin); }
  void setPin(byte pin) { _pin = pin; }
private:
  byte _pin;
};

template<unsigned len>
class A {
public:
  A(const byte sensorPins[]) {
    for (unsigned i = 0; i < len; i++)
      _vec[i].setPin(sensorPins[i]);
  }
  unsigned getLen() { return (len); }
  B* getB(unsigned ix) { return (ix < len ? &_vec[ix] : NULL); }

private:
  B _vec[len];
};

void setup() {
  Serial.begin(115200);
  A<membersof(dataPins)> test(dataPins);
  unsigned len = test.getLen();
  Serial.print(F("test.getLen()="));
  Serial.println(len);
  for (unsigned i = 0; i < len; i++) {
    B* bp = test.getB(i);
    Serial.print(F("test::B["));
    Serial.print(i);
    Serial.print(F("].getPin()="));
    Serial.println(bp->getPin());
  }
}

void loop() {
}

Cheers!


text:
How can I pass a char array as the parameter to a function?
I am creating a menu for adjusting system variables.
The menu is made up of pointers like so:
char* options4[] = {"hMin1", "hMax1", "refr1", "fSpeed1"};

I want to pass the selected string as the parameter for an 'adjust' function for use in some conditional logic and for display on a HCMAX7219 7 segment display. Here's what I've got:
int option = 0;
float variable = 82.0;

if(Serial.available() > 0) {
  key = Serial.read();
  if(key == back) {
    return;
  } else if(key == fwd) {
    float newVar = adjust(String(options4[option%4]), variable);
  } else if(key == down) {
    option++;
  } else if(key == up) {
    option--;
  }
}

float adjust(char* str, float var) {
  ...do some stuff...
  display.print7Seg(str, 8);
  EDIT: forgot this call..
  display.print7Seg(var, 1, 4);
  ...do stuff to var...
  return var;
}

The library function takes (char[] TextString, unsigned int Offset) as it's parameters.
EDIT: the library also has functions print7Seg(long number, byte decimalPlace, unsigned int Offset) and print7Seg(long number, unsigned int Offset)
Now I'm new to pointers, but I can see that I am passing a pointer to my adjust function, and expecting it to dig out a char array from memory. I can't see any problems with that, though I may be missing something. When I try to compile, the IDE just crashes with exit status 84; so no debug info.
Am I going about this the wrong way?

There are one or two things missing in your code. Where is setup() and loop()? Or is it just a snippet?
But answer to the question first. This is not right:
newVar = adjust(String(options4[option%4]), variable);

Should be:
newVar = adjust(options4[option%4], variable);

You want to index the vector of strings and pass one of the elements to the function.
Cheers!

It is just a snippet yeah. The full code is about 300 lines so thought I'd try to keep it brief. There are 12 variables to adjust so a generic function is what I'm aiming for.
You're absolutely right about the typecasting on the function call, I didn't spot that.
I've commented that line out for compilation, as I'm yet to think of a way of assigning the variable, so that's not the cause.
Thanks for the spot though.

Do you mean the cause of the IDE crash?

Yeah, the cause of the IDE crash could be linked to a problem in the code.

Then you will have to post all the code and tell us about the Arduino IDE version, board, etc. Have you turned on the "Show verbose output during:" in the IDE Preferences? Collect as much info as possible before the crash of the IDE.

And I would also suggest changing the title of this post??

I think the cause of the crash was an attempt by the library to treat a float as a long. I don't know a whole lot about the compilation process, but changing this seems to have solved the problem.. it compiles at least.

Let us continue this discussion in chat.

Ah .. ok I've just figured it out..
This is a legitimate way to pass char arrays to functions.
The original char* options4[] array is just an array of pointers to char arrays in memory, so passing one of these pointers to a function works fine.
The culprite was actually my float parameter, I was trying to make a library function call with a float to this function: print7Seg(long number, byte decimalPlace, unsigned int Offset).
This is what was causing the IDE to crash.
I got around it by having an int version of each of the variables I need to set. Then typecasting and dividing by a float to get variables that will be used in the main program. like so:
int hMin1Int = 820;
float hMin1 = (float)hMin1Int / 10.0;
int hMax1Int = 880;
float hMax1 = (float)hMax1Int / 10.0;
int refr1 = 30; //minutes
int fSpeed1 = 128;

I was then able to change my function to accept an int, the library function, so far, seems to be ok treating an int as a long, but if not I can just make all my ints longs:
int adjust(char* str, int var) {
  ...do some stuff...
  display.print7Seg(str, 8);
  display.print7Seg(var, 1, 4);
  ...do stuff to var...
  return var;
}

I was asking the wrong question!
Still I hope this will be useful to someone, so I will leave it up. Thanks for the response Mikael Patel.
Moral of the story, know your library.


text:
Setup J-K Flip-flop for logging on Arduino RESET
There are two events I plan to log; using no switches or requiring manual input of some kind.  One of the events is whenever the Arduino Serial Monitor is opened; the other, is when external event occurs that causes a Arduino RESET.  Second event produces a LOW pulse used to CLK the J-K Flip-flop.  digitalRead of J-K Flip-flop Q; using a conditional statement, if Q = HIGH log to SD Card as event1 date/time stamp else log to SD Card as event2 date/time stamp.  I need the J-K Output Q to be STORED thru the Arduino RESET, so Q can be read.
After reading Q, will need to clear Q; plan to do this from running sketch with a DigitalWrite
74HC73 is the chip I plan to use; it is triggered with a negative going CLK.
What needs to happen with the J and K inputs?  Will this work in toggle mode; with both J and K tried to +5 volts?

I am only looking to log when a LOW condition at Q output.  When I open the Arduino Serial Monitor with the way the 74HC73 is wired now, it immediately toggles, need to HOLD the status of Q until the J-K Flip-flop is reset.  Work finished so far:  http://tinyurl.com/jkflipfop includes testing code and wiring diagram.

Rather than having events that set 1Q or 2Q, consider having the external events take 1R\ or 2R\ low, to reset 1Q or 2Q.  When your sketch starts up, it would read 1Q and 2Q.  If one or the other is low, its event occurred and you can log it.  Then the sketch sets both Q's by dropping the CP lines with J's wired high and K's wired low.  You'd use three I/O pins: two for reading 1Q and 2Q, one for strobing the CP lines to set the Q's after reading them.
Arduino AVR pins default to inputs on Reset so the Arduino can reset without affecting the 74HC73's state.  A 10 to 20KΩ resistor to passively pull the CP lines high is reasonable.
Edit: Note, 1R\ and 2R\ operate asynchronously, and are independent of clock inputs.  This leads to simpler interface requirements for your external events.  However, it may also increase sensitivity to electrical noise; if your system is in a noisy environment a different approach might be needed.

Using with an external watchdog circuit that sends a  LOW pulse to reset the Arduino; this is what I am trying to aquire by reading Q.  The reading of Q takes place in Setup portion of sketch.  Okay, will read 1Q and 2Q, external event to 1R and strobe CP.  Can I use the strobing from input of the external, watchdog?  Are there any specific requirements for strobe at CP?

@William, see edit.  CP is relevant when your program is setting 1Q, 2Q after reading them.  CP is not relevant to 1R, 2R\ lines -- they operate asynchronously.  At 5V and 25℃, nQ goes low within 15 ns of nR going low; see Table 7 in nxp specsheet.

My resolution:

This is the code for logging Arduino RESET and WDT RESET.  Plus the code for resetting the J-K Flip-Flop.
 /////////////// J-K Flip-Flop 74HC73,  Status of Q Monitor ///////////////////////////////////////

 delay(10);

 getDateTime();

 if(value == 1)
 {

      //Creates an entry in "Server.txt" for every RESET cause by "Dual Watchdog Timer"
      SdFile serverFile;
      serverFile.open("Server.txt", O_RDWR | O_CREAT | O_APPEND);

      if (!serverFile.isOpen()) error("Watchdog Start Server");

      serverFile.println("Watchdog RESET:  " + dtStamp);
      serverFile.close();
      Serial.print("Watchdog RESET  ");
      Serial.println(dtStamp + "  ");
      Serial.println("Listening for connections...  ");
      //Serial.println(value);

 }
 else
 {

      //Creates an entry in "Server.txt" for every RESET; caused by opening Serial Monitor
      SdFile serverFile;
      serverFile.open("Server.txt", O_RDWR | O_CREAT | O_APPEND);

      if (!serverFile.isOpen()) error("Manual Start Server");

      serverFile.println("Manual RESET:  " + dtStamp);
      serverFile.close();
      Serial.print("Manual RESET  ");
      Serial.println(dtStamp + "  ");
      Serial.println("Listening for connections...  ");
      //Serial.println(value);

 }
 //Sends LOW to RESET the 74HCT73, JK Flip-flop
 digitalWrite(RESET, LOW);
 delay(10);
 digitalWrite(RESET, HIGH);
 delay(10);
 digitalWrite(RESET, LOW);

///////////////////////////////////////////////////////////////////////////////////////////////
William Lucid 12/22/2016


text:
Playing music with an Arduino
Good evening!
I am quite new with Arduino but not in programming. Still, I have already done some programs with few leds.
I was just wandering how to create a circuit and a program that would play the "happy birthday" song with the following materials:

I have a breadbord and some wires.
Else, do you have some links where I could start learning how to play music with it?

You are in luck: http://forum.arduino.cc/index.php?topic=178460.0

God! I'm trying it right away and send feedbacks soon!

Thanks to Mikael Patel for suggesting that link (your Google-Fu must be strong!).
I am pasting the code below so that this answer survives any possible future deletion of the read-only part of the Arduino Forum.
//ONG LIT YIT 2013-07-20
//This following code plays happy birthday melody on Arduino
//Put Piezo Buzzer on GDN and 9 (Positive and negative are reversible)
//this project requires a Piezo Buzzer and

// an Arduino board and
//jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

const int speakerPin = 9;
const int LENGTH = 28; // the number of notes
const char notes[LENGTH + 1] = "GGAGcB GGAGdc GGxecBA yyecdc";
const int beats[LENGTH] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 16 };
const int tempo = 150;

void playTone(int tone, int duration)
  {
  for (long i = 0; i < duration * 1000L; i += tone * 2)
    {
    digitalWrite(speakerPin, HIGH);
    delayMicroseconds(tone);
    digitalWrite(speakerPin, LOW);
    delayMicroseconds(tone);
    }
  } // end of playTone

void playNote(const char note, const int duration)
  {
  char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',
                  'c', 'd', 'e', 'f', 'g', 'a', 'b',
                  'x', 'y'
                 };
  const int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,
                  956,  834,  765,  593,  468,  346,  224,
                  655 , 715
                };
  const int SPEE = 5;

  // play the tone corresponding to the note name
  for (int i = 0; i < 17; i++)
    {
    if (names[i] == note) {
      int newduration = duration / SPEE;
      playTone(tones[i], newduration);
    }
  }
} // end of playNote

void setup()
  {
  pinMode(speakerPin, OUTPUT);
  } // end of setup

void loop()
  {
  for (int i = 0; i < LENGTH; i++)
    {
    if (notes[i] == ' ')
      {
      delay(beats[i] * tempo); // rest
      }
    else
    {
      playNote(notes[i], beats[i] * tempo);
    }

    // pause between notes
    delay(tempo);
  }
} // end of loop

I also cleaned up the code a bit.


text:
Maintaining Arduino on Ubuntu 14.04
I used to use Arduino on Windows but I changed to Linux last week and I was wondering how to have a maintained version of the Arduino terminal:
Indeed, I'm not sure my version is quite recent:

The icon seems to have lived ages without a little lifting...
Maybe I'm wrong but it seems so when I open the "Tools" option for instance...
Furthermore I tried to copy and paste this code:
//ONG LIT YIT 2013-07-20
//This following code plays happy birthday melody on Arduino
//Put Piezo Buzzer on GDN and 9 (Positive and negative are reversible)
//this project requires a Piezo Buzzer and

// an Arduino board and

//jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

//HAVE FUN

//this project requires a Piezo Buzzer and

// an Arduino board and

//jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

//HAVE FUN

int speakerPin = 9;

int length = 28; // the number of notes

char notes[] = "GGAGcB GGAGdc GGxecBA yyecdc";

int beats[] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8,8, 16, 1, 2,2,8,8,8,8,16, 1,2,2,8,8,8,16 };

int tempo = 150;

void playTone(int tone, int duration) {

for (long i = 0; i < duration * 1000L; i += tone * 2) {

   digitalWrite(speakerPin, HIGH);

   delayMicroseconds(tone);

   digitalWrite(speakerPin, LOW);

   delayMicroseconds(tone);

}

}

void playNote(char note, int duration) {

char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',

                 'c', 'd', 'e', 'f', 'g', 'a', 'b',

                 'x', 'y' };

int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,

                 956,  834,  765,  593,  468,  346,  224,

                 655 , 715 };

int SPEE = 5;

// play the tone corresponding to the note name

for (int i = 0; i < 17; i++) {

   if (names[i] == note) {
    int newduration = duration/SPEE;
     playTone(tones[i], newduration);

   }

}

}

void setup() {

pinMode(speakerPin, OUTPUT);

}

void loop() {

for (int i = 0; i < length; i++) {

   if (notes[i] == ' ') {

     delay(beats[i] * tempo); // rest

   } else {

     playNote(notes[i], beats[i] * tempo);

   }

   // pause between notes

   delay(tempo);

}

}

And not all of it appeared in the Arduino terminal.

That is a very old version. Please download from the Arduino Software page https://www.arduino.cc/en/Main/Software. I normally install to ~/opt/arduino-x.y.z. Run the arduino binary from that directory.

Okay! Thanks! How do I install it to  ~/opt/arduino-x.y.z. ?

Go to the download page. Click on the Linux version you require (32 or 64 bit). Wait for the download to complete and the Archive Manager is started. Push extract and select where you want to "install" it.

Basically you un-archive it as Mikael Patel said, and then just double-click the Arduino icon to execute it. You may need to fiddle with permissions or settings or it might just open it in a text editor.

Just mark the arduino file as executable and launch it through the terminal. (cd into the directory and launch it) Then lock it to the sidebar. Next time you can just easily launch latest Arduino IDE from the sidebar.

FYI, the reason Ubuntu packages such an old version of the IDE is that the Arduino licensing needs to be updated/clarified. As is, Ubuntu cannot legally distribute the latest Arduino version: https://github.com/arduino/Arduino/pull/2703 The rest of the work to include it in the Ubuntu repository is done, so there's nothing more they can do about it.

If you want to get maintained (automatically updated) version of Arduino IDE then you install if from a package repository with its dependencies e.g. using apt-get:
sudo apt-get update
sudo apt-get install arduino arduino-core

However, this way you get a very old version (currently 1.0.5). Obviously, it is not updated too often if at all.
If you already installed from the package repository via apt-get you can uninstall the package and its dependencies like this:
sudo apt-get remove arduino arduino-core
sudo apt-get autoremove

Better way is to download and install Arduino IDE yourself. This way Arduino software won't automatically be updated, so you should check Arduino website every now and then and download a new version if one is available.
Open a terminal window (e.g. by pressing CTRL-ALT-T), and run uname -m to check if you are running 32 bit or 64 bit platform:
uname -m

See output:
x86_64 ==> 64-bit kernel
i686   ==> 32-bit kernel

Go to Arduino Download page on Download the Arduino Software and download the 32 bit or 64 bit version, depending on the Ubuntu version installed on your computer.
In a terminal window extract the package and move it to your preferred location, e.g. /opt. You need sudo rights to move it to /opt. Finally, run the install script if you want to start the IDE graphically (adds desktop icon, MIME type, default application for .ino). See the example commands below for installing the latest 32 bit version as of the time of writing to /opt.
cd ~/Downloads
tar xf arduino-1.6.7-linux32.tar.xz
sudo mv arduino-1.6.7 /opt
/opt/arduino-1.6.7/install.sh

You can also start the IDE from the terminal:
/opt/arduino-1.6.7/arduino

Why into /opt? Why not just keep it under /home and launch it there?

@Avamander It makes sense if you aren't the only user of the computer. If you are the one and only user of the Linux box then keeping it under your home dir if just fine.


text:
Arduino Audio Shield Problems
I recently bought a Velleman KA02 Arduino Audio Shield (http://www.velleman.co.uk/contents/en-uk/p579_ka02.html), which uses an ISD1760PY audio chip and soldered it together. The first time I fired it up, it worked fine, I had freshly soldered it together. But from the next time up to now, if I press any button but the reset button, the onboard LED blinks 7 times and it doesn't record or do anything. I checked the solder joints and nothing fell out and I also checked the ISD1760PY datasheet but found nothing about my problem. Is there a way to fix this and why it it happening? Please note that I am not controlling the shield with SPI or with the Arduino.
This question was put on hold in the EE section so I an posting it here because the reason was that it has something to do with Arduino.

Look at page 35 of winbond datasheet.
If the LED is blinking 7 times either the chip is in isp mode or in an unstated mode. This can happen after power off during erase function.
I held erase button for about 20 seconds and after that I was able to record messages.


text:
Daikin Remote ARC
I started off attempting to use the  IRRemote    Library and a VS1838B Sensor to capture the Daikin air condition signal.  I’ve read about the timing and in all honesty, I don’t think I can do it on my own so I looked to find the code others had created and adapt it to my own, trying their remote controls first thinking Daikin may only have a few sets.
I can’t confirm that will work as yet because I’ve only been able to find the code below but I’m not quite sure what is the best practice for ripping (stripping out the parts I don’t need) it apart.
When I attempted to capture the IR codes, most of the time I get nothing at all.  My stereo remote is immediate displayed though.
Now the good news,  based on Harizanov’s work, he’s mapped the ARC533 Remote,  which is the same model that I have.

My Model : FTM18NV2S
Remote:  ARC533A55
Daikin - Smash

NV2S  (On the Inverter)

Remote:  Doesn’t say anything of use
15-Series Wall Mount

Code Here: Control Daikin air conditioner over the Internet
Code here: Github: mharizanov/Daikin-AC-remote-control-over-the-Internet
Can anyone provide a recommendation on how I could trim up this code to try it?

I'm not sure if I can just use the irsend.SendRAW options for this application but I figured since the ARC533 was already mapped out, why not use that.  This is my first attempt at anything like this so I'm a bit out of my realm of understand.
Appreciate any help.
Side note: I have been testing with a stereo remote and have copied the stereo remote On/Off as raw and can send it back, except the timing seems off because it flashes way too slow.

Anyone at all?    Got no idea how to proceed

I had a problem with my daikin A/C. After spending lot of time trying to fix this problem, i found out that is is using long ir codes which is hard to simulate using the IRSenderBitBang (38 kHz). After lot of fustation I used irdevkit.com. It has a ir decoder built in and I can control it using ESP8266. Works well


text:
Are there flexible pressure sensors for Arduino that can measure forces of at least 600 lbs?
I'm in need of flexible pressure sensors that can read how much force is exerted on someone's foot while running (these sensors would be placed inside the shoe). Since pressure can often be three times the weight of the person, I need something fairly strong. Are there fairly cheap sensors that are available or hacks that could do the same thing?
Thanks!

As you are presumably measuring changing (dynamic) loads, you could consider a piezo electric sensor.
At the simplest, use a piezo element usually sold as a buzzer (make sure you get the plain element with no electronics included, some 'buzzers' also have drive circuitry).

That will give you a voltage pulse proportional to applied pressure, which might give you the precision that you need, and is very small and light to insert in a shoe.
See this question for a similar solution (and the above image!)

This could be a great method! Thanks for pointing this out, I will need to try this.

Sensors such as you describe are usually called "Load Cell".
At the 600 pound weight, I haven't found any "flexible" load cells. A sensor would have to be quite robust.
Flexible might not be the best answer.
This load cell page has quite a range of load cells, several thousand pounds, also not very inexpensive.
This might be difficult to install in running shoes :

... unless you have big futs.

Thank you! Hopefully I can find one that's thin enough that I can just cut a small portion out of the shoe. I heard that you can change how sensitive some of these sensors are so that they can measure up to 500 lbs. Check out what Im talking about here: http://forum.arduino.cc/index.php?topic=304657.0


text:
Detect how long a push button is being pressed?
I would like to detect how long the state on/off is going on for. Is there a way to do that? I would like to do that for two reasons:

I would be able to make a very simple toggle button. (I know about the other way with the old value and new value).
I can make the button being pressed for a long time be like a return button.

Anyone got any ideas?

You would need to use millis()

This needs a combination of patterns.
First, the button pin needs to be debounced. This can be done with the "blink-without-delay"-pattern where the button pin is sampled with a low period (40 ms in the example code below).
Second, a simple state-machine is needed to keep track of the button state but also if the return button action function, doReturnButton(), has already been called.
The button is assumed to be connected from GND to pin4. The button action function, doButton(), is called when the button is pushed (goes LOW).
const int buttonPin = 4;
const unsigned long debounceInterval = 40;
const unsigned long returnInverval = 400;
bool buttonState = true;
bool returnButtonState = false;
unsigned long buttonDownMillis = 0L;

void doButton()
{
  Serial.print(buttonDownMillis);
  Serial.println(F(":doButton"));
}

void doReturnButton()
{
  Serial.print(buttonDownMillis);
  Serial.println(F(":doReturnButton"));
}

void setup()
{
  Serial.begin(57600);
  while (!Serial);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
  unsigned long currentMillis = millis();
  static unsigned long previousMillis = 0L;

  // Check if it is time to sample the button pin
  if (currentMillis - previousMillis >= debounceInterval) {
    previousMillis = currentMillis;

    // Did the button change
    if (digitalRead(buttonPin) != buttonState) {
      buttonState = !buttonState;

      // Was the button released
      if (buttonState) {
        returnButtonState = false;
      }

      // Was the button pushed
      else {
        buttonDownMillis = currentMillis;
        returnButtonState = true;
        doButton();
      }
    }

    // Check if button was pushed and time for return action
    else if (returnButtonState) {
      if (currentMillis - buttonDownMillis >= returnInverval) {
        returnButtonState = false;
        doReturnButton();
      }
    }
  }
}

What does the code do?

It samples the button pin with a debounce interval.
If the button state changes:
a. High to Low it calls the doButton() function and captures a timestamp. It also allows detect of return time interval.
b. Low to High. Return time interval is not allowed any more.
It checks if the return time interval has elapsed and if so calls the doReturnButton() function. The detect is then not allowed any more.

The doButton() function is called when the button is pushed (transition high to low), only once. The doReturnButton() function is called if the return time limit exceeds and the button is still low. Both are only called once per push (transition high to low).
To avoid the multiple transitions that occur when a button is pushed a debounce time period is used. The can also be done in hardware with a RC-circuit.
With some abstraction it could be rewritten as:
#include <Timemark.h>

Timemark debounce(40);
Timemark buttonHold(400);

const int buttonPin = 4;
bool buttonState;

void doButton()
{
  Serial.println(F("doButton"));
}

void doReturnButton()
{
  Serial.println(F("doReturnButton"));
}

void setup()
{
  Serial.begin(9600);
  while (!Serial);
  Serial.println(F("started"));
  pinMode(buttonPin, INPUT_PULLUP);
  buttonState = digitalRead(buttonPin);
  debounce.start();
}

void loop()
{
  if (debounce.expired()) {
    bool currentState = digitalRead(buttonPin);
    if (currentState != buttonState) {
      buttonState = currentState;
      if (buttonState) {
        if (buttonHold.expired())
          doReturnButton();
        else
          doButton();
        buttonHold.stop();
      }
      else {
        buttonHold.start();
      }
    }
  }
}

This also demonstrates the callback on the release of the button. The Timemark class hides all the time intervals, expire calculations, etc.
Cheers!

Isn't this just making a toggle button?

It calls doButton when the button is pushed and doReturnButton if the button is still pressed after a time limit.

Ah sorry I just got to understand the code better hang on.

I am genuinely sorry but can you please explain each part of the code? it would really help me understand it as well as broaden my knowledge of arduino.

On a long press, you will doButton() and doReturnButton(). I do not thing this is what the OP wants, although the question is not clear on this regard.

I avoided that as it actually adds some complexity to the "state machine". The "callback" has to be delayed for the return button interval. From an UI point of view the button feedback becomes "sluggish". It is a bit like mouse click and double click. You get both events and the application has to add logic on top of that. But it is a good point!

You could get a slightly more responsive UI – and not really more complicated – by calling the “short press” callback on the button release event: that's when you know it was actually a short press.

I am so sorry. For some reason, I did not get the notification of the comments and that the answer changed. I believe this is what I was looking for. Thanks!

I've just seen your updated answer with a Timer class. This would certainly provide a terrible user experience. If you tell the user that, for performing some action, a long press is needed, he will typically press the button and hold it down until he sees the action is taken. But your code waits for the user to release the button... which leads to a dead lock. I've previously commented that the release event is the best time to fire the “short press” callback, but that does not apply to the “long press”.

@EdgarBonet Please feel free to edit the code. The idea was to illustrate different approaches not the ultimate correct version. The last approach was callback on release which what typical GUI events click/doubleClick do. Other GUI events are mouseDown and mouseUp. But again I can only agree that this is not the perfect user experience for push buttons.

Note the time the switch is pressed (with millis())
Note the time the switch was released.
When the switch is released calculate the difference. If it is a "long" time do one thing, otherwise do something else.

But won't millis() just detect how long the program was running?

@Jack Think about it. You're not looking at millis() directly, but at the difference between two consecutive calls.


text:
Should millis() be stored in a variable once each loop, or called for every reference?
When comparing the value of millis() numerous times per loop(), are there reasons for/against storing it in a variable once at the top of loop(), v.s.  calling millis() each time?
The most basic example code "Blink Without Delay" is written as such:
void loop() {
  //...
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // Do stuff
  }
}

I don't really she why the example code above bothers storing millis() in a variable "currentMillis" at all. (I realize that in such a simple program, there would be no noticeable difference.)
I imagine that if I use a variable, the longer the duration of loop(), and the further down my use of the "currentMillis" variable, the more deviated the stored value will be.
I'm wondering the other ramifications of either method as well.
Does calling millis() directly hog resources of any sort? If not, I imagine it would be better to not use a variable, so as to get a more accurate time value and save a bit of memory.

Personally I'd save it in a variable if I had to call it more than once. That's because I don't want to call functions more times than strictly needed (the overhead is higher) and because I want that the loop is executed as if it happened "instantaneously". I mean, if you have if (millis() > interval) do_something; a_function_that_takes_10ms(); if (millis() > interval) do_something_else; I'd like the do_something_else to be executed always after do_something. If I store the millis value, this is correct, otherwise who knows..

As @frarugi87 may be implying above but worth stating explicitly, millis() does overflow (after about 50 days) and calling it repeatedly will on occasion end up with a lower value later in the program.

The primary downside to calling a function each time is that it may take more CPU cycles to complete the overall loop. The difference in CPU cycles, if any, depends on the actual implementation of the function and how the compiler optimises the call. For low-CPU sketches, this difference is probably unnoticeable.
Generally speaking, it is good programming practice to avoid calling a function more times than is necessary. Really the function should be called directly only if you have reasons to believe, based on desired timing and procedure order, that using the same return value in multiple places could create problems. In the example sketch given, there would be almost no functional difference between using a variable or calling the function inline.
Another advantage to using a variable is that you can give it a name that makes the code clearer to understand. In the example given, the relationship between currentMillis and previousMillis is very clear. In the case where a function returns a more complex object, such as a class or structure instance, using a variable (of the appropriate type) can be really useful since this would allow multiple members of the returned data to be accessed without calling the function multiple times. In fact, even in the given example, the function would have to be called twice since currentMillis appears twice in the loop.
As far as memory goes, an unsigned long uses very little.


text:
21 Servo on Mega?
I want to use 21 servo (SG5010) motors using Mega board. Is it possible to do this?
A possibility is all the servos will be operating at the same time, with average load of ~3.5 KG, and each using 1A, so 21 servos will use 21A.
Will be able to supply power? If yes then how do I go about it?

There is a servo/sensor shield for the Arduino Mega that can control up to 54 servos. This shield will only fit the Mega, unlike the usual 14 servo Arduino shield, which is shaped to fit most Arduino boards.

Here is an easier to view diagram:

It is possible, and advisable, to supply power via the screw terminals from an external power source, rather than use the Arduino's own power. Even just one servo can have difficulty in working from the Arduino's on board power supply, especially if just using USB to power the Arduino. However, even with the use of an external power source powering the shield, I have my doubts as to whether the shield could support 21A without burning out. Someone may be able to clarify this.
You may find this page, Servo Shield, useful:

MEGA Sensor Shield
The Arduino MEGA has many more I/O pins (54 Digital pins and 16 Analog
  pins)than a standard Arduino. This shield also has connectors
  specifically for some external devices like an SD Card, Radio
  communications (Bluetooth and others). It also has an option to power
  the "V" pins on all the Digital I/O 3-pin groups from an external
  power supply instead of the Arduino +5V. This is good for large
  numbers of servos etc. The "Analog" 3-pin groups still use the Arduino
  +5V which is better from an electrical noise perspective.
This version has two options of +5V supply to all the "V" pins:

Jumper on: +5 comes
  from the Arduino. Should be limited to about 300 ma
Jumper off: +5 (or
  other appropriate voltage) comes from an external supply connected to
  the blue terminal strip. External power Ground must also be connected
  to the blue terminal strip.

Using an external supply allows more current than the Arduino or Mega
  can supply, such as current for control of many servos or relays, and
  other attached devices. Usually this is +5V because most external
  devices require it. It is possible to use +6 volts if ALL the attached
  devices are the same such as Servos with that rating.

The Mega board will not be able to supply that much current, no. If you consult the schematic, you will see that the 5V regulator is rated for a maximum current of 800mA.
A computer PSU would be an appropriate power supply (a typical 350W PSU will happily supply >30A on the 5V rail). Be aware that some PSUs have a minimum load; you may need to add a power resistor or other load.
Also note that if you want individual control of all the servos, the ATmega1280 only has 16 PWM outputs (IIRC), so you would need software PWM or an external PWM IC.

As for the power supply, I agree with you. But I really hope the OP wasn't thinking of attaching them to the arduino power supply, was he? As for the PWM, the serial library should not use the PWM pins (I'm not really sure about it). Anyway, they explicitely say here that The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega.

frarugi87: I was thinking in terms of timers on the m1280 (although the Mega only has 15 "official" PWM outputs, I think), but yes, the Servo library provides software PWM and can handle up to 48 servos.

Yes, also because using the hardware PWM is inefficient in this case (the default PWM resolution is 8bit and the servos require a signal between 1 and 2ms every 20ms, so you would end up with a servo using only values between 12 and 24 for the positioning (and so you would be able to set a servo position to just 12 discrete positions)


text:
ATmega32U4 (Leonardo/Pro Micro) bootloader, 8K rather than 4K?
Recently hit the dreaded 0x7000 / 28k~ AVRDUDE+LUFA limit.  It states everywhere this is because the bootloader uses 4KB, thus reducing the 32KB to 28KB.  Makes sense, except...
Blank sketches on the 32U4 take nearly 4KB from the get go, which I thought was attributed to the bootloader?  So now I'm confused.  If I'm losing 4KB off the top, and 4KB off the bottom - is the bootloader 8KB?
EDIT:  In case the above is unclear, it appears my sketches only have ~24k of the 32k available to them.  Is this expected behavior?

32u4 sketches include the USB stack that 328p sketches don't. That consequently uses more space.

I read the USB stack lives in the bootloader; are there two USB stacks?

The bootloader needs a USB stack to work. It is possible to run the main sketch without a bootloader. So yes, I suppose you must have two of them. Looking at the assembler output for a blank sketch, it appears that you get the USB code in it by default. As I said, they have to assume you may not have the bootloader around, so they can't just execute the stack from the bootloader.

Not the answer I was hoping for, but an accurate and informative answer nonetheless.  Thank you!


text:
SendSMS example sketch hangs at PINMUNBER if statement
I'm using an Arduino shield connected to an Arduino Uno for sending text messages. I'm using one of the in built examples from the Arduino IDE for sending SMS by name - sendsms in the GSM examples. However, the code doesnt work at all... it keeps hanging at the line
if (gsmAccess.begin(PINNUMBER) == GSM_READY)

and never goes beyond it.
I didn't keep any pincode for my SIM card. please help

Post your code properly. Does the shield show any sign that it is on, like a blinking LED? Do you have a SIM attached?

...and please summarize your problem in the title. Success.

You can't just straight away to send SMS, you need to send commands to establish the Serial communication with the module, register to the network, and if the module acknowledged that it has register to the network, you can then start sending msg. Whatever library you are using, it should come with the examples, try those and try to understand the example code.

Try this sketch:
#include <SoftwareSerial.h>

SoftwareSerial gsm(2,3);
void setup() {
  Serial.begin(9600);
  gsm.begin(9600);
  delay(1000);
}

void loop() {
  // put your main code here, to run repeatedly:
  while (gsm.available() > 0)
    Serial.write(gsm.read());
  while (Serial.available() > 0)
    gsm.write(Serial.read());
}

This sketch will help troubleshoot exactly what's wrong with your setup, without the clutter of a library.
Connect the shield's TX pin to Arduino pin 2 and the shield's RX pin to Arduino pin 3. Ensure that all GNDs are connected. Upload the sketch. Set your serial monitor to BOTH NL & CR and the baud rate to 9600. Enter AT from the serial monitor. If you recieve OK, it means comms have been established with the shield. If you receive gibberish, change the SoftwareSerial baud rate to values from 19200, 57600, etc. until you get a legible response.
Then send the command AT+CREG? to check the SIM's registration status. If you get something like +CREG: *, 1 or +CREG: *, 5 (* means 'dont care'), then your SIM has been registered on the network. Report your results here.


text:
MQTT broker and Arduino + Sensors NRF24L01
I am newbie, I have never used MQTT before, so I have some questions.
Here is my topology.
I have several sensors (Arduino Pro Mini + NRF24L01) and main server/handler(Arduino Mega + Ethernet Shield or ESP module) to receive/send messages to/from sensor nodes, so all network is build on NRF24L01 (NRF24 Mesh library). But I need to be able to communicate with all these sensors from outside over the internet. Previously I implemented simple socket communication.
I have recently discovered MQTT protocol and it is awesome. I want to implement communication between main server and outside world using it.

What part of my topology should implement broker in? I think it should be on the main server (Arduino Mega) but again communication between main server/master server is implemented via NRF24L01 modules and custom protocol.
Or in my case is better to use HTTP communication with master server?

Please explain this topic and suggest how to implement this correctly in my case.

The normal topology is sensor nodes publishing topic-data on a MQTT broker. And the broker distributing updates to subscribing clients. The MQTT broker is responsible for several levels of QoS (Quality of Service) such as storing attribute/topic-values (persistence), checking that messages are delivered, etc. Typically the broker runs on a server with disk, multiple network connections, etc.
A possible solution is to send sensor messages to a bridge that translates and publishes the message on the MQTT broker. The sensors may use a simple cheap local wireless network (such as based on NRF24L01) and the bridge would publish over IP (Ethernet, WiFi, etc) to the MQTT broker.
Some sensors/actuators might need configuration/control (alarm thresholds, resolution, etc). In this case they need to subscribe to messages (topic updates) from the MQTT broker. Again the bridge needs to provide the subscription and message translation/routing back to the sensor.
Last, topics naming is a challenge as the bridge should be transparent in the naming structure but still configurable. The bridge configuration (e.g. network address/topic translation) could also be handled as a bridge topic.
Cheers!

You can use a Raspberry Pi as your MQTT server and you can also connect a nRF24L01+ module.

nRF24L01+ can directly be connected to the rPi.


text:
Power converting - up or down?
Sorry if there is an obvious answer to this - I'm pretty new at Arduino and electronics. I've searched a bunch, but I think I'm too vague - and don't know what terms to look for.
I have a pretty simple project using a 3.3v Arduino Pro Mini (https://www.adafruit.com/products/2377) and a 12v button/LED (https://www.adafruit.com/products/1185).
I'd like to give the LED the full 12v so the light is a bright as possible. The system will be battery operated.
The question is: Do I need a 12v power supply or can I use a 3.7v power supply and upgrade it somehow? I know I can power the LED with 3.7v but then it's really dim. Is there a way to "upgrade" the 3.7v to 12v? I would assume this would draw more power and drain the battery faster, but I think that would be ok.
I'm hoping to get away with a 3.7v power supply because I want to use a lithium ion polymer battery (https://www.adafruit.com/products/328) - since it's small and rechargeable.
Seems like if I go with 12v source then I need a much bigger battery pack, and I'm hoping to keep the project small. Not sure if it would help to know, but I only need the device to run for 4+ hours between charges.
I'm guessing people will say to go with 12v since the Pro Mini can downgrade the 12v supply so there'd be less parts I have to deal with (I can already make this work). But, again, I was hoping to get away with a small rechargeable power supply. Or, are there good, small 12v batteries - I can't seem to find any on Adafruit or SparkFun.
Any recommendations? Thanks!

The product description states "The LED has a built in resistor so you can run it up to 12V"., But, of couse, at 3.7 you won't get enough bright. I'd probably feed the Arduino with a 12 vdc power source and divert some of the power for the button. Maybe you need to find a lower voltage button, or test the one you have with the 3.7 v supply,

Since your project is to be battery powered, you want to make your system as efficient as is reasonable.
So I am going to take an approach that ends up improving the efficiency of your project.
The button you describe in your link states :

This button has a domed red plastic cover with a black retaining ring around it. There's an optional LED included

Further, the LED included has a "built in resistor", so that the LED can operate from 12 volts.
Since you would have to install the "optional LED",  why not purchase a Red LED that operates from lower voltage. You will still need a resistor but you won't need to have a voltage converter.
Example  :  Their LED probably has a 2 volt LED (approximate) that operates at perhaps 20 mA).  This would require a 500 ohm resistor (which they incorporate into the LED).  The power loss (wasted) in the resistor is 0.2 watts (200 mW).
Improved Example :  With LED of about 2 volts operating from 3.3 volt power source.  This would require a 68 ohm resistor.  The power loss in the resistor would be 0.027 watts (27 mW).  A substantial improvement in efficiency.
The manufacturer of the button does not give specifications for the LED (the one with the resistor included).  You should connect their LED to a 12 volt power supply and measure the current drawn.  It is possible their LED draws more current than I have shown in the examples.  This would require a re-calculation of the resistor values.
But in any case, the improvement in efficiency will still exist.

Thanks! Would a 2v LED be way dimmer than the 12v one? I don't know a lot of about electronics (clearly), but I guess I assumed the higher the volts the brighter it would be? For my project a nice bright LED is desirable.

I reread your comment... Realized I missed your point. Yeah, if the LED is only 2v then your solution would be perfect! I'll try to find the specs on the LED... That being said, am I still going to be limited on my light output based on 3.3v? I think I'll have to do some tests... Thanks for your response!

I'm thinking this is what I'll need: https://www.adafruit.com/products/754 Thanks again for the suggestion!

Would a 2v LED be way dimmer than the 12v one? - LEDs have a standard voltage drop (around 2V depending on the colour). When you get a "12V LED" it just has a bigger resistor, as Marla said. See Wikipedia for a bit more detail.

The ones you linked from Adafruit have a slightly higher voltage drop: "3.0V Typical Forward Voltage, at 20mA current". You still need the current-limiting resistor though.

Basically you have two choices. There is a third, but you don't wan to take that route.
The third route is to directly power the system with 12V and rely on the Arduino's regulator to drop it to the right voltage for the Arduino. That is very very inefficient and wasteful, and your battery won't last very long - plus the regulator will get hot. So don't even consider that option.
So the two sensible options - start with 3.7V and step it up to 12V using a boost regulator, or start at 12V and step it down using a buck regulator.
Which of those will be the easiest and most efficient?  Well, there's not much to choose between them.
With either of those solutions you are converting voltage and current. With a buck regulator you are converting voltage into current, and with a boost regulator you are converting current into voltage.
If you start at 12V and step it down yes you need more cells, but each cell can be smaller since each one will have to supply less current.  With 3.7V and stepping up you will have just one cell, but it will need to be bigger since it will have to supply more current.
From a charging perspective it is easier to charge a single cell since you don't have to worry about cell balancing.
From a price and availability point of view, buck (step-down) regulators are cheaper and easier to get hold of on places like eBay than boost (step-up) regulators as pre-built circuits.
So really the choice is yours - 12V (well, 11.4V it would really be - 3S LiIon / Li-Poly) and buck regulator, or 3.7V and boost regulator. Both will work, both will be about as efficient as each other.
Incidentally there are boost regulators specifically designed for driving LEDs from battery sources - you might like to look around to see what is available in that way.

Thank you for your reply! I think I will dig into your suggestions a bit - since I think the brightness of my LED may require more power. For now, however, I think Marla's answer above my be better for my project.


text:
SIM900A GSM/GPRS Shield Transaction per minute
I'm planning to buy SIM900A GSM/GPRS Shield for Arduino Uno. I wanted to create an application that sends SMS to a list of mobile numbers, let's say 1000 mobile numbers. Is it applicable to use SIM900A GSM/GPRS shield for bulk messaging? Did anyone of you tested the sms transaction sent per second/minute using this shield? I accept any suggestion that would be helpful. Thanks.

Sound like you need an online sms gateway (.e.g. message bird) .

Yep, but this is only for my testing purposes for a few mobile numbers. Thanks

"Did anyone of you tested the sms transaction sent per second/minute using this shield?" This depends on the service provider, the radio network, more than the SIM900A.


text:
Does a moisture sensor need warm-up time?
I am trying to use a moisture sensor to identify the moisture value of my plants. (As every one does.)
The sensor was connected to VCC all the time and my battery goes empty after a short time. So I decided to connect power only at the time I read from the sensor (on the arduino with digitalWrite(moisture_vcc, HIGH).
To problem is that the values were too high.
So I'm wondering if these kind of sensors need a "warm-up time"? And If so, how long is it?
Any experience with it?

Do you have a part nr or something?

It's a YL-69 sensor.

There is a very good analysis of the YL-69 sensor on :  http://electronics.stackexchange.com/questions/105549/is-my-moisture-sensor-yl-69-broken

Another analysis is  :  http://electronics.stackexchange.com/questions/90725/arduino-moisture-sensor-value-decreasing-for-no-reason

@Marla thanks. The last post was a bit helpful:

When you want to take a reading, power the sensor for maybe a few seconds, and take your readings. Then power it off again.

@Marla can you post an answer with at least the basic summary of that link, so OP can mark the question as answered?

Photograph of the YL-69 Sensor  :

Most of this content was generated by :  Conner Wolf
Basically, that sensor works by measuring the resistance between the two "pins" of the PCB stake. It does this by applying a voltage across the pins, and measuring the current flow. So, the intention is that more water means less resistance, means less voltage, and a fall in the voltage sent to the ADC of the processor.
However, this is also going to lead to the metal from one of the pins being eaten away by galvanic action (electrolysis).
The other pin is likely to have accumulation of materials rather than being eaten away.
This electrolysis and coating of the pins results in a change in surface area of the pins and causes resistance measured to change (for the same given moisture content).
If you want to squeeze as much life out of the thing as possible, there are a few things you can do.

DO NOT leave the sensor powered. When you want to take a reading, power the sensor for maybe a few seconds, and take your readings. Then power it off again. Don't take readings too often.
Periodically reverse the pins of the electrical connection between the readout board and the "stake" board. Since only one terminal will be eaten away at a time, this should spread the decay out a bit.
Be aware that ANY mechanical disturbance of the "stake" board will probably cause a large shift in readout value. Your "jiggling the wires" causing a shift in values probably came from the mechanical force transmitted to the PCB through the wiring.

An improved version for this sort of thing use a AC bias on the sensor, which minimizes galvanic corrosion. AC bias reverses the voltage applied to the sensor, attempting to eliminate electrolysis on the sensor.
Higher Quality soil moisture sensors use capacitive sensor, and therefore make the sensor immune to the corrosion issue, but are much more complex and expensive.


text:
Do I use 3,3V or 5V, when device supports both?
I have a general question regarding the power-supply of the electronic components, that are attached to an Arduino.
If I have a device that operates at voltages between 3,3V and 5V (e.g. this RS232 to ttl converter), what is the best way to connect it with the Arduino?

Connect 3.3V or 5V power supply between VCC and GND

I know, that you can not draw as much current out of the 3,3V Pin like on the 5V Pin. But what if I don't need much current anyways (like in the linked example)?
What ware the advantages / disadvantages of connecting it to 3.3V and 5V?

Using the MAX3232 data sheet , which is what the TTL Converter has on it's board :
The main difference between using 3.3v or 5v is on the receiver data line "R" (or Rout as it is called on the MAX3232).
Simply put, you want to power the TTL converter from the same voltage as your Arduino is using (3.3v or 5v). Meaning the voltage that your I/O pins will put out and accept.
The received data line R will go between 0 volts and Vcc.
You would NOT want to power the TTL converter at 5 volts if you are using the converter for a 3.3v Arduino, as the received data line would go to 5 volts when high. Actually Vcc - 0.1 volts (typ.)  (5 - .1 = 4.9)  as per this specification :

If you power the TTL converter from 3.3 volts, the received data line (Rout) switches between 0v and 3.3v   as shown here :

@Marla You didn't finish explaining what happens when you connect a 5 volt signal to a 3.3v Arduino pin (I know, it's obvious).

@linhartr22   Arduino says, "Owww", and then won't behave afterwards (permanent damage).  Some devices are tolerant to over voltage, and mention it in their specifications)


text:
What is preventing my code from checking the number of pushbutton values for a correct/wrong answer?
My code is supposed to generate a random number and then display it in binary using four LEDs. After you press it, it waits for two seconds before checking your number of pushbutton presses to see if they equal the random number, and it turns the green/red LED on accordingly and restarts the loop.
It doesn't do that, and also it counts multiple pushes if you keep the button pressed in, since it reads the pushbutton as being "on".
Code:
//VARIABLES:
const int ledPin1 = 2;
const int ledPin2 = 3;
const int ledPin3 = 4;
const int ledPin4 = 5;
const int buttonPin = 6;        //push button
const int ledPincorrect = 8;   //green LED that switches on for correct answer
const int ledPinfalse = 9;    //red LED that switches on for wrong answer

int randomNumber = 0;
int buttonState = HIGH;
int buttonPushCounter = 0;             //counter for button presses
int lastButtonState = HIGH;             //previous state of the button
int getal;
int i;                              //for the ConvertBinary function, i serves as a variable for the LED's
unsigned long Timer;               //Timer, switches on after buttonstate = LOW, and after 2 seconds the game restarts
long lastDebounceTime = 0;         // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers
int ledState = HIGH;
int remember;

void setup()
{
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  pinMode(buttonPin, INPUT);
  pinMode(ledPincorrect, OUTPUT);
  pinMode(ledPinfalse, OUTPUT);
  Serial.begin(9600);
  randomSeed(analogRead(0));
  buttonState = digitalRead(buttonPin);
  Timer = millis(); // unsigned long Timer = millis();

}
void loop()
{
  if (randomNumber == 0) {
    Serial.print("lets start with random");
    getal = random(1, 16);
    Serial.print("random is: ");
    Serial.println(getal);
    randomNumber = 1;
  }

   int remember = getal;
   for (int i = 2; i < 6; i++) {
   remember = remember / 2;
      if (remember % 2 == 1){
       digitalWrite (i, HIGH);
      }
     else ((digitalWrite(i, LOW)));
    }

    // reading the button state

    // read the state of the switch into a local variable:
    int reading = digitalRead(buttonPin);

    if (reading != lastButtonState) {
      lastDebounceTime = millis();
      if (reading == LOW) {                    // if (reading == LOW) ????
        buttonPushCounter++;
        Serial.println("on");
        Serial.print("number of button pushes:  ");
        Serial.println(buttonPushCounter);
        Timer = millis();
        lastButtonState = buttonState;

      } else {
      // if the current state is LOW then the button wend from on to off:
      Serial.println("off");
    }

      if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;
      lastButtonState = reading;
    }

    if (Timer >= 2000UL) {
      if (buttonPushCounter == getal) {
        digitalWrite(ledPincorrect, HIGH);
        digitalWrite(ledPinfalse, LOW);
        digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4, LOW);
      randomNumber = 0;
      buttonPushCounter = 0;
      }
      else {
        digitalWrite(ledPinfalse, HIGH);
        digitalWrite(ledPincorrect, LOW);
        digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4, LOW);
      randomNumber = 0;
      buttonPushCounter = 0;
      }
}

    }
}

}

Have you tried using serial communication to get some debug information out of your sketch? I see you've got some Serial calls in there, what does your output look like?

@Martin Carney
lets start with randomrandom is: 1
number of button pushes:  1
number of button pushes:  2
number of button pushes:  3
number of button pushes:  4
number of button pushes:  5
number of button pushes:  6
number of button pushes:  7
This is from one button press

Sounds like you have a debounce problem. I'd recommend making a simple sketch (e.g. with just one button and one LED) just to get your debounce code working the way you expect it to, then bring that over into your program as a whole.

Let us start with the simplest issue in your code:
Timer = millis();
...
if (Timer >= 2000UL) {
...
}

After 2000 ms this is always true (for about 49 days)?
Cheers!
Please format your code if you expect anybody to take the time to read it and help.


text:
Are there sensors that can detect the color of an LED?
Are there sensors that can detect the color of an LED?
I am working on an Arduino project that needs to detect the color of an LED on an external device. I am trying to identify a light sensor that can be connected to the Arduino's input that can tell me the color of light the LED is currently emitting. The LED is capable of displaying red, green and yellow.

Take a look at AMS color sensors family for example. One of them in a Adafruit: https://www.adafruit.com/products/1334

E.g. http://www.ebay.com/itm/TCS230-TCS3200-Color-Recognition-Sensor-Detector-Module-For-MCU-Arduino-M7-/351493999961?hash=item51d6accd59:g:wMIAAOSwPcVVwHPf

You mean like this one?
Adafruit RGB Color Sensor
They have similar products in different form factors.

You can use an LED as a light sensor - http://www.instructables.com/id/LEDs-as-light-sensors/
In theory, LEDs should be most sensitive to the frequency it emits - if this is true, the same type of red/green/yellow LED would be best.
I don't know how sensitive this will be.
If you control the "external device", then you could get much better accuracy by blinking the LED at very high rates (not visible to the human eye). Or, if you can get at the legs of the LED, you can tap into the signal directly (you should use an opto-isolator - even if powered at a few volts, the ground of your project may be different from the ground of the external device, causing 100s of volts to run through your Arduino - not good!).

There are a few different things you can do to detect a color.
The Arduino starter kit that I got when I first got into Arduino had some photoresistors plus some colored films. One of the projects in the project book had you put a different color film over each photoresistor, so that only that color of light would hit the sensor. You could do something like that if you only need to check for a small number of distinct colors.
There are also a wide array of color sensors and sensor modules available (just search your favorite online store for "color sensor" or "arduino color sensor"), which will allow for far more detailed and precise color readings, but at a higher price point.


text:
Can an L293D motor driver shield do microstepping?
I bought a L293D motor driver shield and have used it with a pre-made sketch for driving a pair of stepper motors, but I'm not familiar with its capabilities.
The sketch I've used so far doesn't use microstepping when it's set up for this shield (though it does use it with the Adafruit shield).
I've done some searching, and it's not clear if the L293D chips on the shield can do microstepping, and if so, how.
Are L293D chips (and thus the motor driver shield that uses them) capable of microstepping? If so, how can I add this capability into my sketch?

See Microstepping with Arduino - if that helps maybe post an answer summarizing what you found.

It would be more accurate to say that it can be used as part of a microstepping system, though it's probably not a good choice for any use today.
The L293D is merely an (effectively obsolete implementation of an) H-bridge, not a stepper motor sequencer, hence it is no more capable of autonomously driving a motor in full or half step mode than it is of microstepping - it can only do any of these when it is controlled by a sequencer, such as an L297 chip, or software running on an Arduino's processor.
Microstepping requires partially actuating the coils to interpolate between the angular positions which would be achieved by activating each in turn fully.  It can be thought of as a proportional extension of how half-stepping uses actuating both coils at the same power to achieve a halfway in between position, only now the coils are actuated at different power levels to achieve finer gradations of position, though achieving accurate interpolation requires care as the relationship is not linear.
Modern power electronics no longer use variable analog drivers, as these convert the unused power to heat.  Instead, the goal is to use switches which come as close as possible to only ever being fully on or fully off.  Reduced driver power is achieved by pulse width modulating the switch, varying the average amount of power delivered to the load over a short period of time.  In a stepper motor setting, this on-off modulation can be done to achieve microstepping and or also to achieve current regulation when a many-times-rated-voltage supply is used to allow overcoming winding inductance at high step rates.
The L293D (and its larger cousin the L298) are quite inefficient bipolar transistor bridges (they aren't very good switches compared to MOSFETs), and should probably not be chosen for new designs today.  They are, however, capable of being used to microstep a motor when actuated by a sequencer which pulse width modulates the phase signals.
Adafruit, who appear to be the original creators of this shield design, have in fact published microstepping driver code for their L293D board on github.
https://github.com/adafruit/Adafruit-Motor-Shield-library
Given that the ebay seller you link to as the source of the board is using Adafruit's own schematic on their product page, it's a bit unclear why your software is differentiating between this board vs an Adafruit one, unless by the the Adafruit board you mean their V2 shield.  The V2 design uses a more efficient TB6612FNG FET bridge, but of more relevance to microstepping offloads the sequencing task from Arduino software to a PCA9685 chip which is apparently capable of microstepping (as well as simpler modes) by itself.  Depending on the computational load and/or your  level of determination, you may be able to get the ATmega microstepping the L293D in the context of your overall project.

Not directly. The L293D is a digital H-bridge chip. L293 series devices allow you to supply enough power for small motors, and the "D" model has internal protection diodes. There are other ICs and breakout boards that are designed specifically for microstepping. Here are a few options...

The SparkFun EasyDriver ($14.95) will probably be the quickest solution.
There are a variety of stepper driver ICs on the market with a wide range of power ratings. For instance, ST makes the L6219 ($4.86) and ON also makes several versions of the LB1847 ($4.19-$6.90). TI also makes a few.

Datasheets will typically say whether a driver is capable of microstepping at the beginning. Just make sure the driver you choose is capable of handling the stall current of your stepper.
Are your steppers unipolar (6+ wires) or bipolar (4 wires)? That may make a difference in how you wire them, although some unipolar motors can be driven as if they were bipolar.

No.  There's a fundamental misunderstanding in this answer.  Microstepping is not practically implemented via analog circuitry, rather it is done in the time domain with switches that are always either fully on (to the best of their ability) or fully off.  As the L293 is merely a bridge, with no chopping or other current control of its own, the ability to microstep - or not - depends on what is driving it.  That said, the L293, like any bipolar driver has internal losses that make it a severely obsolete part!

@ChrisStratton, I am fairly new to SE. Can you recommend changes to improve the answer? From my understanding, a microstepper approximates two out-of-phase sinusoids. With that assumption, given a square wave generated from an L293D, it could be theoretically possible to build an analog circuit that would convert a square wave to a sine wave. The problem is that it would be difficult to create such a circuit that would work correctly at more than one frequency.

No.  Do not try to convert the digital output to analog - that way only leads to losses.  The key concept to grasp is that microstepping is ultimately about a time average over short periods of time.  It does not have to be achieved by an analog circuit at all.  Rather it can be (and usually is) done by purely digital means, modulating the on-time of a purely on/off switching device.  Anything other than an on/off switch converts unacceptable amounts of power to heat when it is "partially on" - but a time average of on and off does not, except in the switching transition itself.

@ChrisStratton, that makes sense. So, should I stuff about adding analog circuitry, delete this answer attempt completely, or just leave it as is?

Unclear.  The L293D is a rather disappointing device, but the problem it (sort of) solves is different part of the system than where micro stepping would, or would not, be implemented.  It is a bridge, while microstepping is implemented in the bridge controller (which is probably also the current regulating chopper).

Most of the micro-stepping circuits I am familiar with are hybrids (not purely digital). The current from each h-bridge is sensed (usually with a current-sensing resistor) and fed back to an analog comparator. This is compared to the output of a DAC (digital to analog converter) which outputs a voltage proportional to the desired current for the coil for the micro-step. The comparator output normally resets a flip-flop which is part of the digital timing circuit for the chopper-drive. The analog input used to set the drive-current is often the reference voltage for the DACs.


text:
Cannot disable interrupts
I am new to arduino.
Why does this not work the way it's supposed to?
Shouldn't it block all interrupts for 3secs after it received one from digi pin 2?
How would I accomplish this:
Running a method whenever the value on this pin changes, execute it and then listen for more interrupts from that pin?
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

int i = 0;

void loop(){}

void test(){
  noInterrupts();
  Serial.println("Interrupt registered - waiting " + i);
  delay(3000);
  Serial.println("done waiting!" + i);
  i++;
  interrupts();
}

What is it doing that it isn't supposed to? I think delay and Serial depend on interrupts being active, you should never disable them globally for an appreciable amount of time. Handlers need to run fast. Also running an interrupt and then continuing to trigger future interrupts is the default behavior.

You could achieve that by this simple rewrite:
void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

volatile bool changed = false;
int i = 0;

void loop() {
  if (!changed) return;
  Serial.print(F("Interrupt registered - waiting "));
  Serial.println(i);
  delay(3000);
  Serial.print(F("done waiting "));
  Serial.println(i);
  i += 1;
  changed = false;
  clearInterrupt(digitalPinToInterrupt(2));
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

void test() {
  changed = true;
  detachInterrupt(digitalPinToInterrupt(2));
}

The interrupt service routine (ISR), test(), is really short and does not call functions that actually need interrupts to work (e.g. delay(), Serial). Please see Nick Gammon's comment below on clearInterrupt(), i.e. EIFR = bit (INTF0);
An alternative rewrite is to use the BlinkWithDelay-pattern and a somewhat more complex state-machine:
volatile bool changed = false;
bool waiting = false;

const unsigned long waitIntervalMillis = 3000UL;
unsigned long waitStartMillis = 0L;

int i = 0;

void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

void loop() {

  // Check for change
  if (!changed) return;

  // Check for change before wait interval
  if (!waiting) {
    Serial.print(F("Interrupt registered - waiting "));
    Serial.println(i);
    waiting = true;
    waitStartMillis = millis();
  }

  // Check if wait interval has expired
  else {
    unsigned long currentMillis = millis();
    if ((currentMillis - waitStartMillis) >= waitIntervalMillis) {
      Serial.print(F("done waiting "));
      Serial.println(i);
      i += 1;
      changed = false;
      waiting = false;
    }
  }
}

void test() {
  changed = true;
}

A third rewrite is possible. Assuming that the pin is connected to a push button, the interrupt handler can be replaced by simply reading the pin with a low frequency (for debouncing).
Cheers!

If the switch bounces it will probably register (queue) another interrupt during your delay. I suggest doing EIFR = bit (INTF0); before attaching the interrupt again. See: Interrupts.

This is one of those disturbing things. There was a pull request to fix that nearly two years ago; https://github.com/matthijskooijman/Arduino/commit/c82e9aadd358127e4f272dc99bc2a6a4d70963c6. It must have broken something else as it was removed/not merged. They could at least added a clearInterrupt(pin) function just for the symmetry of things. Anyway, that is a very good catch!

Once people get used to behaviour (no matter how annoying it might be) it is hard to change it.

why do you need to disable and reenable interrupts at all?

The question is why use interrupts at all if the signal is generated from a button pushed? In any case, I do agree, it is possible to do yet anther rewrite without attach/detach interrupt.

Probably your biggest problem is that delay() cannot be used inside interrupt service routines (ISR's) and it doesn't work if interrupts are turned off because it uses interrupts to function.
ISR's should be as short as possible, because they stop normal operation of the device while they execute. A good ISR will set a few variables, and then return, while the main program loop checks the state of those variables and actually does stuff. Mikael Patel's answer shows how you can rewrite your sketch to do this.


text:
Calibrate motors using arduino
I'm trying to create a car that's being controlled by an Arduino.
I'm using the following chasis:
http://www.aliexpress.com/item-img/New-2WD-car-chassis-DC-gear-motor-wheels-easy-assembly-and-expansion-car-toys-robot-toys/32310649967.html
And L298N motor driver.
The problem is it's hard to make the car go straight. Giving the same PWM value to the motors still makes them spin in different speeds, trying to calibrate the value is hard and every time I recharge my batteries the value changes.
What are my options on making the car go straight when I want (well, sometimes I'll want to turn it around of course)?
I've thought about using an encoder but I wish to avoid that since it will complicate the whole project, is there any other viable option? and even when using an encoder, Does it means I will need to keep track all the time and always adjust the motors value continuously? is there some built-in library for that?
Thanks in advance!

You may find Robotics Stackexchange also useful for questions like this.

With a separate motor for each wheel, a couple of encoders and a feedback loop seem unavoidable.

You might be able to use a "hall effect sensor" or "reed switch" and a magnet. It won't be as pretty as a encoder. But it can be used to sync both the wheel speeds.

@my past self. It sounds fairly stupid to use a hall effect sensor near a electric motor. (Never mind that suggestion.)

An old method is that if you have access early in the gear train where speed is high and torque low, a pair of magnets can mechanically synchronize two motors when their drive is comparable but still allow them to turn at substantially different speeds/directions when driven differently.

I used a simple optical encoder and the little disks that came with my kit.  The encoders cost < £1 for 2 of them.
Failing that use an accelerometer and measure the lateral motion, should also cost about £1.

Modern tiny $20 toy quadcopters use a magnetometer to maintain a steady heading.    Duplicating that effect could be cheaper and more reliable than dual encoders.  On certain surfaces, like carpet, even perfect encoding with perfect voltage and wheels can't guarantee maintaining the heading.
One viable option might be to drive one wheel with your control system, drive the other wheel to maintain the magnetometer heading, and then steer by adjusting the target heading.

Actually the cheap ones try to integrate the gyro.  Magnetometers only come in at a higher price point.  Even if you do get a magnetometer it will be harder to interpret and more interference prone than encoders.  But it is possible with care if an external reference is what is desired.


text:
Reprogramming a specific slave from the master ATTiny 85 (connected to IDE)?
Given that every ATTiny connected already has a bootloader (micronucleus) installed, here's my theoretical chain:
Computer > Master ATTiny (Connected via USB) > ATTiny Slave A > ATTiny Slave B
Is it possible to flash an individual slave (say, slave B) with new software without replicating it to all of the other slaves, or altering the master?
Can this be done with the normal MISO/MOSI/SCK/RESET method?
I've done some research (Programming multiple ATMegas/Arduinos at once) but I'm not looking for a batch flashing method; I want to upload custom programming to a single slave.
Note: I'm not trying to pass data between the master and the slaves. What I want is to reprogram the slaves from a single USB connection. It's also important that each slave has a fixed identity so I know exactly which one I'm flashing every time I boot the "system".
Disclosure: I'm an arduino novice and programming intermediate. This is my first project utilizing serial communication.

I recognize that I could simply connect each ATTiny as a unique USB device but (a). I don't want to have that many USB devices connected to my PC and (b). I would like to be able to pass some data between the master and slaves if it turns out reprogramming over the serial bus is feasible.

What sort of wiring are you envisaging? How close is the slave to the master? Using the bootloader you normally reprogram using a serial connection (not MISO/MOSI/SCK).

Wiring is flexible, I haven't actually put together the hardware yet. Closest slave would be a few inches, furthest out 3-4 feet. Does that mean I would want these connected via I2C?

Well, the current bootloader expects serial input, as I said. Not SPI and not I2C. You can write your own bootloader, but that would take more work than somehow adapting your hardware to use the existing one.

Is there a wiring diagram for that? I would like to have the ability of flashing the slaves in addition to master/slave serial communication (like with I2C). Can I use serial input to flash and I2C to communicate in-software?

If I can't control individual slave flashing, then pushing a software update through to master and every attached slave would suffice. Just unsure of the wiring I'm going to need and where to research.

Given that the ATtiny85 has 8 pins, 3 of which are Vcc, Gnd, and Reset, you don't have all that many to play with. This is starting to sound like an X-Y problem - rather than asking about flashing multiple chips either at once or individually, perhaps explain more about the project?

Here is an app note that can inspire: http://www.atmel.com/images/doc8079.pdf


text:
Arduino error when compiling
When this code is uploaded I get an "Error Compiling". Any help is very much appreciated.
#include <MeetAndroid.h>
#define supplyVolts 6
#define motorVolts 5
#define baudRate 57600
// If you are using a General Bluetooth adapter (available on buildcircuit.net), then, it works with 9600bps baud rate
MeetAndroid phone;
int left = 255; // midpoint
int right = 255;
int pwmLeftPin = 3;  1 int pwmRightPin = 11;
int directionLeftPin = 12;
int directionRightPin = 13;
void setup() {
  pinMode(pwmLeftPin, OUTPUT);
  pinMode(pwmRightPin, OUTPUT);
  pinMode(directionLeftPin, OUTPUT);
  pinMode(directionRightPin, OUTPUT);
  setMotors();
  // use the baud rate your bluetooth module is configured to
  Serial.begin(baudRate);
  phone.registerFunction(setLeft, 'l');
  phone.registerFunction(setRight, 'r');
}

void loop() {
  phone.receive();
}

void setLeft(byte ignore, byte count) {
  int value = phone.getInt();
  left = value;
  setMotors();
}

void setRight(byte ignore, byte count) {
  int value = phone.getInt();
  right = value;
  setMotors();
}

void setMotors() {
  int vLeft = abs(left - 255) * motorVolts / supplyVolts;
  int vRight = abs(right - 255) * motorVolts / supplyVolts;
  int dLeft = (left > 255);
  int dRight = (right > 255);
  if (vLeft < 50) {
    vLeft = 0;
  }
  if (vRight < 50) {
    vRight = 0;
  }
  analogWrite(pwmLeftPin, vLeft);
  analogWrite(pwmRightPin, vRight);
  digitalWrite(directionLeftPin, dLeft);
  digitalWrite(directionRightPin, dRight);
}

Welcome to Arduino Stack Exchange. We hope you find this site useful. In future posts, please format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you. On this occasion I see that @jwpat7 has done it for you.

Where did you get the MeetAndroid library from? It's hard to reproduce your issue if we have to guess at where the libraries are to be found.

http://www.amarino-toolkit.net/index.php/download.html

Take a close look at this line. The compiler will not like that as it does not have the right syntax.
int pwmLeftPin = 3;  1 int pwmRightPin = 11;

Change it to:
int pwmLeftPin = 3;
int pwmRightPin = 11;

This should at least remove the first issue with your code.
Cheers!

@Tom Evans if mikael's answer worked, you should press the check mark next to his answer to reward him with some reputation.