text:
How to read bitmap image on Arduino
I want to convert a bitmap into binary array. My bitmap image is 272*208 pixel monochromatic 1bpp image. I'm confused when the width I get from my image is 16 instead of 272, the height is corrected. And when I skip the bitmap header to get bitmap infomation, I got string of meaningless number in my text file.
#include <SPI.h>
#include <SD.h>
#include <TFT.h>

File bmpImage;
File textFile;

void setup()
{
Serial.begin(9600);
while (!Serial) {
;
}

Serial.print("Initializing SD card...");
if (!SD.begin(53)) {
  Serial.println("initialization failed!");
  return;
}
Serial.println("initialization done.");
int height = 0;
int width = 0;

// Open
bmpImage = SD.open("Circle.bmp", FILE_READ);
textFile = SD.open("test.txt", FILE_WRITE);

bmpImage.seek(0x12);// width in pixel = 16
width = bmpImage.read();
bmpImage.seek(0x16);// height in pixel = 208
height = bmpImage.read();
Serial.println(width);
Serial.println(height);

int imageSize = height*width;

bmpImage.seek(0x36);//skip bitmap header

for(int i = 0; i < height; i ++) {
  for (int j = 0; j < width; j ++) {
    textFile.write(bmpImage.read());
    textFile.write(" ");
  }
  textFile.write("\n");
}

bmpImage.close();
textFile.close();

Serial.println("done write");
}

void loop()
{
  // nothing happens after setup
}

That was a very raw way of trying to read a BMP file. There are a lot of assumptions that might give errors.

The file is a BMP file. The header signature is not checked.
The image offset is assumed to be directly after the file header. It is not read.
The image width is less than 256. Only the lowest byte of the 32-bit image width is read. As 272>256 the low byte is 16.
The image height is less than 256. Only the lowest byte of the 32-bit image height is read.

It is a small bitmap but it will take a very long time to read when reading a single byte at a time. There are methods to improve performance but that is an answer to another question.
A more robust method to read the BMP header and image information is to define them as a struct and read.
struct bmp_file_header_t {
  uint16_t signature;
  uint32_t file_size;
  uint16_t reserved[2];
  uint32_t image_offset;
};

struct bmp_image_header_t {
  uint32_t header_size;
  uint32_t image_width;
  uint32_t image_height;
  uint16_t color_planes;
  uint16_t bits_per_pixel;
  uint32_t compression_method;
  uint32_t image_size;
  uint32_t horizontal_resolution;
  uint32_t vertical_resolution;
  uint32_t colors_in_palette;
  uint32_t important_colors;
};

bmpImage = SD.open("Circle.bmp", FILE_READ);
...
// Read the file header
bmp_file_header_t fileHeader;
bmpImage.read(&fileHeader, sizeof(fileHeader));
...
// Check signature
...
// Read the image header
bmp_image_header_t imageHeader;
bmpImage.read(&imageHeader, sizeof(imageHeader));
...
// Check image size and format
...
// Locate the pixels
bmpImage.seek(fileHeader.image_offset);

The file and image information are stored in little-endian so that works just fine on an AVR.

First of all I suggest you to read the full specification of the bmp file header (for instance on wikipedia).
Particularly see that

You can have a color table (palette): consequently the starting address of the bitmap data CAN not be 0x36
The pixels are not stored one per byte, but can be packed (see Pixel storage)
There are different type of headers
Width and Height are 4 byte integers, so your width is fine (272 = 256 + 16)

This said, if your bitmap has a standard BITMAPINFOHEADER header, and if your bitmap has a 24 bit standard coding (16 millions of colors) you can do something like this:
int32_t readNbytesInt(File *p_file, int position, byte nBytes)
{
    if (nBytes > 4)
        return 0;

    p_file->seek(position);

    int32_t weight = 1;
    int32_t result = 0;
    for (; nBytes; nBytes--)
    {
        result += weight * p_file->read();
        weight <<= 8;
    }
    return result;
}

void setup()
{
    Serial.begin(9600);
    while (!Serial);

    Serial.print("Initializing SD card...");
    if (!SD.begin(53)) {
        Serial.println("initialization failed!");
        while (1); // <- this is how you should block execution, not with returns
    }
    Serial.println("initialization done.");

    // Open
    File bmpImage = SD.open("Circle.bmp", FILE_READ);
    File textFile = SD.open("test.txt", FILE_WRITE);

    int32_t dataStartingOffset = readNbytesInt(&bmpImage, 0x0A, 4);

    // Change their types to int32_t (4byte)
    int32_t width = readNbytesInt(&bmpImage, 0x12, 4);
    int32_t height = readNbytesInt(&bmpImage, 0x16, 4);
    Serial.println(width);
    Serial.println(height);

    int16_t pixelsize = readNbytesInt(&bmpImage, 0x1C, 2);

    if (pixelsize != 24)
    {
        Serial.println("Image is not 24 bpp");
        while (1);
    }

    bmpImage.seek(dataStartingOffset);//skip bitmap header

    // 24bpp means you have three bytes per pixel, usually B G R

    byte R, G, B;

    for(int32_t i = 0; i < height; i ++) {
        for (int32_t j = 0; j < width; j ++) {
            B = bmpImage.read();
            G = bmpImage.read();
            R = bmpImage.read();
            textFile.print("R");
            textFile.print(R);
            textFile.print("G");
            textFile.print(G);
            textFile.print("B");
            textFile.print(B);
            textFile.print(" ");
        }
        textFile.print("\n");
    }

    bmpImage.close();
    textFile.close();

    Serial.println("done write");
}

The text output of this should be a file with an array of strings like R10G100B25, where R is the red component of the pixel, G is the green component and B the blue one.
Now, this is only compatible with the 24bpp format. If you want to support more formats you will need to read the specs and code them.
Let me know if this works for you

Or you could keep your old code with some adjustments, if you just want to read your image without bothering with too many checks.
Change the type of imageSize to unsigned long.
The height and width are 4-byte fields, so a single read() wont cut it. You have to declare the height and width as long or int32_t variables and then read 4 bytes at each offset, while using bit shifting to assemble the bytes into one number and remembering that it's little endian.
Something like this:
long width |= bmpImage.read();
width |= (long)(bmpImage.read()) << 8;
width |= (long)(bmpImage.read()) << 16;
width |= (long)(bmpImage.read()) << 24;

Repeat this to get the height but use abs() to get the absolute value since its usually negative.
You can also check for a colour table; usually the ColorDepth field is a good indicator (offset 28); if its less than 16, then you should expect a colour table. But if you know this already, you can skip it and get to the start offset, usually 0x36.
Your current code doesnt take the padding into account (even though your image doesn't have any padding) and it also isnt using the actual image width in bytes. To get this width, assuming the BMP uses RGB888 24 bits per pixel:
width = ((width * 24) + 31) / 32;
width *= 4;

With this, you can now read each row, though its usually arranged bottom-up. However, you arent writing properly to the file. You should use textfile.print() and not write(); the former will write the decimal value of each byte to your file while the latter will write the exact un-encoded byte to the text file, which would result in a lot of gibberish when you try to display the file's contents, say on Notepad, since the range of printable characters (under default ASCII encoding) is between 32 - 127 and your image probably has lots of bytes outside that range.


text:
Inheritance: error in calling the constructor of the base class?
I want to write a library for the RGBDigit shield (http://rgbdigit.com/), which essentially is an Adafruit Neopixel strip, packed as a 7 segment display. The shield also has a DS3231 clock and an IR receiver.
So my plan was to make a class RGBDigit, which inherits from the Adafruit_NeoPixel class and add private objects DS3231 and IRrecv.
This is my RGBDigit.h:
#ifndef RGBDigit_h
#define RGBDigit_h

#include <Arduino.h>
#include "Wire.h"
#include "../Adafruit_NeoPixel/Adafruit_NeoPixel.h"
#include "../IRremote/IRremote.h"
#include "../DS3231/DS3231.h"

class RGBDigit : public Adafruit_NeoPixel {
    public:
        RGBDigit(int nDigits);
        ~RGBDigit();
    private:
        int _nDigits;
        DS3231 _clock;
        IRrecv* _ir;
};

#endif

This is RGBDigit.cpp:
#include "RGBDigit.h"

RGBDigit::RGBDigit(int nDigits)
    : Adafruit_NeoPixel(8 * nDigits, 12, NEO_GRB + NEO_KHZ800),
    _nDigits(nDigits)
{
    _ir = new IRrecv(10);
    _ir->enableIRIn(); // Start the receiver
    Adafruit_NeoPixel::begin();
}

RGBDigit::~RGBDigit()
{
    delete _ir;
}

And this is my Arduino sketch:
#include <Wire.h>
#include <RGBDigit.h>

RGBDigit display = RGBDigit(4);

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

}

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

}

I get al lot of "undefined reference" errors:
RGBDigit/RGBDigit.cpp.o: In function `RGBDigit::RGBDigit(int)':
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:23: undefined reference to `Adafruit_NeoPixel::Adafruit_NeoPixel(unsigned int, unsigned char, unsigned char)'
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:23: undefined reference to `DS3231::DS3231()'
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:25: undefined reference to `IRrecv::IRrecv(int)'
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:26: undefined reference to `IRrecv::enableIRIn()'
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:27: undefined reference to `Adafruit_NeoPixel::begin()'
RGBDigit/RGBDigit.cpp.o: In function `RGBDigit::~RGBDigit()':
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:30: undefined reference to `Adafruit_NeoPixel::~Adafruit_NeoPixel()'
collect2: error: ld returned 1 exit status

But I don' t understand why. What am I doing wrong?

You're assuming that the IDE is smart enough to know that it needs to copy over and link the other libraries.

#include "../Adafruit_NeoPixel/Adafruit_NeoPixel.h"
#include "../IRremote/IRremote.h"
#include "../DS3231/DS3231.h"

What you're doing there is telling the compiler where, relative to where it's performing the compiling (or one of its include directories), the header files you list are.
What you're not doing is telling the IDE where the CPP files are to compile and link with your sketch.
When including anything external to the sketch folder that is more than just a header file you must treat it as an Arduino library - that is, place it in one of the standard library folders and name it properly (libraries should be named LibraryName/LibraryName.h).
Then you include the libraries properly:
#include <Adafruit_NeoPixel.h>
#include <IRremote.h>
#include <DS3231.h>

You must do that in both your sketch and your custom library.  That way the IDE knows where to look for the files to compile - the compiler doesn't understand the concept of an Arduino library (and thus the CPP files associated with a header file) - that is purely down to the IDE gathering the data by examining your sketch and locating the right files to then pass to the compiler.

Thank you very much; I understand it now! But isn't it a bad thing that someone who wants to use my RGBDigit library, also needs to know which other classes and libraries are used by RGBDigit?

@Ralph: With all due credit to the Arduino IDE's developers for a basic download-and-go beginners IDE, it has its limitations. You have met some of them.

@Ralph Yep, that's a shortcoming all right.  One that I addressed in my replacement IDE - UECIDE.  Upgrade to that and you won't see that problem since it can recursively scan libraries for other libraries that they rely on.

See How the IDE organizes things for more details about this. But isn't it a bad thing that someone who wants to use my RGBDigit library, also needs to know which other classes and libraries are used by RGBDigit? - most IDEs need you to tell them, one way or another, which libraries to use. If UECIDE does that automatically, that sounds good. However if you rely upon a different IDE, now you need to tell your users that it only works with that IDE. Maybe you could just explain in the documentation you post with it?

source: Stack Exchange

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

sort: votes


text:
Android Studio project for Redbearlab BLE Shield apps
To interact with its BLE shield, Redbearlab published sample Android apps in the Play Store. The sources for the apps are available on GitHub. How can I build them in Android Studio?

It was much simpler than expected to put together the Android Studio projects. They are on GitHub now.
Note that the apps built from source are actually different from the ones published by Redbearlabs on the Play Store. On top of that, the chat app is not working.

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


text:
Lithium Polymer/LiPo set to power Arduinos
I want to switch from using disposable 9V blocks to a proper setup of 3.7V LiPolys for all my portable Arduino (Uno/Mega) projects consisting of:

only 3.7V LiPo units
charger
upconverter (to 5V)

My questions:

Is this generally a good idea? Or is there a better solution for portable Arduino power?
How should I actually hook the LiPolys up to the Arduino? They usually ship with JST connectors. Should I use the Vin/GND Pins or should I build my own JST/DC-Connector adaptor? I want to create a robust, pluggable solution.
Am I actually losing power twice that way (once in the upconverter and then in the Arduino voltage regulator)?

If you are using the boosting regulator to get 5V you wouldn't need to put it into the Vin pin, so you won't loose power there. The boosting regulators are also efficient anyway.

Keep safety in mind when moving to LiPo batteries.  Many people don't know that they are more volatile than your average battery.  Research/youtube LiPo fire, they're not common but actually do occur.  Lots of people out there charge in a fire retardant lipo bag.  Your choice, but always good to be informed.

Thanks to all the replies! However, I still feel my questions are not actually addressed yet.

If you can get away with it, I recommend not using a boost converter and instead connecting the battery directly to the supply voltage input (the "5V" pin).
The AVR chips used in most Arduinos (but not the Due or Zero [and the Yún and Tre are a totally different kettle of fish entirely]) can operate with anywhere between 2.7 and 5.5 volts, with the ATmega328P found in the Uno able to run with as little as 1.8V. This is a much larger range than the 3.0-4.2V available from rechargeable Li-ion/Li-poly/LiFePO4 cells.
Naturally you will need to make sure that any external components can run with the reduced voltage as well, but quite a few are able to work with anything from 2.0 to 5.5 volts.

When the lipo is near the 3V range and the uno board is at 16MHz one might need to disable the resonator surely?

Or just set the prescaler to /2. For added safety, program the CKDIV8 fuse and set the prescaler in setup().

good point ;) should have thought. +1

You don't mention the DC plug. That should not be used in this case? How can I create a solution with plug?

Isn't the "5V" pin output? Or do you mean "VIN"?

@HaukeHoltkamp: You don't want to use the plug. The plug passes through the linear regulator.

@FuaZe: The "5V" pin is the output of the regulator, but it is the input of the MCU supply rail.

Ah, so you bypass the regulator. Will it work with an USB cable connected?

@FuaZe: Not without effort. It would probably easier in the long run to use a breakout board for the MCU and a USB comm chip with a level translator.

Sparkfun do the ideal solution for you - their "LiPower" shield:

https://www.sparkfun.com/products/10711

It contains the Li-Ion / Li-Poly charger, 5V boost converter, and MAX17043G+U fuel gauge chip.

Note their warning re a hardware bug that disables low voltage cutoff and the need to implement a software work-around.

@RussellMcMahon Yea, that is a bit of a pain - but with the fuel gauge chip you can guestimate how much power is left, and with a simple P-channel MOSFET circuit you can shut off the power completely when it gets too low.

I just ordered one. What is that bug exactly?

There is a facility in the charge chip to monitor the voltage and if it's too low to trigger a shut-down circuit. They just didn't use it. You can connect the + of the battery direct to an ADC input and monitor the voltage yourself if you want to protect the battery against over-discharge.

Consider using 2 x LiPo is series (2S). Vmax is 2 x 4.2V = 8.4V
This may be attractive compared to boosting from a single cell.
This is still < the 9V you used previously.
Vmin is say 2 x 3V = 6V - but higher is better for the LiPos.
You can use a buck converter or a linear regulator as desired, and could use one or other depending on project.
You could even use linear + buck in parallel for applications where sleep current is very small and buck converters may find efficiency at very low I challenging.
Using 5V rather than less than 5 is attractive in that you do not need to ensure the processor speed will accommodate the lower voltages.
Using a linear regulator and 5V:
Efficiency at 4V/cell = 5/8 = 62.5%.
Efficiency at 3V/cell = 5/6 = 83%.
Any sensible buck regulators will be more efficient at more than a few mA but at very low currents that may be acceptable.
2 LiPo in 2S will notionally need balancing occasionally but this is easy to do informally occasionally or using any of the many available charging ICs.

How would I plug the two LiPos together reliably (and portably)? And should I use the Arduino's DC plug?


text:
What is the fastest and easiest way to transmit arduino's sensor data to a PC wirelessly
I have a specific problem :

I'm working on a testing platform. It has to be absolutely isolated, so I cannot wire it back to my PC. I again reiterate it. There is no way to wire it to my PC. IT HAS TO BE ABSOLUTELY ISOLATED
It has about 10 different sensors on it and I need to read sensor's data simultaneously at 100Hz.  It is currently working fine with 16Hz, but I need to improve it further, so I think maybe in future sampling rates higher than 100 is beneficial. 7 Hz is the lowest possible value that doesn't botch the whole things up.
I have a laptop on the platform which reads the sensor data via RS232, then it processes them in a fraction of a second and produce a control signal and send it to the actuators. It has to happen at real-time. Control algorithm is not heavy, it is several PIDs.
It has 6 actuators with the fastest possible reaction time of 0.005 second.
The main sensor currently is Microstrain 3DM-GX1. It is a very good sensors.
I want to add a GY-80 sensor in parallel to 3DM-GX1. I want to test various filtering algorithms on the GY-80's output and compare them to 3DM-GX1.
Platform has 6 degrees of freedom so I think laser transmission is not practical.
Distance between the computer and the platform is at most 3 meters.

For some reasons I am not able to use the laptop anymore. I want to read the sensor's data with an Arduino, preferably Arduino Mega 2560. My problem is that I don't want to load the control algorithm to the Arduino.
IMHO the perfect solution is going to be a Wireless link between the Sensors via Arduino to my PC. This way my PC logs data and also the Control Algorithm can promptly calculate the feedback signal and send it to Arduino which will send them to the actuators. This immensely makes things easier for me.
I think I need a RS232 shield for the 3DM-GX1 & Arduino, + some wireless solution for sending data from both sensors to my computer. Then I need to send back the control signal back to the actuators wirelessly.
Now what is the fast and easy way to transmit the data between PC and Arduino in real-time?
Thank you in advance!

How much bandwidth do you really need? 100Hz isn't that fast, even 4800 baud could do it easily if each sensor has a 4 byte response. In any case "the fastest" is vague and hard to answer.

He said he needs 100hz with 10 sensors. If each value is 16bit 4800 baud WILL NOT cover him. Also "fastest" means sample rate but it also means latency. For lowest latency use the highest baud rate / fastest data bus you can

I updated the whole question. I'd be thankful if you could help me find a good solution.

Ok well then some sort of rf would be better. I would look at bluetooth serial. I can find some links. What sort do latency are you looking to meet ?

I think the type that can support 24 sensors at 16bit 100Hz + 6 actuators at 100Hz is enough. Plus the time my computer needs to send back the signal. I need it to be easy to implement with Arduino.

What kind of latency is acceptable ?

I am new to this, Please forgive my ignorance. I am not sure about the latency! I know that at 16 Hz the 19200 baud-rate was enough. But now we are looking at 100 Hz. I don't know how to figure out the latency required.

The fastest way would be to use a laser link!! Yeah lasers. You could go with wifi or some other custom wireless but lasers will guarantee the highest energy density and therefor best bandwidth.  This guy claims near 10 MB/s with his setup:
http://www.instructables.com/id/Laser-Transceiver/

I think the transceivers have to be pointed at each other all the times. Because my platform has six degrees of freedom. It is rotating around different axes. Please correct me if I am wrong.


text:
How to change byte to int? - Arduino
I have searched everywhere, but can you please help me to get this Byte into int, there are alot of examples on the internet, but not for a beginer like me
CODE:
int Button[] = {2, 4, 7 };

byte E = sizeof(Button);

int I = (int) E;

void setup() {

  Serial.begin(9600);

  Serial.print (I); // has to be 3, currently 61

  }

void loop() {

 }

I don't know why the byte E doen't convert to a int in int I by using the  (int)E command, what would also be convinient would be to read the amount of elements directly  as an int .
(you might wonder, why I want to do this, it is beacause, I am writing a program with multiple buttons, so I just want to add another pin to the array and not have to change the "I" int( the I int is used for loops))

I wish I could slap myself a million times, because when I said Serial.print(I); and not println, I saw 61, but it was 6, so I just divided by two!! Can someone please explain this, I am so confused with this, thnx!

there is no need to declare E or I . . . . . . . . . . . . . . . . . . . .  you can just use a command line like this  Serial.println (sizeof(Button)/sizeof(Button[0]));

The code works correctly. The function sizeof() returns the number of bytes in a variable, not the number of elements. Your array is of type int, which consists of 2 bytes each. So in sum you get 6 bytes for the whole array.
What you want to do (calculating the number of elements in the array) is to divide the number of bytes in the array by the number of bytes for one element:
int I = sizeof(Button)/sizeof(Button[0]);

The conversion from byte to int worked correctly, but you really don't need it. You can calculate things with both types the same way. The only difference is the value range. Since a negative element number doesn't make sense and you surely don't want to define more than 255 buttons, you can choose yourself, what you want to use. Using byte would save you one byte of memory.

sizeof returns the size in bytes. int is two bytes in 8-bit AVR mcu. an array of 3 ints has 6 bytes.
return type of sizeof is size_t which in 8-bit AVR is same as unsigned int

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


text:
Error for compiling for board Arduino Uno
I am new to Arduino and just got this error after writing this code:The error message is pasted after the code. I am kindly requesting for assistance so that someone can help me understand why it isn't compiling. I even changed the board to mega at the tools section but still get the same error

    #include <Tone.h>

int ledred1 = 2;
int ledgreen1 = 3;
int ledorange1 = 4;
int ledred2 = 5;
int ledgreen2 = 6;
int ledorange2 = 7;
int ledred3 = 8;
int ledgreen3 = 9;
int ledorange3 = 10;

int sound = 250;

int trigPin1 = 11;
int echoPin1 = 12;

int trigPin2 = 13;
int echoPin2 = 14;

int trigPin3 = 15;
int echoPin3 = 16;

#define buzzer1 17
#define buzzer2 18
#define buzzer3 19

Tone tone1;
Tone tone2;
Tone tone3;

long distance1=0;
long distance2=0;
long distance3=0;

long t1=-10000;
long t2=-10000;
long t3=-10000;

void checkDistance(long distance, Tone toneobj, int frequency, long *timer);

long measure(int trigger, int echo);

void setup() {
  Serial.begin (9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);

  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(trigPin3, OUTPUT);
  pinMode(echoPin3, INPUT);

  tone1.begin(buzzer1);
  tone2.begin(buzzer2);
  tone3.begin(buzzer3);

  pinMode(ledred1, OUTPUT);
  pinMode(ledred2, OUTPUT);
  pinMode(ledgreen1, OUTPUT);
  pinMode(ledgreen2, OUTPUT);
  pinMode(ledred3, OUTPUT);
  pinMode(ledgreen3, OUTPUT);
}
void firstsensor(){ // This function is for first sensor.
  int duration1, distance1;
  digitalWrite (trigPin1, HIGH);
  delayMicroseconds (10);
  digitalWrite (trigPin1, LOW);
  duration1 = pulseIn (echoPin1, HIGH);
  distance1 = (duration1/2) / 29.1;

      Serial.print("1st Sensor: ");
      Serial.print(distance1);
      Serial.print("cm    ");

  if (distance1 <=200&& distance1>=100) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,HIGH);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=250;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
     }

  if (distance1 <100&& distance1>=50) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,HIGH);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=275;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
        if (distance1 <50&& distance1>=0) {  // Change the number for long or short distances.
    digitalWrite (ledred1, HIGH);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=300;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
      if(distance1>200 || distance1<0){
    Serial.println("Out of Range");
    noTone(buzzer1);
  }
  else{
    Serial.print(distance1);
    Serial.println("cm");
    tone(buzzer1,sound);

  }
}
void secondsensor(){ // This function is for second sensor.
    int duration2, distance2;
    digitalWrite (trigPin2, HIGH);
    delayMicroseconds (10);
    digitalWrite (trigPin2, LOW);
    duration2 = pulseIn (echoPin2, HIGH);
    distance2 = (duration2/2) / 29.1;

      Serial.print("2nd Sensor: ");
      Serial.print(distance2);
      Serial.print("cm    ");

     if (distance2 <=200&& distance2>=100) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, HIGH);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=250;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
     }

  if (distance2 <100&& distance2>=50) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,HIGH);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=275;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
        if (distance2 <50&& distance2>=0) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, HIGH);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=300;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
      if(distance2>200 || distance2<0){
    Serial.println("Out of Range");
    noTone(buzzer2);
  }
  else{
    Serial.print(distance2);
    Serial.println("cm");
    tone(buzzer2,sound);

  }
}
void thirdsensor(){ // This function is for third sensor.
    int duration3, distance3;
    digitalWrite (trigPin3, HIGH);
    delayMicroseconds (10);
    digitalWrite (trigPin3, LOW);
    duration3 = pulseIn (echoPin3, HIGH);
    distance3 = (duration3/2) / 29.1;

      Serial.print("3rd Sensor: ");
      Serial.print(distance3);
      Serial.print("cm");

     if (distance3 <=200&& distance3>=100) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, HIGH);

    sound=250;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
     }

  if (distance3 <100&& distance3>=50) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,HIGH);
    digitalWrite (ledgreen3, LOW);

    sound=275;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
        if (distance1 <50&& distance1>=0) {  // Change the number for long or short distances.
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);

    sound=300;

  } else {
    digitalWrite (ledred1, LOW);
    digitalWrite (ledgreen1,LOW);
    digitalWrite (ledorange1,LOW);
    digitalWrite (ledred2, LOW);
    digitalWrite (ledorange2,LOW);
    digitalWrite (ledgreen2, LOW);
    digitalWrite (ledred3, LOW);
    digitalWrite (ledorange3,LOW);
    digitalWrite (ledgreen3, LOW);
      }
      if(distance3>200 || distance3<0){
    Serial.println("Out of Range");
    noTone(buzzer3);
  }
  else{
    Serial.print(distance3);
    Serial.println("cm");
    tone(buzzer3,sound);

  }
}

void loop() {
Serial.println("\n");
firstsensor();
secondsensor();
thirdsensor();
delay(100);
}

This is the error message:
Arduino: 1.8.13 (Linux), Board: "Arduino Uno"
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer0_pin_port'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer0_pin_mask'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer1_pin_port'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer1_pin_mask'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer2_pin_port'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer2_pin_mask'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer0_toggle_count'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer1_toggle_count'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `timer2_toggle_count'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `__vector_7'
libraries/Tone-1.0.0/Tone.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino Uno.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

You include the Tone library and you use the tone() function from core. They are in conflict.
Use tone1.tone() or remove the Tone library and use the tone() function.

Thank you. I removed the tone library and used the tone () function by itself and it worked

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


text:
Arduino Nano Every Vin 5V fixes I2c problems
I had problems with connecting my devices via I2C. The "requestfrom" constantly hanged and the endtransmission sometimes gave NACK responses.
After disconnecting the devices from 12V and powering one of them via USB (vin with which it was connected to the other arduino's became 3.8V) they stopped misbehaving and worked together in harmony.
How is this possible? Am I missing something? An Arduino Nano Every should be driven between 6-21V?
All devices are "Arduino Nano Every"'s. They used to get 12V directly on Vin and are connected together in a chain by Vin,GND,A5(SCK),A4(SDA)
The master is in the middle of the chain so that the distance is max 20cm.
I also tried powering them via vin with 9V and 5V. Had the same issue.
Already big thanks for the help.

Comments are not for extended discussion; this conversation has been moved to chat.

SO... In the datasheet it says you should use 7-21V on VIN. This gave the problem. I powered the arduinos directly from 5V on the vin. This fixed all I2C problems. Haven't had any problems anymore after changing this.
cheers to all.

You're saying that the voltage on the input side of regulator... causes the internal pull-ups to change value inside of a chip on the output side of the regulator?

it doesn't make sense

Not the way I'm reading it currently anyway.

No i'm saying that I THINK there is something wrong with the voltage regulator of the every and that a higher voltage actually goes through. When using a higher voltage on the I2C bus the pull up resistors are not the right Ohm to give a good data signal. That is why it constantly quit the connection after some time.

Pure guess. But it fixed my problems to just power it via 5V on the vin.

I see, It would be good to make clear that you found that it helped (empirically) and that the business about "actually makes the resistances..." is really speculative.  It still doesn't make sense to me, but I'll grant you something may have changed.  As long as whoever reading this understands what's guess and what's not, good deal.

Is this better?

To my thinking, yes.  You're saying something factual about what you did and what you observed correlated to it.  You removed the bits that seemingly had no fact or theory behind them and had no indication that they were, as you put it "pure guess."  I call that an improvement.


text:
How can I program my self made Arduino board using USB to TTL converter?
Recently I got a coupon for JLCPCB which was 100% discount so, I designed my 10 Arduino board specially for my needs and ordered it from JLC PCB. The schematic of the board is given.  At the time while I was designing the board I  thought of using USB to TTL converter which I have one having RX, TX, VCC and GND pins. So, I forgot to add pinouts for MISO which was D13 and also D12. So, how can I program my board now with that USB to TTL converter?
Describing about my board, it has a separate pinout for programming which has pins like GND, VCC, TX and RX. I tried but couldn't upload the program. Please help me out.
Forgot to mention, it uses ATMEGA328P-AU.

Without the ICSP pins you won't be able to program a bootloader into the board. You will have to bodge in some wires to those pins to connect it to a programmer / other Arduino to program the bootloader. Also your LEDs aren't wired right. You need a resistor for each LED, not just one resistor for the whole set.

@Majenko I think you looked for LED5, It is a RGB LED with common positive termianl. So, I used only one resistor.

@Majenko Can't I program using USB to TTL converter? I watched this video and designed my board. https://www.youtube.com/watch?v=sNIMCdVOHOM . He didn't use those ICSP pins.

Yes, it's an RGB common anode. You need one resistor for each LED. Not one for the common. Ask yourself: what's the forward voltage of "the" LED? And what happens if multiple LEDs are on at once?

You can only program through UART if you have a bootloader. The chip doesn't know how to understand UART data by itself. Only once the bootloader is on there will your UART interface do anything at all.

@Majenko Oh, Yes. I forgot about that and neglected this thing. But can you suggest me any way of programming it?

Like I said: solder in some bodge wires to the pins you need. You'll need a steady hand and some thin wires (I use 30 AWG wire-wrap wire with a high temperature PTFE insulation).

Alternatively you would need to program the MCU with the bootloader before soldering it to the board. Either by first soldering it to some other breakout board with the pins you need, or using a TQFP ZIF socket on a breakout board (although those are expensive).

@Majenko Ok. I will do that. Are other components placed right?

Looks reasonable - apart from those RGB LEDs...

@Majenko Will it have any problem if a resistor is connected to MISO pinout of atmega328p? Should I remove the resistor or without removing I can upload the bootloader? It is of 200 ohms

It should be fine. And D13 is SCK not MISO.

Your schematic doesn't have any bypass capacitors. Not on the ATMega, or the voltage regulators. And D1 is the wrong way around.

At the Arduino Website is a tutorial for making an Arduino on a breadbord.


text:
How to burn bootloader into arduino uno without using another arduino
I need to bootload my Uno board but I do not have another Arduino at my disposal so how do I bootload without another Arduino board

with AVR programmer

Sorry, I am new to this will you mind explaining further or may provide a link to relevant video/document for the procedure @Juraj

perhaps you should explain why do you need to 'bootload'

The USBTinyISP programmer attaches to your computer's USB port and uses the 6-pin ICSP port on your Arduino to program it.  It can program both bootloaders and sketches.  It can be purchased for less than $10 from Amazon or Ebay.
USBTinyISP programmer

There are 3 main options how to write bootloader or program to AVR over ISP.

dedicated AVR programmer or Arduino ISP programmer
other Arduino with Arduino as ISP sketch or similar
parallel port of a computer


text:
Arduino Uno R3 USB is not working
I have a problem with my Arduino Uno board. It's not mounting in my Linux machine, but its power is on and the LED light is glowing. It was working before. After I tested buttons with an 12 V external supply, I am facing this scenario.
I tried lsusb and I checked /dev/ ports. Also, I couldn't find `ttyACM. I tried with another Arduino board and it's working. I think the board is gone, and I need help to fix this problem.
I thought it was a bootloader problem, and I got a new ATmega328P chip board. It is getting power on and the LED is blinking, but the port is not mounted. I tried with lsusb and also ls /dev/ttyACM* with no result.

You could try to flash the firmware of the USB controller.
General steps for Arduino R3 are:

Put the Arduino in DFU mode (the R3 does not require soldering for that)
Flash the firmware using:
dfu-programmer atmega16u2 erase
dfu-programmer atmega16u2 flash Arduino-usbserial-atmega16u2-Uno-Rev3.hex
dfu-programmer atmega16u2 reset

The package "dfu-programmer" is most likely available for your distribution.

If you have to build it from source, because your DFU programmer does not know the ATmega16U2 yet, you will need to install libusb-dev (on Debian-based systems).
Useful links for that:

Resetting your Uno R3's default firmware
Updating the Atmega8U2 and 16U2 on an Uno or Mega2560 using DFU

A useful search term for that is Arduino R3 DFU-programmer.

Maybe you need to "reflash" the FTDI firmware. Sorry, I'm very bad in Linux. To do this, you'll need some software and a HEX file. Check this video on YouTube:
ARDUINO- Upgrading USB FIRMWARE using FLIP
And download the arduino_usbtoserial.hex file.
If it doesn't work, and if your Arduino Uno has the ATmega328P chip as DIP, try to change the ATmega328P chip in the board. Remove this chip carefully. Put another chip in with the bootloader and test.


text:
Cannot drive DC motor with Arduino PWM
I've programmed the Arduino Uno to generate PWM corresponding to the serial input values. And it works fine with an LED. I took the connection from PWM pin 3 (where I set the output) to the base of a BC548 transistor and connected the motor in series with an external motor power supply (Vcc) and the collector and the emmitter is grounded (to both Arduino's GND pin and the external supply's). The motor had a fly wheel diode, 4N4007, and a capacitor of 1 µF for protection.
But when I connect the motor and provide it with the PWM input, it works for a few seconds and then I see a few flashes in the rx and tx LEDs, and it stops working even with a serial input or reset. I need to turn it off and then on to make it work again. The same thing repeats when I connect the motor, but it works fine with an LED.
How can I fix that??

Welcome to Arduino.SE. It would be helpful for us to see your source code and a circuit diagram.

A few questions: what motor model do you use (a link to a datasheet would be good to look at); have you put a resistor between Pin 3 and the transistor base? Which value? Does your program use Serial? Could you post the code (or the relevant parts of it if it is too long)?

I second the resistor between pin 3 and the base of the transistor. The rest sound fine; you've even thought of the flyback diode, and connected the two grounds together.

4N4007? Do you mean  1N4007?

I think your Arduino resets itself because of connection or current overload. Also, please share your connection. What is the voltage of the external source? If it needs high power, try a MOSFET like this.

It's hard to know without an oscilloscope, but as a guess you might be seeing voltage spikes on Vcc at the reset pin due to inductive load dumps from the motor.  Per Atmel app note AVR042, you might try a 5V zener diode from the reset pin to ground and/or a capacitor to snub the spikes.

In addition to the zener or a cap (that should be reasonably close to the motor) you can also use a flyback diode (which is a normal diode wired parallel to the motor) to suppress interference from the motor. See https://en.wikipedia.org/wiki/Flyback_diode

You might also want to consider purchasing a simple and popular L293D motor driver chip.  I teach basic Arduino classes and learning to use this chip is much easier than using transistors and diodes.  The other advantage is the motors can go both forward and backward!
On the following link you can purchase one chip for under $1.00 USD and each chip will driver two motors both forward and backward.
http://www.ebay.com/itm/New-L293D-L293-L293B-DIP-SOP-Push-Pull-4-CH-Four-Channel-Motor-Driver-IC-/371198300958

This is not an answer to the question which was asked.  Additionally, the L293/L298 are antiquated devices with high internal losses which really should not be used for new designs.

Do you have an alternative design that would work better?


text:
125 kHz RFID reader with Arduino
Why is a toroidal inductor being used in the RFID reader described in DIY FSK RFID Reader?
I feel that a toroidal inductor wouldn't be very effective in grasping the changes in electromagnetic field changes.

The word "toroidal" may be misapplied in the instructions. They don't show a picture, but their description doesn't seem to include any toroidal core which would contain internal / exclude external flux in the manner you are thinking of.

Yes, Chris Stratton is right. A toroidal inductor keeps flux within the core, reduces the external flux to near zero and have near zero ability to grasp/convert external flux/magnetic field into electrical signal. Apparently, the word 'toroidal' was used in loose sense referring to a circularly shaped coil.
In an real-life commercial product, a 125 kHz coil typically has many turns on a very thin wire on an open-air core (no core).
An example profession factory made a 125 kHz RFID with a GitHub Arduino library and photos of an antenna coil:

125 kHz RFID module - UART
Seeed-Studio/RFID_Library
125Khz RFID module - UART (wiki)

Also, see Building RFID Card Reader using PIC Microcontroller.
Note, for higher frequency RFID, not shown in above examples, coils have fewer turns than for 125 kHz.

While this is supporting material, you have three answers here none of which answer the actual question which was asked.  At the very least you should be combining them.

So If they mean about circular Inductor for 'toroidal' ......why did they use 'former' word(empty scotch tape as former)....

One link inside the article leads to this, http://forums.parallax.com/showthread.php/105889-World-s-simplest-RFID-reader.  At middle page, the coil, same shape as the factory made example but bigger, is 'just visible' (red color wire) sitting under the white tag.  Big size antenna, in this photo, can work longer, may be 6 to 12 inches, instead of the typical 1 to 2 inch when coil is human palm size

authors: Сергей Говядовский


text:
How is stack memory used for fuctions and local variables?
I wanted to save some values to the EEPROM and also wanted to free up SRAM by avoiding some variable declarations, but EEPROM memory is byte wise.
If I want to store an int value, I have to use some expressions repeatedly. I thought I would make some functions for those. But I am concerned that, if I create a function, it would still occupy SRAM memory, better I declare an int variable instead of using EEPROM.
How are the functions and the local variables stored in SRAM? Does it only store the address of the fuction pointer from the flash memory or all the variables and commands are stored on the stack?

Do remember that EEPROM is only writable for a limited number of times, reading it is unlimited. According to the AVR datasheet EEPROM only has 100000 cycles, which sounds as a lot but when you try to use it as SRAM, it will only last a fairly short period.

OMG! After that, will the EEPROM be useless? I am going to check the datasheet!

The Flash memory also has a lifecyle. It's wiser to not burn the program a lot.

With normal use the numbers given for flash and EEPROM are no problem at all. The equation changes when you start using it like you use SRAM.

Only the function's data is stored on the stack; its code stays in flash.
You can't really reduce SRAM use by using EEPROM instead because, as you have seen, EEPROM isn't addressable in the same way. The code to read and store EEPROM also needs to use some SRAM - probably as much SRAM as you were trying to save! EEPROM is also slow to write, and has a limited lifetime (in number of writes to each byte), both of which make it impractical to use for storing the kind of temporary data we usually put on the stack. It is better suited to saving infrequently changed data, like the unique device configuration for mass-produced devices, or capturing infrequent errors for later analysis.
Edited:
There is no stack for that function until the function has been called, so yes, that is when any of the function's data get's put there. What happens after the function returns is that its stack-frame (its reserved area of SRAM) is no longer reserved. It will eventually be re-used by another function call. Here is a diagram of a C stack in memory. When a stack frame is no longer useful, it is simply released and its memory becomes available to be re-used.

I am thinking this way, when the function is called, only then the data inside it is stored in the stack. After execution of the function, the data are erased from stack/SRAM. Am I right?

The AVR (the microcontroller family traditionally used on Arduino boards) is a Harvard Architecture, meaning that executable code and variables are in two separate memories - in this case flash and SRAM. The executable code never leaves flash memory.
When you call a function the return address is usually pushed to the stack - the exception is when the function call happens at the end of the calling function. In this case the return address of the function that called the calling function will be used instead - it is already on the stack.
  Whether any other data is put on the stack depends on the register pressure in the calling function and in the called function. Registers are the working area of the CPU, the AVR has 32 1-byte registers. The registers can be accessed directly by CPU instructions, whereas data in SRAM will first have to be stored in registers. Only if arguments or local variable are too big or too many to fit in registers will they be put on the stack. However, structures are always stored on the stack.
You can read the details of how the stack is used by the GCC compiler on the AVR platform here: https://gcc.gnu.org/wiki/avr-gcc#Frame_Layout
Read the sections "Frame Layout" and "Calling Convention".

Local variables and function parameters are stored on the stack. However, that is not a reason not to use them. Computers are designed to work that way.
Stack memory is only in use while a function is active. As soon as the function returns, the memory is freed. Stack memory is a GOOD Thing.
You don't want to use recursive functions with lots of levels of recursion, or allocate lots of large structures on the stack. Normal use is fine however.
The 6502 stack is only 256 bytes, but the Apple II works just fine.

So, you mean the function will be saved with all its local variables, parameters and expressions to the stack temporarily, only when it is called? Otherwise it will stay in the program/flash memory? After execution, will it be erased from stack? I was talking about Arduino actually, as it is Arduino Forum, I didn't mention that.

No, only the function's parameters and local variables are on the stack. The code of the function is not saved on the stack. Don't over-think this.

I've been trying quite hard to make an example bit of code to demonstrate what the excellent answers here are saying, without success so far. The reason is that the compiler aggressively optimizes things. So far my tests have not used the stack at all, even with local variables in a function. The reasons are:

The compiler may in-line the function call, thus the return address might not be pushed onto the stack at all. Example:
void foo (byte a)
      {
      digitalWrite (13, a);
      }
    void loop ()
      {
      foo (5);
      }

The compiler turns that into:
void loop ()
      {
      digitalWrite (13, 5);
      }

No function call, no stack used.

The compiler may pass arguments in registers, thus saving it having to push them onto the stack. Example:
digitalWrite (13, 1);
Compiles into:
158:  8d e0         ldi r24, 0x0D ; 13
15a:  61 e0         ldi r22, 0x01 ; 1
15c:  0e 94 05 01   call  0x20a ; 0x20a <digitalWrite>

The arguments are put into registers and thus no stack is used (apart from the return address for calling digitalWrite).

Local variables may well be put into registers, again saving having to use RAM. This not only saves RAM but is faster.

The compiler optimizes away variables you don't use. Example:
void foo (byte a)
   {
   unsigned long bar [100];
   bar [1] = a;
   digitalWrite (9,  bar [1]);
   }
 void loop ()
   {
   foo (3);
   }  // end of loop

Now that's got to allocate 400 bytes for "bar" doesn't it? Nope:
00000100 <_Z3fooh>:
   100: 68 2f         mov r22, r24
   102: 89 e0         ldi r24, 0x09 ; 9
   104: 0e 94 cd 00   call  0x19a ; 0x19a <digitalWrite>
   108: 08 95         ret
 0000010a <loop>:
   10a: 83 e0         ldi r24, 0x03 ; 3
   10c: 0e 94 80 00   call  0x100 ; 0x100 <_Z3fooh>
   110: 08 95         ret

The compiler optimized away the entire array! It can tell that we are really just doing a digitalWrite (9, 3) and that is what it generates.

Moral of the story: Don't try to out-think the compiler.

Most non-trivial functions use the stack to save some registers, so that these can be used to hold local variables. Then we have this funny situation where the function's stack frame contains local variables belonging to it's caller.

Immediately upon a function call entering the function, the first code that is executed is to decrement the stackpointer by an amount equal to the space required for temporary variables internal to the function. The brilliant thing about this is that all functions therefore become re-entrant and recursive, because their variables are built on the calling program's stack.
That means if an interrupt halts execution of one program and transfers execution to another, it too can call the same function without them interfering with eachother.


text:
How to switch an external circuit with Arduino?
I have an object with a series of led and I want to turn on and off these leds from my Arduino. The input of the LED circuit is 24v DC 100mA.
What I've done is the following:

I've cut a wire of this object and I connected one end to the collector and the other end to the emitter of a NPN transistor
I connected the base of the transistor to a digital output (through a 1k resistance)
I connected the power to the led series while the digital pin was LOW (actually completely disconnected)

But with no current on the base of the transistor, the LED has turned on to my surprise. I may have completely misused the transistor and other items. How do I fix this circuit?

Can you describe your circuit a little more? Did you put the transistor between the 24v supply and the LEDs? Also, are you using the same Ground for the Arduino and the external circuit?

I put the transistor between 24v supply and LEDs and I tried using the ground of 24v supply only and also using both the ground

A diagram or photo would be most helpful. I find words can miss out vital detail.

@Cybergibbons http://meta.arduino.stackexchange.com/questions/12/how-do-i-describe-or-draw-my-circuit-in-such-a-way-that-everybody-understands-wh

Thanks guys for the many advices. In the next days I'm going to completely rebuild this project, following jippie diagram, to avoid messing things. I'll let you know

If I understand your writeup correctly, this is what you have built:

simulate this circuit – Schematic created using CircuitLab
What you didn't mention in your question is that you made a connection from Arduino ground to the base of the transistor and the seconds circuit's ground connection. I drew the extra lead 'loose' for illustration only, but you see where it should connect. Current needs a return path, it is not sufficient to only have the forward path (from Arduino through R1 and base-Q1). The return path is emitter-Q1 to Arduino-GND.
Do notice though that the two batteries / power supplies must be floating with respect to each other otherwise you're going to short them out.

Note the transistor part number is just the standard partnumber from CircuitLab. I forgot to remove it and can't edit circuit any more.

From the comments, it sounds like Alessandro actually has the transistor on the other side of the LEDs.

@PeterR.Bloomfield one more reason to upvote http://meta.arduino.stackexchange.com/questions/12/how-do-i-describe-or-draw-my-circuit-in-such-a-way-that-everybody-understands-wh because that is not how I initially understood it. My transistor is "between 24v supply and LEDs" too ... it can be uderstood both ways. Apart from that this is the de-facto standard to solve the problem, unless ...

@jipple which transistor would you recommend for switching between a 5v and a 24v circuit?

I see you made a proper question on the stack from it, so I'll take it that you'll get some good answers there @Martin


text:
Am I Running Out of RAM Or Not?
I'm attempting to drive 300 TM1803 RGB LEDs from an Arduino Uno using the FastLED library. My code works fine for 100 LEDs, but when I go to 150, the arrays that store LED values and my sensor data get corrupted, causing the LEDs to flash colors randomly every few seconds. From what I've read these are exactly the symptoms of running out of RAM, leading to something overwriting the RAM that contains my arrays.
However, with 150 LEDs, the MemoryFree library says I'm only using 920 bytes of RAM, no matter where in my code I measure, and the IDE says 880. Does anybody know what's going on? Is there something using 1100 bytes of RAM for a very short amount of time, so that I can't measure it?
My code:
#include "FastLED.h"
#include <MemoryFree.h>

const byte ledsPin = 3;
const byte sensorPin = A1;

const int numLeds = 300;
const int ledTime = 1000;

const int sensorMin = 0;
const int sensorMax = 512;

const CRGB correction = CRGB(80,255,70); // Cool white
//const CRGB correction = CRGB(160,255,20); // Warm white
const byte hOffset = 170; // baseline hue value
const int8_t hDirection = -1; // 1 or -1, direction of rainbow
const byte s = 255; // saturation (colorfulness)
const byte v = 255; // value (brightness)

const unsigned int arrayLength = numLeds+1;
byte hues[arrayLength];

CRGB leds[numLeds];
byte h = 0; // hue (color)

unsigned long sensorSum;
unsigned int loopCounter;
unsigned int arrayCounterLed;
unsigned int updatesPerLed;
char sp = ' ';
int arrayCounter;

unsigned long time;
unsigned long timeNextLed;
unsigned long timeLeft;
unsigned long time1;
byte route;

void setup() {
  FastLED.addLeds<TM1803, ledsPin, RBG>(leds, numLeds).setCorrection(correction);
  FastLED.setDither(0);
  pinMode(ledsPin, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  delay(10);
  time=millis();
  sensorSum += analogRead(sensorPin);
  loopCounter++;
  if(time >= timeNextLed) {
    timeNextLed = (time/ledTime+1)*ledTime;
    arrayCounter = (arrayCounter +1) % (arrayLength);
    hues[arrayCounter] = (constrain(map(hDirection*sensorSum/loopCounter, sensorMin, sensorMax, 0, 239), 0, 239)+hOffset)%256;
    updatesPerLed = loopCounter;
    loopCounter=0;
    sensorSum = 0;
  }
  for(int led = 0; led < numLeds; led++) {
    time1=micros();
    arrayCounterLed = pseudoMod(arrayCounter - led -1, arrayLength);
    timeLeft = timeNextLed-time;
    byte dist = abs(hues[arrayCounterLed]-hues[(arrayCounterLed+1)%(arrayLength)]);
    if(abs(hues[arrayCounterLed]-hues[(arrayCounterLed+1)%(arrayLength)])<=128) { // if it doesn't cross through 0
      h = (hues[arrayCounterLed]*timeLeft + hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft))/ledTime;
    }
    else if(hues[arrayCounterLed] > hues[(arrayCounterLed+1)%(arrayLength)]) { // if it crosses through 0 forwards
      h = ((hues[arrayCounterLed]*timeLeft + (hues[(arrayCounterLed+1)%(arrayLength)]+256)*(ledTime-timeLeft))/ledTime)%256; // Causing flashing on red pixels?
    }
    else { // if it crosses through 0 backwards
      h = (((hues[arrayCounterLed]+256)*timeLeft + hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft))/ledTime)%256;
    }
    time1 = micros() - time1;
    if(led == 0) {
      Serial.print(dist);
      Serial.print(sp);
      Serial.print(route);
      Serial.print(sp);
      Serial.print(timeLeft);
      Serial.print(sp);
      Serial.print(hues[arrayCounterLed]);
      Serial.print(sp);
      Serial.print(hues[(arrayCounterLed+1)%(arrayLength)]);
      Serial.print(sp);
      Serial.print(hues[arrayCounterLed]*timeLeft);
      Serial.print(sp);
      Serial.print(hues[(arrayCounterLed+1)%(arrayLength)]*(ledTime-timeLeft));
      Serial.print(sp);
      Serial.println(h);
    }
    leds[led] = CHSV(h, s, v);
  }
  FastLED.show();
  Serial.print(updatesPerLed);
  Serial.print(time1);
  Serial.println();
}

int pseudoMod(int a, int b) {
  if(a<0) {
    return a+b;
  }
  else {
    return a;
  }
}

You're running out of memory.  An uno has enough memory to drive ~140 RGB LEDs.  Each LED needs 6 bytes. (i.e. Red 0-255, Green 0-255, and blue 0-255.  So to define one LED's color takes 6 bytes (i.e. #000000 thru #FFFFFF)

Wouldn't it be three bytes per LED?

Memfree does not lie. Either not measuring in depest place. Is it possible the object if led is being copied, just temporarily. Doubling used space. Also that chip does not have clock. Any stuttering can cause to string could latch. turn off interrupts. And or show code.

PLease post your code here, otherwise it is difficult to find out what in your program could potentially use more memory than you think, even for a short amount of time.

Alright, added my code. I did some testing to see exactly how many leds it can handle, which is 126. It seems too close to 128 to be coincidence, particularly considering the array to hold my sensor data has numLeds+1 indexes.

Welcome to Arduino SE! Questions that rely on external sites for context are not allowed on Stack Exchange, so I've copied your code into the question for your (and edited your comment to remove the link dependency). Thanks!

I found it! I was returning an int8_t variable from my mod function, causing me to not be able to iterate over more than 126 LEDs. Now this little Arduino Uno is maxing out it's RAM at 409 LEDs!


text:
How can I filter out noise from ADC lines without delay or signal change?
I'm working on a project with a joystick and I'm trying to keep everything a simple and low latency as possible. I am reading the pots with the onboard 10bit ADC on the ATmega 32u4 but may be upgrading to either a 16bit ADC or 24 bit ADC. How can I filter noise out of the signals?

Have you tried averaging multiple readings yet? Using ADC noise reduction mode?

will give that a try now

how do you use the built in noise reduction on the 32u4 from the arduino programming enviroment?

Not directly. You need to drop to raw AVR code (not assembly though, just direct register manipulation).

#i have no idea where to even begin with that

not sure the best way to implement the multiple reads either

also averaging reads is not going to work either, i do not want to "soften response from the joystick

What kind of noise do you get? High or low freq? Maybe your best bet is to use a simple RC filter, high or low-pass based on the noise you want to reduce

The datasheet has a chapter on the ADC and it talks about noise reduction. There are many aspects of noise reduction, amongst which sleep states and filtered analog power supply rails. For using 16 bit ADC (let alone 24 bit, which is pretty much state of art) to spec, you need a very well designed circuit and PCB and quality components. Otherwise it is just a waste of your money. You can start by changing the reference voltage to one of the internal band gap references. What is the exact problem you are trying to solve?

This sounds a bit like another XY problem http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem.

What is the issue you are trying to solve? Even if you throw away 2bits of the 10bit of ADC due to noise, you still have 256 discrete levels - this is a lot of precision. I think the PS3 controllers only have 16!

And with respect to latency - do you know how much latency is too much latency? There's no point in spending hours trying to get low noise 16bit ADC readings 1000/s when you could just average 10bit ADC readings 100/s.

The Atmel ATmega328 datasheet, section 24.6.1, recommends that you drive the analog input pin with an output impedance of 10 KOhm or less. Also, it recommends that you remove high-frequency components with a low-pass filter. (That low-pass is sometimes called an antialiasing filter).
The simplest possible low-pass filter is a resistor and a capacitor.
  +5V                        +5V
   |                          |
(sensor)---resistor---+---(Arduino)
   |                  |          |
   |            capacitor        |
   |                  |          |
  GND----------------GND--------GND

Contrary to popular belief, it is not possible to make an antialiasing filter in software.
For an initial low-resolution prototype, a quick rule of thumb is to pick the RC time constant at least 10 times as long as the time between samples.
So if you are sampling at around 1000 Samples/second (i.e., a sampling interval of 1 millisecond), then 100 Ohms of resistance and (roughly) 100 uF ceramic capacitor may be adequate.
(The RC time constant here is RC == 100 Ohms x 100 uF = 10 milliseconds).
Many joysticks already have a relatively high output impedance; you'll need to use a resistor with that much less resistance to compensate.
(Sometimes you don't need any additional resistance; but you still need that capacitor between the Arduino analog input pin and the Arduino ground pin).
(Many sensors have an output impedance more than 10 KOhm; people who use them are pretty much forced to use an op-amp chip to get clean signals).
Entire books have been written on signal filtering.
In addition, there are many other techniques for getting higher resolution analog signals, higher speed data collection, and trading off between them --
but they are probably overkill for reading the position of a joystick.

One possible approach is to go for a completely software side solution.
Microsmooth is a signal processing library that I am working on that is specifically intended for low latency, low memory signal smoothing. It is still in development, but even now, most of the filters work in less than 100 microseconds per call while giving fairly good accuracy and smoothing. Also, the header file allows for simple configuration for certain filter parameters.

The noise from your joystick pots will drown out any resolution over eight bits regardless.  They were designed for the very crude game port on a pc and use a copper wiper on a slab of carbon.  Not a terrible recipe for a noise generator.


text:
What's the most efficient implementation of map(x,0,1023,50,250)?
I recently noticed how the map() function in Arduino was bulky in both terms of flash space used and time taken to execute, largely because it deals with long and involves a division and multiplication.
Many times you can replace maps with more basic functions i.e.
output = map(input,0,1023,0,255);

can become
output = input >> 2;

or
output = map(input,0,1023,1023,0);

can become
output = 1023 - input;

I have one line in some code that says:
backlight = map(LDRreading,0,1023,50,250);

How could this be simplified so that it is both space and time efficient?
I'll allow slight differences in output values if it results in a much better solution.

The screenshot shows a base-2 (i.e. binary) result of calculating the constant part of a mapping. You can approximate this multiplication by a constant by a number of shifts added together. You need to break down each multiplication in the result first:
x * 0.0012 = x >> 3
x * 0.00012 = x >> 4
x * 0.00000012 = x >> 7
Then add these together. You are essentially breaking it down into convenient base-2 multiplies (which can always be represented by shifts) and adds - nearly always more efficient.
This doesn't get you right to 250, but pretty close:
>>> for i in range(0, 1024, 34):
...   print (i >> 3) + (i >> 4) + (i >> 7) + 50
...
50
56
62
   [snip]
235
241
247
>>> print (1023 >> 3) + (1023 >> 4) + (1023 >> 7) + 50
247

Do all your processing with a left-justified int (ADLAR=1) though, to minimize errors. The ADC returns a 10bit result, and ADLAR choses if this is aligned to the left or right of the two result registers.

Great answer. I have clarified how you got from the calculator result to the code, hope that is ok.

This is an excellent technique in general, but the original range was 1024, not 1023 (the 0 counts).

How about this, mapping to 50..249?
output = ((input * 25) >> 7)+50;

Your input range was 1024 (0..1023). Output range is 200 (In the original specification, it would have been 201, which does not divide as neatly). These have a gcd of 8, so output = (input * (200/8)) / (1024/8) + 50 will do, and the division by a power of 2 can be expressed with a shift. The nice thing is that 1024*25 still fits into a 16 bit integer, so no longs are needed.
If you want full range, you can try throwing in rounding
output = ((input*25+64) >> 7)+50;

Actually I'd say the input range is 201 as both boundaries are included.

@jfoilpret, I agree, that's why I said my solution (at least without the rounding) only covers 50..249.

Ah ok, sorry I misunderstood your statement "output range is 200"; maybe you should add " (instead of the expected 201)" that would clarify your answer.

You could approximate it quite closely using only two integer operations:
backlight = (LDRreading / 5) + 46;

That effectively maps input range 0 - 1023 onto output range 46 - 250, so it's fairly accurate. If LDRreading is a 2 byte integer type then it should be significantly more efficient (comparatively speaking) than anything which uses long.

The problem with division by a number that is not a power of 2 is that the AVR has no instruction for it, hence the compiler has to generate a bunch of instructions for this computation, which makes the formula longer to calculate.

If the input range is limited in size and you have the memory for it nothing beats a simple lookup-table.
like
unsigned char map[1024] = { 50, 50, << more entries here  >>, 250 } ;
You can pre-compute the content in a part of the program that isn't time-critical or just compute the entire table-content beforehand and put it verbatim in the source-code.
Doing a map is just a read of map[] with the original value as index.
If you input range starts with a non-zero number just decrement all inputs by the lower-bound value so you have a 0-base index for the map array. (That works for negative lower-bounds too !)
At most 1 substract (to adjust for a non-zero lower-bound) and 1 addition to calculate the array-base + index.
And a good compiler will be able to optimize it further.
You can't get more efficient than that, but you do need the space to store the table somewhere.

This is extremely space inefficient though and only marginally faster than the shift/add which gets very very close.

@Cybergibbons It is only marginally yes, but the question was about efficiency. If every cycle counts... Space efficiency could be an issue for larger tables, but I already mentioned that in my answer. I mainly posted this as a more generalized answer because many people don't realize that this technique exists at all. And it has far wider application than just Arduino's. (Check your C-library's implementation of isspace(), isalpha(). Most implementations use this technique extensively.)

"both space and time efficient" was the question :). isalpha() certainly doesn't use a lookup table in avr-libc. It's very memory heavy - 1Kbyte of RAM (1/2) or flash (1/32).

@Cybergibbons Embedded Libc do (mostly) things differently, but generic ones often make extensive use of lookup-tables. I have to admit I missed the "space" word in my initial read of the question.


text:
Arduino Motor Shield and Adafruit CC3000 WiFi Shield Compatibility
My question is similar to this one: Motor shield and wireless transceiver compete for same pins
But not exactly the same!
I would like to know if the solution is as practical, though.
I have an Arduino Mega 2560 R3, with an Arduino Motor shield plugged into it. Now I want to use the Adafruit CC3000 WiFi shield. It plugs in fine, but when reading the specifications, it wants to use pins 13, 12, 11 which are also used by the Motor shield. I also want to use pin 10 as a servo is plugged into it. This is all on a robot so I don't have space to wire the shield separately through a breadboard or similar.
It should perhaps also be noted that I have the motor shield on top of the wifi shield so that the wifi shield can use the ICSP ports which the motor shield doesn't have, therefore any redirecting of pins on the CC3000 will mean that the motor shield pins will also be affected unless I redirect them too, and at that point I feel like it would be all a bit of a mess.
The solution to the other question was indeed to redirect the relevant pins to other free pins on the micro-controller board. However, I noticed that the Adafruit shield has a second row of connector holes next to the main pin holes. In the shield documentation I found, I didn't find any specific reference to these parts and in what situations they could be used, but maybe this is one of them.
My concern with using these is that (as you can see in the second image below, ignoring the coin!), the ports are wired together in the board. Does this mean that it won't make any difference which I use; if I connect a second row of pins/connectors to these points will it simply transmit the same data down both sides? I don't know enough about how electronics work at that level to understand the consequences.
So really my question is: can I use the outside row of ports for my motor shield and the inside row for the wifi shield?

EDIT:
So I've spent until now on the Adafruit forums trying to get some help with this and I still am not all the way there... maybe at this point someone here can cast fresh eyes over my problem.
The Adafruit CC3000 uses both the dedicated ICSP pins and pins 3, 11-13 to transmit the same data. The reason for this is to do with compatibility between different Arduino boards and their versions. E.g. apparently the Uno uses those pins whilst the mega uses some of the pins in the 50s range. I'm not sure what to make of this as the Uno and most of the boards seem to have the ICSP pins, so if they're not used for this purpose then what's the point of connecting to them? Anyway.
As it was explained to me, even if the board can use the ICSP pins to communicate with the microcontroller, it is still sending data via the other pins. So the main pins are essentially useless at this point. To make them useful again, the idea is that you sever the wires that are sending the data through them (often referred to as trace wires). This means that only the ISCP ones will be active for what they are needed, and the main pins will be free for other uses. This is what I ended up doing to my board for pins 11-13, and then for pin 3 I cut the trace wire and wired up the connection to pin 2 as these can both be used for an IRQ (interrupt request) on the Mega and I need pin 3 for the motor shield. The lighting on these pictures isn't the best, but you can see what I've done (the lower part of the second image shows where I made the cuts and the top image shows the wire connection):

After doing that I have been testing the shield connected to both my Mega and my Uno and they both produce the same results. This is using the Adafruit-created library called Adafruit_CC3000_Library. It starts the initialisation, then whilst it's trying to run the code it gets stuck. I traced the problem to a while(1) loop of which you can only exit by meeting a condition which is never met in my case: if (*pucReceivedData == HCI_TYPE_EVNT). This may be because pucReceivedData is not initialised properly, but I don't know why and whether it has to do with my modifications. This happens in the hci_event_handler method of evnt_handler.cpp. This is  through the main file and wlan.cpp so I won't write it here as it is simple enough to follow.
It should also be noted that this shield doesn't work properly with the later versions of the arduino IDE (1.5+) so I had to reinstall 1.0.6. To be honest, I got the same problem on both versions so who knows.
I realise that this is a very specific problem, but I figure that this may leave someone with a lot fewer issues in the future. If anyone has any bright ideas, even if just for testing then I would be grateful.

And I've just realised that pin 3 is used as the PWM for one of my motors and the IRQ for the wifi shield. Pin 3 also has a 'double' next to it, though. Any advice would be appreciated!

Right, have hopefully come up with a solution from talking to Arduino and Adafruit, so will post it up tomorrow (if it works!).

It works!
First I'll say thanks to the moderators/support staff from Adafruit. One dude in particular has tried to help me constantly for the past couple of days or so.
So, following on from my edit, Adafruit told me that the ICSP pins are connected to the control part of the board via the main pins. I should have seen it actually, but I obviously didn't examine and understand it properly. This means that although I severed the connection between the main pins and the centre, the ICSP and 11,12,13 were still connected together. What I actually needed was for the ICSP pins to be connected to the controls to receive the data, and the main pins to be detached from them. So I de-soldered the solder jumpers that I had originally put on the connector plates on the underside of the board (which connect the ISCPs to the main pins), then soldered wire from the ICSP side to the associated breakout holes which are the ones on the inside of the cuts that I made on the board. Here is a picture:

If anyone tries to do this, beware of where you are wiring to! I was very careful to make sure I matched the connecting wires to the correct pins. I have tested it several times (using the example test file that comes with the library) and it works as it should. It works on my Uno R3 and my Mega 2560 R3, which is great, as now pins 11-13 are free to use for my motor shield, or potentially any other shield which may need those pins.
I hope this helps someone else in the future. There doesn't seem to be any information on this particular combination of shields, but as these projects are becoming more popular this may prove to be useful.


text:
bluetooth module with stk500_recv() error
I am trying to dow what is demonstrated in this tutorial. I have altered the original setup a little by adding a level converter to not fry the Bluetooth module and resistors for the LEDs, as well as using only 2 instead of four LEDs (which I adjusted for in code later). other than that I am using the exact same setup, code,and procedure. Yet when I try to run my code on the Arduino. I get the error below. I believe it is due to using Tx/Rx and serial at the same time but I really don't know anything about this. Should I add more libraries?
Should I change the wiring shown in the tutorial link? It seems like I need to use Tx/Rx
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xce
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xce
avrdude: stk500_recv(): programmer is not responding

Here is the code I used from tutorial:
//Coded By: Angelo Casimiro (4/27/14)
//Voice Activated Arduino (Bluetooth + Android)
//Feel free to modify it but remember to give credit

String voice;
int
led1 = 2, //Connect LED 1 To Pin #2
led2 = 3, //Connect LED 2 To Pin #3
led3 = 4, //Connect LED 3 To Pin #4
led4 = 5, //Connect LED 4 To Pin #5
led5 = 6; //Connect LED 5 To Pin #6
//--------------------------Call A Function-------------------------------//
void allon(){
     digitalWrite(led1, HIGH);
     digitalWrite(led2, HIGH);
     digitalWrite(led3, HIGH);
     digitalWrite(led4, HIGH);
     digitalWrite(led5, HIGH);
}
void alloff(){
     digitalWrite(led1, LOW);
     digitalWrite(led2, LOW);
     digitalWrite(led3, LOW);
     digitalWrite(led4, LOW);
     digitalWrite(led5, LOW);
}
//-----------------------------------------------------------------------//
void setup() {
  Serial.begin(9600);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
}
//-----------------------------------------------------------------------//
void loop() {
  while (Serial.available()){  //Check if there is an available byte to read
  delay(10); //Delay added to make thing stable
  char c = Serial.read(); //Conduct a serial read
  if (c == '#') {break;} //Exit the loop when the # is detected after the word
  voice += c; //Shorthand for voice = voice + c
  }
  if (voice.length() > 0) {
    Serial.println(voice);
//-----------------------------------------------------------------------//
  //----------Control Multiple Pins/ LEDs----------//
       if(voice == "*all on") {allon();}  //Turn Off All Pins (Call Function)
  else if(voice == "*all off"){alloff();} //Turn On  All Pins (Call Function)

  //----------Turn On One-By-One----------//
  else if(voice == "*TV on") {digitalWrite(led1, HIGH);}
  else if(voice == "*fan on") {digitalWrite(led2, HIGH);}
  else if(voice == "*computer on") {digitalWrite(led3, HIGH);}
  else if(voice == "*bedroom lights on") {digitalWrite(led4, HIGH);}
  else if(voice == "*bathroom lights on") {digitalWrite(led5, HIGH);}
  //----------Turn Off One-By-One----------//
  else if(voice == "*TV off") {digitalWrite(led1, LOW);}
  else if(voice == "*fan off") {digitalWrite(led2, LOW);}
  else if(voice == "*computer off") {digitalWrite(led3, LOW);}
  else if(voice == "*bedroom lights off") {digitalWrite(led4, LOW);}
  else if(voice == "*bathroom lights off") {digitalWrite(led5, LOW);}
//-----------------------------------------------------------------------//
voice="";}} //Reset the variable after initiating

How did you upload the sketch? With the Bluetooth module still connected? In that case please disconnect it and the upload. Connect again after the upload.

Yes your comment was the solution Thank you so much

How did you upload the sketch? With the Bluetooth module still connected? In that case please disconnect it and the upload. Connect again after the upload.


text:
How can I see the mySerial.print( ) through the serialmonitor on IDE?
I made an object named "mySerial" like this.
SoftwareSerial mySerial(2,3) //pin 2 = RX, pin 3 = TX

also I made pin 13 periodically(0.5 seconds) blink(HIGH/LOW),
then the signal from pin 13 goes directly to pin 2 and pin 0(basic RX pin of UNO). I connected pin 0,2,13 directly with jumper wire.
and in the setup(), I wrote
Serial.begin(9600);

mySerial.begin(9600);

and in the loop(), I wrote
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);

if(mySerial.available()){
    mySerial.println("mySerial!");
}
if(Serial.available()){
    Serial.println("Serial!");
}

when I compile this code and operate arduino,
I can only see the "Serial!" on the serialmonitor.
I think this means that the pin 0 can recognize the signal but the pin 2 cant'
How can I solve this problem?
I can't find what I've missed. Please help me guys!

And what exactly is it you hope to achieve with that setup? It makes absolutely no sense to me whatsoever, and from my initial understanding "Serial!" on the serial monitor is all you can expect to get.

I connected pin 0,2,13 directly with jumper wire. - why? You've lost me here.

Not the most scientific of approaches, and fundamentally flawed at any rate.
You've toggled the input twice over the period of one second, hardly an emulation of any serial port transmission and so one is letting you know there's been a change of state, the other is letting you know that it hasn't received any valid data.
In any case, when you attempt to read the port both will/should correctly give you nothing as a result because there was never anything there to begin with, nor is there anything coming in at the time.
If you want to test serial port comms like this, you are going to have to make a sketch for each scenario and use a real device to test it (like your actual serial port thru the Arduino IDE). Run some test, print the results and upload your second sketch and do it again.
You could even get a bit fancy and have a bit of fun with this and send a command to the arduino to turn off one serial port and turn the other one on, but that's got nothing to do with what you asked, so I won't be writing the code for that here ;)


text:
Execute Code on power off?
Arduino newbie here.
I'm thinking about building an Arduino-based light switch to control the Philips Hue light system in my living room. I have standard wall light switches that power ceiling lamps, and I basically want all Hue lamps that are scattered around the room to be on when the switch is on, and off when the switch is off, so that I don't necessarily need the app or the Hue remote to turn the room's lights on.
My idea is to install an Arduino on the ceiling instead of a normal lamp, so that its power supply is switchable through the light switch.
I would configure it as a Hue remote control, e.g. with ArduinoHue; if all works well, this would control the Hue lamps directly via ZigBee or via WiFi through the bridge - in both cases without having to use additional wiring.
Whenever it gets power, I would have it turnOn() all lamps, and whenever its power supply is turned off, I would have it turnOff() all lamps.
The first part seems simple to me, the second part - not so much.
So here's my question:
Can I execute code in the event of the Arduino losing power, i.e. turn off my Hue lights with its last energy before shutting down? Is there maybe some hardware configuration that would allow me to detect the power off event and retain enough energy through a battery or capacitors to still run the code?
I have never worked with Arduino before, but I do have some colleagues that can help me out when there's trouble.

Bonus question: am I likely to run into noticeable delays when powering on because the device needs to boot/initialize first?

2 Options:
Know, beforehand that it's going to lose power, or sense this so fast that it's able to execute the code.
Use a 'backup' chargable battery that will power the arduino until the lights have been switched off. And then put the arduino in either sleep mode or just power it off.

Is it possible that the program gets disarranged in low power mode??
I did the same with a 1F capacitor to use with a RS 232 connection and it works so far. But sometimes it stops working at all. I guess that at low power, the variables in RAM or the program gets disarranged and fail, after low power and later on power on again. I use counters in the program. Or maybe its not a good idea to use RS232 (with MAX232) where one side always get turned off and on?

For the capacitor part, two one Farad supercapacitors in series (each 2.7 volts max) cost about a dollar, and there is one 10 Farad cap for two dollars each.  I guess that one of these options would work.  And the supercaps should last a very long time.  I'm not an Electrical Engineer -- just a Joule Thief hobbyist, but I thought this would contribute to your design and wouldn't cost much.
As far as balancing the supercaps, since we're close to the 2.7 volt max, I personally would just put three of the supercaps in series with a voltage divider of three 10K resistors in series tied in, but they would probably not really be necessary.
Oh, and the supercaps I spoke about are actually relatively small (10mm dia x 32mm high for each 10F, and 8mm dia. x 13.5 mm high for the 1F supercaps).  Found the 1F at $1.03 as 1572-1270-ND on Digikey.  The 10F was $1.97 each for 1572-1287-ND also on Digikey.

You could do what you want as you describe it, but are making things harder for yourself that you need to. If you can access the circuit from the switch at or near the switch (which should be 'easy' in most cases) then your system does not have to be depowered when the lighting circuit is as you will have access to the mains AC voltage on either side of the switch.
If you do wish to depower the processor when the lights are turned off you can easily add either a backup battery or a capacitor that runs the processor for "long enough". You can also run a processor in "sleep" mode at extremely low power so that it is always running so have no 'wakeup time". And it is possible to power up a processor so that the delay is not noticeable for practical purposes.
However, as Hue Bulbs are Zigbee controlled, with provision ofr both iOS and Android control,  you should be able to control them via Zigbee directly without any connection to their wiring.

Hue control
Hue specifications

Thanks! Your idea of accessing the circuit from the switch is intriguing, but won't work in my particular case: not enough room there - especially for the power supply.

How would I use the capacitor to achieve this? And would I have to throw additional hardware at the system in order to sense the main power going off, or could I do this through software only?

Add a diode to the incoming power. Add the large capacitor (or multiple in parallel) after this. Connect one of the arduino pins to before the diode, so you can measure if the input voltage is low (indicating power loss)(assuming a 5v power supply). But I think you'd need a very large capacitor for this.


text:
ESP8266-01S only coming back from DeepSleep every 2nd time
I'm using an ESP8266-01S for a battery-powered project. The ESP is in DeepSleep, a doorbell relay pulls RST to GND, bringing the ESP to life to do some stuff, before going back to DeepSleep.
My problem is that once the program ran successfully and the ESP is in DeepSleep, the next RST will not bring it up properly. Instead, it will linger in some undefined state, eating around 33.7mA constantly (I went through that battery quite quickly without realizing it).
With serial output enabled, I reliably get something like this when entering those undefined states:
rll�r$�n�l�b|���rb�b�nnlnnbbp�$blrl
Edit: setting the Baud rate to 74880 revealed the above to be the following:
11:58:17.042 -> �
11:58:17.042 ->  ets Jan  8 2013,rst cause:2, boot mode:(3,6)
11:58:17.042 ->

The next RST will then perform successfully, i.e. the ESP comes up, does its thing and goes into DeepSleep. My multi meter shows a power consumption of roughly 15uA, which looks like proper DeepSleep to me.
Another RST would then bring the ESP back into the undefined state, and so on.
Cutting power provokes the same behaviour, so it feels like it could be a hardware thing, some lingering current or something.
I created a minimal version of my program that shows the behaviour on the ESP:
int Led = LED_BUILTIN;

void setup() {
  pinMode(Led, OUTPUT);
}

void loop() {

  digitalWrite(Led, false);
  delay(4000);// Delay 4 seconds
  digitalWrite(Led, true);
  delay(1000);// Delay 1 second

  ESP.deepSleep(0);
}

Is there anything I'm missing or doing wrong, maybe something on the hardware side, to make DeepSleep work on an ESP8266-01S? Do the pins have to be initialized or brought in a defined state somehow? Also, is there a better way than Serial Output to figure out what's going on?
I believe I don't have to connect GPIO16 to RST, since I don't want to wake the ESP by software, but through hardware events only.
Edit: I left the device in DeepSleep over night and RSTed it in the morning, and this time it recovered fine for once.

that is exactly what should be in the included in the question

I reliably get something like this when entering those undefined states perhaps if you set the baud rate of the terminal software to match what the esp is using, the text will provide some insight into the problem - 74880 I believe is the default for ESP's

will check that out, thank you @JaromandaX

thanks again, I got some new information and edited my question accordingly

Hello, i have the same issue and asked for help in https://www.esp32.com/viewtopic.php?f=50&t=39737 but sofar didnt come to any resolution. Did you find a solution @Jan ?


text:
Cannot enter programming mode on Arduino Uno
I have an Arduino Uno that I've been programming with an AVR Dragon through Atmel Studio 7.
I did two things in close proximity, and I'm not entire sure which action is the culprit. I tried using the DebugWIRE interface (for the first time) instead of ISP in the tool select screen. I also hit the Arduino's reset button as Atmel Studio was compiling/uploading to the Arduino (stupid, I know.)
Now I cannot program with ISP the normal way, or do anything really.  If I try to upload to the Arduino I get:

I've tried to use the device programming feature using the Dragon and change the fuses as I've read about in other posts and get:

I've tried burning a new bootloader with the Arduino IDE and the IDE tries ten times, but it tells me that the programmer is not responding.
When I plug my AVR ISP mk2 into a different Arduino Uno I get a nice constant green light. If I plug it into the board I've been discussing it blinks red.
I'm not sure where to go from here...

I think either the chip or the board is fried. Try swap the chip (only the chip) to the other board and retry loading the program.

I swapped the chip from the good board to the bad board and it works.  I guess I'll order another atmega328p.   How can i determine if the chip is actually fried or just needs reprogramming?  I had heard of people forcibly reprogramming a chip after you "goober" it up using hvpp mode with the Dragon.
I was reading an article here that talked about it while trying to debug with dragon which is what i was doing when it happened (as well as resetting the board while atmel studio was programming it).

@Khaines0625 You need something that can perform High Voltage Parallel Programming, which, by applying 12V to RESET pin, bypasses all fuse settings to program the device. You can check out the TL866A (not the CS variant) for this.