text:
Using ESP8266-01 with Arduino uno R3
I am trying to learn how to use ESP-01(AI-Cloud, Black Version) with arduino
Initially, I created an adapter for it that has 4 inputs: RX, TX, Vcc(3.3v), GND I checked it and the wiring seems fine then I attached TX of arduino to TX of ESP and same with RX but with a voltage divider (1k ohm,2kohm),I uploaded arduino with a blank sketch and tried to run commands like AT and AT+CWMODE? but I got no response on the serial monitor.I tried to look for a proper tutorial to do this but, all tutorials show how to upload a sketch to ESP rather than arduino. Then I searched and found this piece of code:
#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                            // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                            // and the RX line from the esp to the Arduino's pin 3
void setup()
{
 Serial.begin(9600);
 esp8266.begin(115200); // your esp's baud rate might be different

 sendData("AT+RST\r\n",2000,DEBUG); // reset module
 sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
 sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
 sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
 sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
}

void loop()
{
 if(esp8266.available()) // check if the esp is sending a message
 {
   /*
   while(esp8266.available())
   {
     // The esp has data so display its output to the serial window
     char c = esp8266.read(); // read the next character.
     Serial.write(c);
   } */

   if(esp8266.find("+IPD,"))
   {
    delay(1000);

    int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                          // the ASCII decimal value and 0 (the first decimal number) starts at 48

    String webpage = "
Hello
&lth2>World!
<button>LED1</button>";

    String cipSend = "AT+CIPSEND=";
    cipSend += connectionId;
    cipSend += ",";
    cipSend +=webpage.length();
    cipSend +="\r\n";

    sendData(cipSend,1000,DEBUG);
    sendData(webpage,1000,DEBUG);

    webpage="<button>LED2</button>";

    cipSend = "AT+CIPSEND=";
    cipSend += connectionId;
    cipSend += ",";
    cipSend +=webpage.length();
    cipSend +="\r\n";

    sendData(cipSend,1000,DEBUG);
    sendData(webpage,1000,DEBUG);

    String closeCommand = "AT+CIPCLOSE=";
    closeCommand+=connectionId; // append connection id
    closeCommand+="\r\n";

    sendData(closeCommand,3000,DEBUG);
   }
 }
}

String sendData(String command, const int timeout, boolean debug)
{
   String response = "";

   esp8266.print(command); // send the read character to the esp8266

   long int time = millis();

   while( (time+timeout) > millis())
   {
     while(esp8266.available())
     {

       // The esp has data so display its output to the serial window
       char c = esp8266.read(); // read the next character.
       response+=c;
     }
   }

   if(debug)
   {
     Serial.print(response);
   }

   return response;
}

I hooked pins according to the code and it worked serial monitor output some lines but with allot of garbage values, This also created a wifi hotspot 'AI-Thinker' which I connected to and opened Ip as shown on debugging. This made ESP try to send string 'webpage' but mostly was garbage.
so my question is, how to properly use esp with arduino to maybe just switch an led on or send data from sensors, super basics?
Is it better to use esp Library and upload sketches to esp and control arduino with it?
Can some one suggest the proper tutorial for this? because even after all this I am still confused that is RX of arduino connected to RX(which makes no sense but given in many of google images) or TX of ESP-01?

Start troubleshooting the serial connection, Arduino <-> ESP01. In the https://www.arduino.cc/en/Tutorial/SoftwareSerialExample you find a example that copy data from Serial (PC) to SoftSerial (ESP01). And Rx is supposed to go to Tx and vice versa. Arduino digital pin 0 (Rx) connects to ESP01 pin 2 (Tx) and Arduino digital pin 1 (Tx) connects to ESP01 pin 7 (Rx).

Possible duplicate of ESP8266 + Arduino Uno: Can't send AT Commands

"Is it better to use esp Library and upload sketches to esp and control arduino with it?"? YES!

@MatsK I was really confused and found that Tx-Rx used when there is need to send commands from arduino code & Tx-Tx used when there is need to send commands from arduino serial monitor this is when arduino isattached to pc via usb, Is this right ?

@dandavis thanks, so I should use my arduino and its IDE to upload sketches to ESP8266 , and then through ESP's Tx Rx pins control arduino and its sensor because I don't have any ftdi chip ,or 3.3v voltage regulator and hoping arduino is enough for this ?

Please remove the part "is it better...", that makes your question opinion based and worth closing. Also you should make only one question: this is not a forum.

To confirm that the serial communication is working, connect the ESP to the Arduino D10 and D11 that is used as SoftSerial pins.
+----+
| PC |
+--/-+
   |       +---------+
   \-------| Arduino |
     USB   +--.------+
              | SoftSerial
              |
           +--\----+
           | ESP01 |
           +-------+

And then upload this code to the Arduino. The code is from https://www.arduino.cc/en/Tutorial/SoftwareSerialExample
/*
 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.

 The circuit:
 * RX is digital pin 10 (connect to TX of ESP01)
 * TX is digital pin 11 (connect to RX of ESP01)

 Created back in the mists of time
 modified 25 May 2012
 by Tom Igoe
 based on Mikal Hart's example

 This example code is in the public domain.
 */

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ;
  }

  Serial.println("Goodnight moon!");

  // Set the data rate for the SoftwareSerial port
  mySerial.begin(115200);
  mySerial.println("Hello, world?");
}

void loop() {

  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <SoftwareSerial.h>

...

SoftwareSerial wifiSerial(WIFI_RX, WIFI_TX);
WiFiEspClient WIFI_CLIENT;

...

void setup() {
  wifiSerial.begin(9600); // or 115200
  WiFi.init(&wifiSerial);
  if (WiFi.status() == WL_NO_SHIELD) {
    printLog("WiFi shield not present");
    // don't continue
    while (true);
  }
  printLog("Connecting to AP ...");
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  printLog("Connected to AP");
}

...

The TX pin of the Arduino goes into the RX pin of the ESP and vice versa: that's the way serial communication works, apart for voltage level considerations.
Another factor you have to take into consideration is the two devices MUST operate at the same speed, once known as Baud Rate: I believe 115200 might be the ESP default speed, but that's programmable.
There are also other two additional parameters which play a role in serial communication, Parity and Data bits, but the default values are more than likely fine and you shouldn't worry about those.
So, in essence, verify your wiring and set the right speed considering some ESP modules run a firmware using non standard speed for serial comm.


text:
How to connect a simple wall switch to arduino GPIO
I am trying to create a smart doorbell, but my problem is that doorbell makes ring any time when nobody touch the button.
I think that the problem is caused for the incorrect way to connect the analog wall button to arduino GPIO.
Basically my wiring diagram is:
Analog Input (A0) to 1 pin of the button.
Ground of the Arduino (GND) to the other pin of the button.
When the button is pressed, the circuit is closed, and doorbell makes ring!
But surely this is not the way to connect a button on the wall because the doorbell sounds on its own.
I leave a picture of the button

Can you provide a schema over the button, power source (AC or DC and voltage) and doorbell (current consumption), preferable with type of component. Or just more data is needed.

jose can u c is absolutely right, you need a pullup. No need to change your wiring however: the Arduino has built-in pullups on all the inputs. You just have to activate them:
const uint8_t buttonPin = A0;  // or any other pin for that matter

void setup()
{
    pinMode(buttonPin, INPUT_PULLUP);
}

This is true. But in some cases where the wires are long, induced noise can overpower the relatively weak internal pull-up resistors. If this happens with external pull-ups, you can decrease the resistance value to increase the pull strength, but with internal pull-ups, you cannot change them.

You need to have a pull-up resistor, see circuit below.
You do not need to connect it to an Analog pin, but a digital pin. Without a pull-up or pull-down resistor, the voltage on the input pin "floats" anywhere, and can give false triggers. This circuit forces the pin to either be 5V or 0V.

simulate this circuit – Schematic created using CircuitLab

This is a good answer; but @santiago-dantuoni should clearly mention if its an AC powered doorbell or a DC powered doorbell;

source: Stack Exchange

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

sort: votes


text:
Using Multiple identical sensors - Beginner
I'm trying to make an interactive installation where I have 6 pressure pads that each control an Air Fan. The pressure sensors ideally will be on chairs.
I would like the changes in pressure to change the speed of the Air Fans.
What is the easiest way for me to do this? Can I do it with just an Arduino?
I haven't bought anything yet as I'm assessing what the best route is.

If you have selected the pressure sensor, please provide details about it -- the type/model affects how this question could be answered.

well i'm not entirely sure what's best but I was thinking just a PM1?

When you say PM1, do you mean a pressure pad, something like this?

yeah that's what i was thinking

In order to better focus your question and generate useful answers, I suggest you edit your question and include that information.   Try to make your question Arduino-specific, and show what you are working with.

Yes one Arduino have enough in and out-put to make your project fly.
The sensor that would detect pressure sensor is called "Force Sensitive Resistor".
Example: http://www.ladyada.net/make/midisense/forcesensors.html
They need some amplifier circuitry that could adapt the sensors low output signal to an Arduino analog input.
And to make six digital output that uses PWM to control the FAN's is also quite straight forward. but may also be subject to some driver circuit.

If you mean this kind of sensor:
The sensor is a simple microswitch with mechanical pressure switching point, which means your Arduino just needs to monitor 6 digital inputs. That is entirely possible.
The sensors would have one side connected to ground, and the other to a GPIO pin on the Arduino, with a pull-up resistor to 5V. Your code should just check each of the 6 GPIO inputs. If the pressure sensor is tripped, the input would be LOW, otherwise HIGH.

This indicate "I would like the changes in pressure to change the speed of the Air Fans." that the OP is asking for an analog answer.

What is the easiest way for me to do this?

you have to figure out how those sensors output their pressure measurements. if it is analog, you will need 6 analog pins, or have to a way to mux 6 analog inputs.
if it is digital, you will have to figure out how - 6 parallel output or 6 serial output; 6 GPIO digital or 6 numerical digital, ......
basically, do your homework first so others can help you help you.

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


text:
Controlling relays with IR and button
What I have:

1 x 8 channel relay
1 x IR receiver
1x Arduino Uno
1x momentary switch
1x breadboard
1x 10K resister

I think the wiring is all ok as for the most part things are working as they should..ish.
Just a few bugs I need to fix.
The goal was to toggle just 2 relays (at the moment) on/off with the hardwired switch and individually toggle the a relay using an IR remote control.
Like I said this sort of works....
If I press the momentary button it does indeed toggle both relays...yeah!
then as long as the 2 relays are toggled to the on position by the momentary switch I can toggle each relay using buttons on a remote.
However if I turn the relays off with the momentary button I can't turn them on with the remote. Also if I turn off one of the relays with the remote and then press momentary switch it alternates the toggle between the 2 relays rather than just turning the other one off.
I have been using various example sketches to achieve all this and just trying to stitch them together as best I can but something is telling me that the approach is all wrong and that I should maybe be looking into Boolean's perhaps?
Hope you can shed some light on this for me.
#include <IRremote.h>
#define irPin 8
IRrecv irrecv(irPin);
decode_results results;
const int buttonPin = 2;
const int relay1 = 13;
const int relay2 = 12;
int relay1State;
int relay2State;
int buttonState;
int lastButtonState;
long lastDebounceTime = 0;
long debounceDelay = 50;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn();
  pinMode(buttonPin, INPUT);
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  digitalWrite(relay1, relay1State);
  digitalWrite(relay2, relay2State);
}

void loop() {
  if (irrecv.decode(&results)) {
    switch (results.value) {
      case 0xFF30CF:
        Serial.println("Button 1 Pressed");
        relay1State = ~relay1State;
        digitalWrite(relay1, relay1State);
        delay(250);
        break;
      case 0xFF18E7:
        Serial.println("button 2 pressed");
        relay2State = ~relay2State;
        digitalWrite(relay2, relay2State);
        delay(250);
        break;
    }
    irrecv.resume();
  }

  int reading = digitalRead(buttonPin);
  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }
  if ((millis() - lastDebounceTime) > debounceDelay) {

    if (reading != buttonState) {
      buttonState = reading;

      if (buttonState == HIGH) {
        relay1State = !relay1State;
        relay2State = !relay2State;
      }
    }
  }

  digitalWrite(relay1, relay1State);
  digitalWrite(relay2, relay2State);
  lastButtonState = reading;
}

Welcome Michael. First, just a suggestion, in line 30 and 36 change the ~ to !. Now just clarify us one thing. Suppose you start arduino and press the the buttonPin once. You make both relays ON. Now with remote you make relay 1 OFF. So current state is relay1 OFF and relay2 ON. Now you press the buttonPin again. What do you want the new relay states to be? (not what is happening right now, what you intend to be)

Thank you! That changes has solved one issue of being able to turn on the relays from the remote while first being in the off state with the button.  To answer your question: I was hoping to turn both relays off or on using the button (like an all on all off switch/override) which works when both are on or off but if one is on and the other is off they toggle opposite to each other, so I guess it is doing what the code is telling it to do, just not the way I want it. I want the one that is left on to turn off with the button then when i press the button again both will turn on. Thank you!

That's because you're telling it "relay1State = !relay1State;". IE invert the relays' state when you press the button. If you want them both to go off and on together, you need an extra variable, to store whether the next time you press the button, you want on or off. So have the button flip that variable, then whatever value that variable is, send that to the relays. Also at the top, "int relay1State;" should be "int relay1State=0;" because in your setup, you send that state to relay1 without defining it first. By luck, it works anyway.

Also I should add, having the button do on AND off is a bit confusing! If one is on, other is off, then which state do you want them both to go to when you press it? I suppose if you only have one button you're a bit constrained by that. A better design would involve buying another button! Then you'd have one ON and one OFF. And the user would know which one to expect, where if currently you have one relay in each state, should the button switch them on or off? Maybe an LED or something could inform the user of that, but an extra button would be better I think.

So according to your comments this should be the code if no mistake was made
#include <IRremote.h>
#define irPin 8
IRrecv irrecv(irPin);
decode_results results;
const int buttonPin = 2;
const int relay1 = 13;
const int relay2 = 12;
int relay1State = 0;
int relay2State = 0;
int masterState = 0;
int buttonState;
int lastButtonState;
long lastDebounceTime = 0;
long debounceDelay = 50;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn();
  pinMode(buttonPin, INPUT);
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  digitalWrite(relay1, relay1State);
  digitalWrite(relay2, relay2State);
}

void loop() {
  if (irrecv.decode(&results)) {
    switch (results.value) {
      case 0xFF30CF:
        Serial.println("Button 1 Pressed");
        relay1State = !relay1State;
        digitalWrite(relay1, relay1State);
        delay(250);
        break;
      case 0xFF18E7:
        Serial.println("button 2 pressed");
        relay2State = !relay2State;
        digitalWrite(relay2, relay2State);
        delay(250);
        break;
    }
    irrecv.resume();
  }

  int reading = digitalRead(buttonPin);
  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }
  if ((millis() - lastDebounceTime) > debounceDelay) {

    if (reading != buttonState) {
      buttonState = reading;

      if (buttonState == HIGH) {
        masterState = !masterState;
        relay1State = masterState;
        relay2State = masterState;
      }
    }
  }

  digitalWrite(relay1, relay1State);
  digitalWrite(relay2, relay2State);
  lastButtonState = reading;
}

what I've done is create a masterState that only changes whenever you press the buttonPin and by pressing it will also change both relays to the value of new masterState independently of their actual state.
Another advice: is a bad practice to not initialize variables before use, because when you declare it is not granted that they are automatically equal to zero.

You sir are a big help! That's solved my problems! I'm not sure I totally understand how my program works just yet but it's slowly sinking in. But I can say I have learned much more and quicker by just getting stuck in and attempting small projects, rather than just reading book after book or watching tutorial after tutorial. Program to learn, not learn to program I think they say :)  Thanks again for your help. That was a real head scratch-er for me!  Think I might fire a photo-resister into the mix now..why not eh? This is fun! :D

Go on Michael. Keep testing things. To help you undertstand your original code, what you did was invert the current state of the relays when you pushed the buttonPin. The ! gives you the logical not of a variable. So if a var is 1, true, using ! will give the negation of that var. This is why you needed a master state to do what you wanted. Go on and keep practicing! Happy coding

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


text:
How to enable maximum Dead Code Removal?
I am running out of code and data memory space on ATMega328P.
Code size is big as I used several libraries, but, I only use a few functions of those library.
Apparently, the default IDE is only doing a partial job in dead code removal (remove unreferenced code and data).
Some experiments shows:

A normal program that uses several Arduino libraries is 22 kilo bytes in code size.
Rename setup to o_setup.
Rename loop to o_loop
Add
void setup(){};
void loop(){};
Code size is 8 kilo bytes while the program is 'empty' effectively.
Start a new program.
Add
void setup(){};
void loop(){};
Code size is 0.5 kilo bytes

Apparently, the IDE (linker called by IDE) is doing a 'partial' dead code removal job, as reducing code from 22kB to 8kB (case 1 and 2), instead of 0.5kB (case 3).
How can I enable maximum dead code removal function (reclaim code space occupied by unused library functions)?

Be aware that some libraries declare global variables, instances of a class, for which the constructor code (and all its dependencies) will be linked into the final program. Hence the simple fact to #include a library but not use it can still add a lot of code in the link process.

I need all the lib as they are physical hardware chip drivers. But, I only use a few functions of each lib. Could you kindly explain "instances of a class, for which the constructor code"? Global var can be 'optimized/removed' by linker which see that it is declared by never used, by looking at assembly language linkage map, right?

In case 2 did you also remove all the code outside of  loop2 and setup2. E.g. to use the Servo library you'd use #include <Servo.h>  Servo myservo;. Here Servo myservo; actually creates in instance of the Servo class, with all it's memory it needs for its private variables.

Can you list the libraries you require?

I have several hardware sensor boards and each has its own needed lib (driver) to work. For example, the LCD driver has many functions for drawing line, circle, pie, fill, etc. but I only use the draw 3D text mode. In worst case, I can manually delete un-used part of the library source. Can take time as inter-dependency is everywhere. The LINKER should be able to do this task automatically. The question is how to turn it on and command it to perform? Compiler can still allocate code/ram space. linker is final gate keep who has full and latest info, which code where, call who and called by who

For example, many hardware sensor driver lib has 2 function to give SI and Imperial units. I use one only. Some has hardware changeable setting like, range, gain, parameters. I do not need many of these as I use many default settings.

Enable your IDE's verbose of the compile via the preferences. From there you can see exactly what and how it is being compiled.
In short the IDE (and toolchain) will compile everything and anything it can find into an object. Where only the used code is compiled in the linking phase, as garbage collection is enabled with the "--gc-sections" command.
Note that the optimization level is "-Os" or "Optimize for size". In IDE 1.0.+ this appears to be hardcoded. Where as in IDE 1.5.+ the compiler options are configurable, in "\arduino-1.5.6-r2\hardware\arduino\avr\platform.txt" can be customized to meet your needs.
Where you can use the avr-objdump command as described in https://stackoverflow.com/questions/15291750/does-importing-libraries-load-everything-in-arduino/15296808#15296808.
I would recommend 1.5.6r2 and not 1.5.7 as the gcc commands won't run individually without some path manipulation.

you can try to change the -Os to -O2 or -O3 to get smaller. S is supposed to include 2. However, I have seen it in some cases get smaller.

-O2 and -O3 ask the compiler to optimize its output for speed, not for size. Thus the compiled binary will get larger rather than smaller.

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


text:
Is there a way to shift through sensors
We are doing a project and have to use around 25 temperature sensors. Is there a way to shift through them on one Arduino similar to using a shift-register?
It is a set of analog sensors in a fridge.

Think about using a pair of 16-channel multiplexers. Sparkfun have a board that might be suitable.

What kind of sensors? analog, digital, ...? How far are the sensors? 1mm from each other, 10cm, 2km, ...?

@sempaiscuba, why not flesh out that comment and add it as an answer.

sorry for not being specific enough.
it is a set of analog sensors in a fridge.

@sempaiscuba
thanks for the answer. we will probably go with that.

@sa_leinad Done. :)

As I mentioned in the comments, one way to do this is to use a multiplexer.
You haven't said which temperature sensors you are planning to use, so I'll illustrate this example using the TMP36 Analogue temperature sensor.
Now, if you were using just one of these, the connection would be trivial:

But you want more sensors than available pins. That's where the multiplexer comes in.
I'm going to illustrate this using 16 sensors and the Sparkfun 16-channel multiplexer breakout board which is based on the 74HC4067 multiplexer. For 25 sensors, you could use a 32-channel multiplexer (like the Analogue Devices ADG732, for example), or just combine two 16-channel multiplexers (which is probably cheaper, but requires a little more care in the wiring).
[If your soldering skills are OK, I wouldn't even bother with the Sparkfun breakout board myself. It's pretty simple to connect something like this on protoboard, or make your own PCB.]
The 16 sensors are connected to pins Y0 - Y15 on the 74HC4067 (pins C0 - C15 on the Sparkfun board). Take care to note which sensor is connected to which pin!
With 16 inputs, we need 4 bits to address them. The address pins are labelled S0 - S3. The Sparkfun datasheet for their breakout board includes a Truth Table mapping the addresses to the inputs:

The input from the selected device becomes the output from the multiplexer (pin Z on the 74HC4067; the SIG pin on the Sparkfun breakout board).
The diagram below shows one way of connecting 16 TMP36 analogue temperature sensors to an Arduino Nano using the Sparkfun breakout board:

Note the mapping chosen for the address pins:

D5 -> S0
D4 -> S1
D3 -> S2
D2 -> S3

This makes the drawing layout simpler, but may not be the most intuitive mapping when you come to write your code. My advice is to assign meaningful labels to the pin-mappings in your code, and document that decision with comments! (I'm sure that I'm probably preaching to the choir here, but this may help someone reading this in the future to avoid some of the pitfalls.)
Now, you cycle through a loop:
while true {
    increment the address to be written to pins D5-D2 (note the order)
    read the input on A0
    <do whatever you need to do with the temperature reading>
}

And Robert is the male relative of your choice.

Have you looked at OneWire temperature sensors? You connect them to a bus IC and the bus IC to your Mcu. This allows you to multiplex many sensors.
You can also forego the master bus IC and just bit bang using a GPIO pin. The Arduino OneWire library uses this approach.
You can learn a lot about from this one wire sensors tutorial.

Another way to do this is with a series of actual shift registers (74HC595 or similar, daisy-chained.)
The shift register outputs drive a transistor. Each transistor has its collector connected to the temperature sensor, and the emitters are all collected into a single Arduino input. Depending on the number you shift into the shift register, you can pick any of the temperature sensors you want to query.

The LED in this simplified schematic actually represents the Arduino input pin. Shift a 2 into the register to query T1; 4 to query T2; 8 to query T3, and so on.

If you are using analog sensors, consider using the CD4051B analog multiplexer (link to data sheet). It's great for expanding analog I/O pins.


text:
Esp8266-01 and Arduino
I recently bought an ESP8266 (ESP-01s). When I first connected it to Arduino,AT commands showed. Then when I uploaded other code,the commands stopped showing. I flashed it using many flashing tools and firmwares and the flashing was successful but AT commands still not showing. ESP is not responding to any code I execute in Arduino.

"Please help" How exactly? You need to give something to work with. Code, wiring, etc.

When you put code on the esp you remove the AT code. If your way AT commands you have to put on the AT code

ESP-01 by default shipped with AT Command firmware, when you upload an Arduino sketch, it override the firmware and replaced with Arduino boot loader and sketch (i.e. ESP-01 became an Arduino). If you want to get back the AT Command firmware, see my answer here on how to do that.

This is a common problem with newcommers to the ESP8266. It ships with AT commands working and as soon as you try putting your own code on it the AT commands stop working.
Well, of course they do.
The AT commands aren't something the ESP8266 does. It's something the software installed on the ESP8266 does, and you just deleted that software and put your own software on.
You can either have AT commands (by installing the correct AT firmware for your board) or run your own software on it - not both (unless, of course, you write your software in such a way that it responds to AT commands, but that's a completely separate thing...)


text:
ESP8266 How to run MQTT Client and Http Client in one loop
Scenario: Existing project: read soft serial then do http post
New project: MQTT player from other (MrDIY / MrDIY Audio Notifier · GitLab)
Objective: Combine together (Result: successful )
Issue: When read serial do http post, after http.end(). MQTT client disconnect.
It taks above 10 secs to reconnect.
The only way I found is just a workaround to add ESP.restart(); after each http post.
But that's stupid. I have spend more than 10 hours to fix this issue.
Any one can help?
Eg code:
void loop() {
  if (!mqttClient.connected()) {
    mqttReconnect();
  }
  mqttClient.loop();

  if (mySerial.available() > 0)  //Checks is there any data in buffer
  {
    receive_data = String(receive_data) + String(char(mySerial.read()));
    //Serial.println(receive_data);

    if (String(receive_data).indexOf("lighton") >= 0) {
      Serial.println("lighton");
      receive_data = "";
      http.begin(client, switchon);
      http.addHeader("Content-Type", "application/json");
      http.addHeader("Authorization", auth);
      int httpCode = http.POST("{\"entity_id\": \"switch.sonoff_guest_room\"}");
      Serial.printf("[http] GET... code: %d\n", httpCode);
      http.end();
      //ESP.restart();
    }
}

Please add URL to things you refers to!

Did you ever figure this out? I'm struggling with the same problem myself now, I also can only make one initial http request, all subsequent requests fails with status -5...


text:
L293D motor shield
I have the L293D motor shield on top of my Arduino UNO.
The L293D has a servo attached of 5 volt and a motor of 12 volt there is an external power supply.
If I remove the jumper of the board and power my motor with the 12 volt? Will my servo of 5 volt still have the 5 volt of the Arduino or is this connected to the external 12 volt?

this cannot be answered without examining the motor shield schematic diagram

Or at the very least a link to (or even photo of) the shield in question (there is no "The" L293D shield, there's many shields that have that chip on them) so that we have a chance of working out what you're talking about.

No , your motor will actually get power from outside but the Servo Motor will be powered by arduino even if the jumper removed because the ln298 shield is mounted on the arduino.


text:
Which are the unused digital pins after L293D motor shield is installed on a Arduino Uno board?
I have just started my first project on Arduino. I have an Arduino Uno and an L293D motor shield.
I have installed the motor shield on the Arduino Uno board and the motor shield covers all pins of the Arduino Uno board. The motor shield is connected with four gear motors and one servo motor.
Can I use digital pins 2-13 to make some LED flashing circuit?
Which digital pins are used by the Motor shield and which pins are not used?

It is L293D motor shield. A0 and A5 are used in the code. Four DC motors and one servo motor is used.

Link to the shield? Is it really a L29D, or is it actually a L293D? What pins are used in the code?

@MatsK, I notice in your edit you removed tt from gear motor description. It looks like this is a brand/model. See here: https://www.adafruit.com/product/3777. I didn't know what it meant at first either so I had left it in.

If this is the same board as seen on Banggood Which may also be seen at Adafruit
The schematic shows most of the digital pins in use
D3  - PWM2B
D4  - DIR_CLK
D5  - PWM0B
D6  - PWM0A
D7  - DIR_EN
D8  - DIR_SER
D9  - PWM1A
D10 - PWM1B
D11 - PWM2A
D12 - DIR_LATCH

The analogue pins A0-A5 are still free - these can be used as digital pins.


text:
"Serial" does not name a type -> How to solve this problem?
I'm trying my best to solve this problem but it didn't changed
The red line was drawn on the last Serial.println */
int cds = A0;
int led = 12;
int trig1 = 2;      // Left Trig
int trig2 = 3;      // Right Trig
int trig3 = 4;      // Front Trig
int trig4 = 5;      // Upside Trig
int echo1 = 6;      // Left Echo
int echo2 = 7;      // Right Echo
int echo3 = 8;      // Front Echo
int echo4 = 9;      // Upside Echo
int vib1 = 10;      // Left vib
int vib2 = 11;      // Right vib

void setup() {
        pinMode(led, OUTPUT);

        pinMode(trig1, OUTPUT);
        pinMode(trig2, OUTPUT);
        pinMode(trig3, OUTPUT);
        pinMode(trig4, OUTPUT);
        pinMode(echo1, INPUT);
        pinMode(echo2, INPUT);
        pinMode(echo3, INPUT);
        pinMode(echo4, INPUT);
        pinMode(vib1, OUTPUT);
        pinMode(vib2, OUTPUT);

        Serial.begin(9600);
}

void loop(){
  long duration1, value1;
  long duration2, value2;
  long duration3, value3;
  long duration4, value4;

  // Ultra Sonic Sensor Part1
  digitalWrite(trig1,LOW);                           // Trigger Output
  delayMicroseconds(2);
  digitalWrite(trig1,HIGH);
  delayMicroseconds(5);
  digitalWrite(trig1,LOW);
  duration1 = pulseIn(echo1,HIGH);                   // Read Pulse Duration
  value1 = microsecondsToCentimeters(duration1);     // Count Distance
  delay(10);

  // Ultra Sonic Sensor Part2
  digitalWrite(trig2,LOW);
  delayMicroseconds(2);
  digitalWrite(trig2,HIGH);
  delayMicroseconds(5);
  digitalWrite(trig2,LOW);
  duration2 = pulseIn(echo2,HIGH);
  value2 = microsecondsToCentimeters(duration2);
  delay(10);

  // Ultra Sonic Sensor Part3
  digitalWrite(trig3,LOW);
  delayMicroseconds(2);
  digitalWrite(trig3,HIGH);
  delayMicroseconds(5);
  digitalWrite(trig3,LOW);
  duration3 = pulseIn(echo3,HIGH);
  value3 = microsecondsToCentimeters(duration3);
  delay(10);

  // Ultra Sonic Sensor Part4
  digitalWrite(trig4,LOW);
  delayMicroseconds(2);
  digitalWrite(trig4,HIGH);
  delayMicroseconds(5);
  digitalWrite(trig4,LOW);
  duration4 = pulseIn(echo4,HIGH);
  value4 =  microsecondsToCentimeters(duration4);
  delay(10);

  //Commend Part (Vibration motor)

  // Print Out Value
  Serial.print(" dist1 =");
  Serial.print(value1);
  Serial.print("(cm)");
  Serial.print(" dist2 =");
  Serial.print(value2);
  Serial.print("(cm)");
  Serial.print(" dist3 =");
  Serial.print(value3);
  Serial.print("(cm)");
  Serial.print(" dist4 =");
  Serial.print(value4);
  Serial.print("(cm)");
  delay(10);
  //

  // Initialize PIN Mode
  digitalWrite(vib1,HIGH);
  digitalWrite(vib2,HIGH);

  // 진동모터1,2,3
  if (  value4<60  or  value3<60)
  digitalWrite(vib1,LOW);
  digitalWrite(vib2,LOW);

  delay(100);

  digitalWrite(vib1,HIGH);
  digitalWrite(vib2,HIGH);

  if (0< value1 && value1<60)
  digitalWrite(vib1,LOW);

  delay(100);

  digitalWrite(vib1,HIGH);

  if (0< value2 && value2<60)
  digitalWrite(vib1,LOW);

  delay(100);

  digitalWrite(vib1,HIGH);
}

// Function of Count Distance

long microsecondsToCentimeters(long microseconds)
{
  return microseconds/29/2;
}

        int cdsValue = analogRead(cds);

        Serial.print("cds =  ");
        Serial.println(cdsValue);

        if (cdsValue < 38 ) {
                digitalWrite(led, HIGH);
        } else {
                digitalWrite(led, LOW);
        }

Your code would be a lot easier to read and find mistakes in if you formatted it. I see that you did that in the IDE, but in your question, you need to highlight all of the code, then click the "{}" button to make it look like code in your question.
When I pasted your code into my IDE and auto-formatted it, the answer was immediately clear: after the function microsecondsToCentimeters() you have written some code that is not inside any function. C and C++ don't allow that. The error message wasn't very helpful - the compilers easily get confused by our mistakes - but in this case, looking at the formatted code made it clear.
All of the executable code in a C or C++ program (Arduino IDE uses C++) must be inside a typed and named function. Since that is what the compiler was looking for, it seems to have interpreted the word "Serial" as a function type, but no type was defined with that name.
I'm not sure where you intended the lines from the end of long microsecondsToCentimeters() to go, but they need to be inside of a function, somewhere.


text:
What is the maximum wire length for serial communication between two Arduinos?
I am building a project in which two Arduinos will be linked by three wires: TX an RX for serial communication and a common GND. What would be the maximum length of the wires here before communication gets affected?
I am using an Arduino Mega R3 on one side and an Arduino Mini on the other one.
I have no particular requirement for the Baud rate, I could use the lowest one if this helps in any way.

You need to specify

The order of range you are interested in - is it in the order of metres, tens of metres, kilometers or interstate ?:-) . ALL are possible with suitable compromise.
How you intend to connect to the circuit - direct Arduino pins, high/low buffer, differential drivers, ...

If you use 5V/0V "unipolar" then at say 9600 baud you can get many metres with suitable drivers. If you use an Arduino pin directly wire resistance and inductance will start to matter as range increases.
At 300 baud you can achiever hundreds of metres with twisted pair cables. As range increases aspects like cross-talk from the other circuit and external noise increase in importance. At longer ranges having 4 wires with signal + ground twisted together in each case helps BUT it is likely that at ranges of interest 2 wires plus ground will work OK.
If you are prepared to use enough voltage and slow enough signalling you can signal over thousands of miles - as was done with very early telegraph cables. The thousands of volts needed and signalling speeds of perhaps a few bits per second will be a disincentive in most cases.

The distance I would like to cover is approximately 40-50 metres from inside our house to the gate outside. My intention was to connect the relevant Arduino pins directly with a cable that I found from a previous intercom installation.

Some danger to Arduino with longish runs of cable. Induction, leakage, electrostatic charge. (Lightning & ground rise from power fault only maybe but ...). Reverse clamp diodes to power supply rails on all lines a good idea. Basic driver IC a VERY good idea. Even an xx74xx14 hex  Schmitt inverter IC at each end would be useful. (where xx is varies with family). Proper line drivers even better but that's a start. IF your Arduino is valuable use a buffer.

Thanks everyone for the comments and suggestions.
In order to find out if I can cover the given distance (ca. 40m) with a simple connection, I gave it a try with two Arduino Uno, respectively set up as a sender and receiver. The boards are directly connected via the TX/RX lines (pins 0 and 1) at 9600 bits per second. The sender sends out a test string every second while the receiver is listening for incoming data.  I am using an existing line (no info about the quality/specs of this cable.
Anyway, the sender/receiver pair seems to work without any problem at this distance and configuration.

Thanks, would you have any particular suggestion / link to an IC or driver chip?

@hobie  At 50 metres and 9600 baud you can probably achieve OK results (try it and see) with almost any 5V digital driver IC and even just digital output ICs. A useful starting point are the Schmitt trigger CMOS inverters typically 74xxx14, CDxxx14, MM.....14. Look for Schmitt triggered inverters, avoid the lowest drive power ones.

@hobie  This Digikey catalog search for Schmitt inverters quantity 5 price ordered  provides many alternatives. This 74LV1G14 single gate package costs 26c each in 1's and 5c in thousands. They can (probably) be used at the receiving end to produce squared up receive signals ...

@hobie and at around 30 mA at 4,5V Vcc (32 max) they provide a useful amount of line drive. There are also many dedicated bus drivers and many otyer Schmitt gates.

This is not exactly what you are asking for but it would be robust and available at low cost in the form of arduino modules. The way I would do it is use a Can Driver and receiver on each end. They are inexpensive differential line drivers. There is nothing that prevents using Async at whatever baud you want up to about 1 megabaud. Run a wire for ground it helps. You will wind up using 5 conductors or 2.5 pairs of wire. Ethernet cable should work fine. You can send some power over the spare wires if you like. You also have the option of using some of the automatic CAN drivers that automatically switch to transmit mode when data is sent and receive otherwise, this will keep you to three wires.


text:
Problem with while loops while detecting frequency of a signal
I just started to use the unusual part of Arduino language (avr) like interrupts, accessing registers, etc in Arduino IDE. I wrote a program to calculate the frequency of a digital signal using external interrupts.
The following code is to calculate timeperiod of a digital signal, the output of the color sensor (TCS3200) which depends on the color filter choosen via S2 and S3 pins, as in the code. That is, color sensor produces 50% duty cycle square pulses of frequency dependent on the power of the light incident on it. So when sensor faces red color, output signal's frequency in red color mode (by setting S2, S3 pins) is more than the frequency in blue and green modes. Thus we can detect the likeliness of the color which it faces w.r.t  R,G,B.
When this code is uploaded in the Arduino, it failed to print the values as expected in the serial monitor i.e. its stuck in while loops. But when Serial.print(e) statement in the while loops are uncommented, it is able to print the required time periods. I am unable to figure out the problem here, which is making Arduino to be inside the while loop when no statements are in it.
// INT0 interupt is used i.e. digital pin 2
int ti=0,tim=0,e=0,S2=4,S3=5;

void Interruptinit() //initializing interrupt INT0
{
  cli();
  EICRA =  0x02; //Control register
  EIMSK =  0x01; //Mask register
  sei();
}

void setup()
{
  pinMode(2,INPUT);
  digitalWrite(2,HIGH); //enabling pull up register
  pinMode(S2,OUTPUT);
  pinMode(S3,OUTPUT);
  Interruptinit();
  Serial.begin(9600);
}

ISR(INT0_vect)
{
  tim=micros()-ti;
  ti=micros();
  e++;
}

void loop()
{
  digitalWrite(S2,0); digitalWrite(S3,0); //switching over red filtered photodiodes
  e=0;
  while(e<2)
  //Serial.print(e) //waiting till interrupt is addressed 2 times
  ;
  Serial.print("red:");
  Serial.print(tim);

  digitalWrite(S2,0); digitalWrite(S3,1); //switching over blue filtered photodiodes
  e=0;
  while(e<2)
  //Serial.print(e)
  ;
  Serial.print(" blue:");
  Serial.print(tim);

  digitalWrite(S2,1); digitalWrite(S3,1); //switching over green filtered photodiodes
  e=0;
  while(e<2)
  //Serial.print(e)
  ;
  Serial.print(" green:");
  Serial.println(tim);

}

Watch the semicolon right after the //Serial.print, even if it's intentional, I wouldn't use it to keep the loop spinning, an empty brackets are much more readable

Whenever you modify non-local variables in an ISR, it's important that they are declared as volatile. This tells the compiler that the contents may change unexpectedly, ensuring it doesn't use out-of-date cached copies somewhere else. If you don't do this, the code can behave in unpredictable ways, such as outputting the wrong value under some circumstances.
Since the variables are bigger than 1 byte, it's also necessary to disable interrupts around non-ISR code which uses them (e.g. in loop()). This is because interrupts could be triggered at any time, potentially half way through an operation which reads/writes them.
You can use noInterrupts() and interrupts() to disable/enable interrupt handling.

The main problem here is that when while loops are accessing variable "e" here, to check whether e<2.... program's unable to come out of loop (ISR is not changing "e").. but when some code like "Serial.print(e)" is kept in while loop...i.e. it spent some time not accessing "e" to communicate serially, its able to come out of the loop. Actually this must not be a problem as when ISR are addressed the main stack remains as it is n returns where it left.

@Wupadrasta I suspect the ISR is executing correctly, but the while loop is simply operating on a different (cached) copy of e. Declaring it as volatile should solve that.

Thanks a lot... I learned about volatile qualifiers but didn't know where to use them.It worked... Thanq.


text:
Way to use other baud rates in console or different input/output rates
I want to send some test codes to a MIDI synthesizer, so I wrote a program that lets me just type in hex codes on the serial monitor and send it over serial as the byte value. For example typing "90 45 63" should turn on note 0x45 with a velocity of 0x63.  This part works ok and I have the arduino hooked up to a midi connector and from there to a midi synth. I've verified that this works ok with some test code.
Where I'm having trouble is that MIDI requires a rather unorthodox baud rate of 31250.  The problem is then that on an Arduino Uno, I don't see how I can enter serial data when the Arduino's serial monitor doesn't allow that baud rate. Also trying to set that baud rate under Linux using stty generates an "stty: invalid argument ‘31250’" error.  So is there a way to use a different baud rate for input than for output or some other solution here?  I do have a Teensy 3.1 with multiple Serial ports, but its kinda tied up at the moment and I just thought I could use an Uno for this.
UPDATE: It works now. Something to keep in mind when working with complex external components like a professional synthesizer. The Roland JV-880 that I'm interfacing with wasn't receiving program changes even though I was sending the 0xC0 0x03 codes or whatever. This is why I made this debugging program to begin with. After searching around and being stumped, I looked around the system settings on the synthesizer and discovered a setting called "System MIDI Rx switch Program change=OFF". After I changed that to ON the program change codes worked. Sometimes the problem is nothing in your code or circuit.

Have you considered using a MIDI port?

@IgnacioVazquez-Abrams Sorry I should have mentioned. I have the arduino hooked up to a female midi connector and from that up to the midi port on a synthesizer. That aspect is working fine and I've been able to play notes using a simple test program.

So... do you then have two serial connections, one to the host and one MIDI?

No, I was just using the TX (pin 1) on the arduino to send data over the midi port and then the usb connection to the computer.  Maybe the serial port can't be shared like this?

The Arduino Uno is powered by an ATmega328P microcontroller. This
microcontroller has only one UART which is not capable of using
different baud rates for sending and receiving.
You could look into the different software serial port implementations
for the sending side. Another solution would be to continually change
the baud rate: each time you get a complete message from the serial
monitor,

you switch the baud rate to 31250 bps
you send the packet to the midi synth
you Serial.flush() to make sure the bytes have actually been sent
you switch back the baud rate to whatever you used in the serial
monitor

You will probably see some garbage on serial monitor as it receives the
bytes at the wrong rate, but that should not be an issue.

Software serial! That's brilliant and was easier than I expected.  So far it works fine, although its a bit slow to send the codes. Not sure why. But it works for my purposes. Thanks.

Well, I was actually thinking about the alternatives to SoftwareSerial, like AltSoftSerial (there are others). The standard SoftwareSerial is not very good, as it tends to block interrupts for too long. But if it works fine for you, then it's all that matters.

I tried AltSoftSerial and it is about the same, but if I use stty to setup the serial and just write to it with echo "904540" > /dev/ttyACM0 its much faster. Instantaneous even. If I use the Arduino IDE serial console the messages take about half a second to arrive on the synth.


text:
Can't play melody and FastLED lights at same time
I'm trying to make an OO state machine based program to play music and lights at the same time. It uses the FastLED library and a 13 pixel neopixel strip.  I've confirmed that with the currently wired setup that I can separately play music and also separately run the FastLED Cylon example code. However when I upload the code below it just kinda hangs out and doesn't do anything and doesn't even print the statements in the setup statement.  The weird thing is that if I comment out the Lights lightstrip1() instantiation line and the lightstrip.Update() line, it does play the melody part ok.
#include "pitches.h"
#include "FastLED.h"

class Melody{

// notes in the melody Minuet in G.
int melody[126] = {
  NOTE_D4, NOTE_G3, NOTE_A3, NOTE_B3, NOTE_C4,
  NOTE_D4, NOTE_G3, NOTE_G3,
  NOTE_E4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_FS4,
  NOTE_G4, NOTE_G3, NOTE_G3,

  NOTE_C4, NOTE_D4, NOTE_C4, NOTE_B3, NOTE_A3,
  NOTE_B3, NOTE_C4, NOTE_B3, NOTE_A3, NOTE_G3,
  NOTE_FS3,NOTE_G3, NOTE_A3, NOTE_B3, NOTE_G3,
  NOTE_A3,

  NOTE_D4, NOTE_G3, NOTE_A3, NOTE_B3, NOTE_C4,
  NOTE_D4, NOTE_G3, NOTE_G3,
  NOTE_E4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_FS4,
  NOTE_G4, NOTE_G3, NOTE_G3,

  NOTE_C4, NOTE_D4, NOTE_C4, NOTE_B3, NOTE_A3,
  NOTE_B3, NOTE_C4, NOTE_B3, NOTE_A3, NOTE_G3,
  NOTE_A3, NOTE_B3, NOTE_A3, NOTE_G3, NOTE_FS3,
  NOTE_G3,

 // Second part
  NOTE_B4, NOTE_G4, NOTE_A4, NOTE_B4, NOTE_G4,
  NOTE_A4, NOTE_D4, NOTE_E4, NOTE_FS4, NOTE_D4,
  NOTE_G4, NOTE_E4, NOTE_FS4, NOTE_G4, NOTE_D4,
  NOTE_CS4, NOTE_B3, NOTE_CS4, NOTE_A3,
  NOTE_A3, NOTE_B3, NOTE_CS4, NOTE_D4, NOTE_E4, NOTE_FS4,
  NOTE_G4, NOTE_FS4, NOTE_E4,
  NOTE_FS4, NOTE_A3, NOTE_CS4,
  NOTE_D4,

  // BACK TO G MAJOR!!!!
  NOTE_D4, NOTE_G3, NOTE_FS3, NOTE_G3,
  NOTE_E4, NOTE_G3, NOTE_FS3, NOTE_G3,
  NOTE_D4, NOTE_C4, NOTE_B3,
  NOTE_A3, NOTE_G3, NOTE_FS3, NOTE_G3, NOTE_A3,
  NOTE_D3, NOTE_E3, NOTE_FS3, NOTE_G3, NOTE_A3, NOTE_B3,
  NOTE_C4, NOTE_B3, NOTE_A3,
  NOTE_B3, NOTE_D4, NOTE_G3, NOTE_FS3,
  NOTE_G3

  };

// note durations: 4 = quarter note, 8 = eighth note, etc.:
float noteDurations[126] = {
  4, 8,8,8,8,
  4, 4, 4,
  4, 8,8,8,8,
  4, 4, 4,
  4, 8,8,8,8,
  4, 8,8,8,8,
  4, 8,8,8,8,
  1.5,

  4, 8,8,8,8,
  4, 4, 4,
  4, 8,8,8,8,
  4, 4, 4,
  4, 8,8,8,8,
  4, 8,8,8,8,
  4, 8,8,8,8,
  1.5,

  // Second part

  4, 8,8,8,8,
  4, 8,8,8,8,
  4, 8,8,8,8,
  4, 8,8, 4,
  8,8,8,8,8,8,
  4, 4, 4,
  4, 4, 4,
  1.5,
  4, 8,8, 4,
  4, 8,8, 4,
  4, 4, 4,
  8,8,8,8, 4,
  8,8,8,8,8,8,
  4,4,4,
  8,8,4,4,
  1.5
  };

  unsigned long OnTime;  // This will be the time in millis to turn on a note.
  unsigned long OffTime; // This will be the time in millis to turn off a note.

  int ToneState;
  unsigned long previousMillis;

  int speakerPin;
  int noteNumber;
  int maxNoteNumber;

  public:
  Melody(int pin) {
     speakerPin = pin;
     pinMode(speakerPin, OUTPUT);
     previousMillis = 0;
     OnTime = previousMillis;
     ToneState = 0; // Off
     noteNumber = 0; // Start at the first note.
//     maxNoteNumber = sizeof(noteDurations); // This turns out to 504 for some reason.
     maxNoteNumber = 125;

  }

  void Update() {
     unsigned long currentMillis = millis();

     if (ToneState == 0 && currentMillis >= OnTime) {
       tone(speakerPin, melody[noteNumber]);
       OffTime = currentMillis + (1000 / noteDurations[noteNumber]);
       ToneState = 1;
       Serial.print(noteNumber);
       Serial.print("/");
       Serial.println(maxNoteNumber);

     } else if (ToneState == 1 && currentMillis >= OffTime) {
       noTone(speakerPin);
       OnTime = currentMillis + ((1000 / noteDurations[noteNumber]) * 0.30);
       ToneState = 0;
       if (noteNumber < maxNoteNumber) {
         noteNumber += 1;
       } else {
         Serial.println("RESET");
         noteNumber = 0; // Reset to the begining of the song.
       }
     }
  }
};

class Lights {
    int ledPin;
        int ledCount;
    unsigned long NextOn;
        int led_R;
        int led_G;
        int led_B;

        CRGB leds[12];

    int ledOn;
        int lightdelay;

    public:
    Lights(int pin, int ledcount, int led_r, int led_g, int led_b) {
      ledPin = pin;
      pinMode(ledPin, OUTPUT);
      digitalWrite(ledPin, LOW);
      ledCount = ledcount;
      led_R = led_r;
      led_G = led_g;
      led_B = led_b;
      ledOn = 0;
      lightdelay = 100;
      NextOn = 0;
      FastLED.addLeds<NEOPIXEL, 7>(leds, ledCount); // It complains if I try to use a variable for the 7. It has to be a constant.
      for (int i = 0; i < ledCount; i++) {
        leds[i] = CRGB::White;
      }
      FastLED.show();
    }

    void Update() {
      unsigned long currentMillis2 = millis();

      if (currentMillis2 > NextOn) {
         if (ledOn >= ledCount) {
           leds[ledOn] = CRGB::Black;
           ledOn = 0;
           leds[ledOn] = CRGB::Red;
         } else if (ledOn == 0) {
           leds[ledCount - 1] = CRGB::Black;
           leds[ledOn] = CRGB::Red; // Need to put RGB to HSV converter in later.
         } else {
           leds[ledOn - 1] = CRGB::Black;
           leds[ledOn] = CRGB::Red; // Need to put RGB to HSV converter in later.
         }
         Serial.print("LED: ");
         Serial.println(ledOn);
         Serial.println(NextOn);
         FastLED.show();
         NextOn = currentMillis2 + lightdelay;
         ledOn++;
      }
    }

};

Melody melody1(2);

Lights lightstrip1(7, 12, 250, 0, 0);

void setup() {
  Serial.begin(115200);
  Serial.println("Started");
}

void loop() {
   melody1.Update();
   lightstrip1.Update();
}

Any ideas?

Are you sure the program is uploading properly and you haven't run out of memory or something daft like that?  (Of course that wouldn't explain why it runs when you comment things out, unless the compiler is optimising things away).

Well, I'm not 100% sure, but its not erroring out and it says the program is only using about 5K (out of 32K) of memory. This is on an Arduino Uno by the way.

Can you comment out JUST the "lightstrip1.Update();" line and see if it works. Then, put that line back in and comment out JUST the "melody1.Update();" line.  That way you can see if the problem is in the constructors or the Update functions.

You could try your luck with Adafruits' NeoPixel library. I also highly advise to use const unsigned char as the type of noteDurations (and simply multiply by 2. This will save you quite some room and avoids floating point math. And depending on the type of a single note int melody[126] could better be const unsigned char or const unsigned int.

What type of Arduino do you have? 32K SRAM is pretty nice? You're probably confusing SRAM and PROGRAM/Flash memory. An Arduino Uno only has 2kbyte of SRAM (so you can save only 2.000 bytes of variables).

sizeof(noteDurations); // This turns out to 504 for some reason.
Yes. sizeof gives you the length, in bytes. So only the note durations already use 0,5KB of your precious 2KB RAM. An float is 4 bytes.

Thanks for all the comments, suggestions and cool tricks to bring memory consumption down. I can also reduce the pitches array size to be a char array by taking it down 2 octaves and then multiplying by 4 on the fly.

I asked on the FastLED library github page and they provided me with the correct instantiation for the object:
Lights *lightstrip1;

void setup() {
  lightstrip1 = new Lights(7,13, 250, 0, 0);
}

void loop() {
  lightstrip1->Update();
}

It now works fine and plays the music and the lights simultaneously without issue.

The WS2812 device requires precise timing down to +/- 150 x 10-9 seconds.  For details look at this chip specification.  As such, it is likely the FastLED library uses processor resources that can not be shared.  Look through the FastLED library's code to verify this.
It appears your sketch plays a note, changes the LED pattern then repeats this cycle.  Assuming the resources for FastLED are initialized in the constructor of the library, you might consider destroying and re-instantiating the FastLED class for each of these cycles.
added later...
Comments about memory space and large amounts of static data in the sketch have merit.  Consider moving your static (unchanging) data from limited RAM to FLASH memory.  This resource explains how this is accomplished.

Hmmm, understand what you are saying but I would think if this were the problem that commenting out the melody1.Update line would still allow the lights to update, but it doesnt. It's almost like the object instantiation of the lights object is crashing the Arduino. I say this because it doesn't print the lines on serial in the setup statement if I have the lights enabled.

I think to understand what is happening and how to fix it, you would have to analyze the FastLED library, the built in millis() function and the Atmel chip specification. Although the comments about limited RAM space has merit.  You said you can control the LEDs if you remove all other code.  But what happens when you put back (only) the large arrays?  Will the LEDs still work?

You have a good idea. When I have time, I think I will build a version that doesn't have the melody part in it at all to see if the FastLED library can handle being updated from an object.  I'm beginning to think this is the problem.


text:
7 Segment Display SET UP
I am new to Arduino.
I have been trying to connect a 7 segment display (3 digits) to my Arduino and I was successful, but I am not doing any connection to ground. I do not find the data sheet so I am not sure if this connection is well done.
My doubt is: Is the connection to ground necessary? Or how do Arduino pins work? I am using 12 pins of the Uno to do the set up.
Thanks
My set up is the following:

Is the display common anode or common cathode?

To tell you truth @IgnacioVazquez-Abrams, I really don't know. How can I verify this? is there any special annotation on the device? or any special behavior?

Which pins control which display lights up and which ones control the segments, and which one do you have to apply the positive voltage to? (Also, your pin notation is incorrect; pin 1 is at the bottom left and they go up counter-clockwise.)

Great, thanks for the help and for the correction on my notation. Tomorrow I will keep posting the things you are requesting once I verify on the Arduino how the display is working.

Could you give a reference to the LED display? That would help check out the wiring. Also, have you already written a sketch to drive the display? Posting it here would help as well.

One danger I see in your circuit is that it seems you are driving at least 7 LED segments at the same time (by the way, why do you need 12 pins to drive 3 digits of 7 segments? 11 should be enough, considering there is also a decimal point to drive: (7+1) x 3). That might draw too much current out of the Arduino and fry it.

I second @jfpoilpret. The pins on the arduino can only provide/sink 40mA of current. I also see you added the resistors to the digits instead of the segments. That way, the more segments are on, the dimmer the display will be. It's better to put the resistors on the segments. Also use a resistor value that will limit the current to no more than 5mA per segment. That way, even if all segments are lit, the total current will be below 40mA.

I don't know exactly how your display is wired exactly, but it is certain that some sort of multiplexing is going on, since A: there is no wired ground, and B, you are controlling more LED's than you have pins going to the display.
Multiplexing manages this by using some trickery and persistence of vision. The pins for each part of the segment are all wired together. For example, the top segment on each of the three segments are all connected to one arduino pin. The common anode/cathode (depending on your specific display) for each of your three displays are wired separately however. Turning only one of the common pins on will cause only one display to function when the other pins set which segments are on. The micro controller then changes which common is active and what segments are on to illuminate the next character very quickly. It pulses between segments so quickly you cannot tell they are only on one third of the time each.
The wiring inside the display will likely look similar to this:
http://www.modd3d.com/articles/wp-content/uploads/normal-multiplexing-s.gif


text:
Controlling Arduino through MATLAB?
I had a Roboteq motor controller, but it wasn't fast enough. I'm hoping Arduino will be faster.
Supposing that the transfer is fast enough for my purposes, how can I read angular velocity, given that I have an encoder? Honestly, I'm not totally sure how to hook it up to an Arduino board.
I can't find a name for my encoder... This is the datasheet though.
Can anyone help me with how to hook it up, and what commands to use in MATLAB?
Thanks.

Do all the processing on the Arduino, and supply the results to Matlab over serial.
I'm not 100% sure about your particular encoder, but generally encoders talk in "Grey Code".  This is a series of bits which allow you to know the direction the encoder has turned.
There are a number of libraries and tutorials for Arduino dealing with encoders.

http://playground.arduino.cc/Main/RotaryEncoders
http://www.hobbytronics.co.uk/arduino-tutorial6-rotary-encoder

The one I use comes from here:

http://www.pjrc.com/teensy/td_libs_Encoder.html

It would be best to use a library with interrupt routines on pins 2 & 3 (these support external hardware interrupts), so whenever the pin gets a signal from the encoder, the Arduino can act on it immediately.  If you do not use these pins, and have time-consuming processing in the loop(), it's easy to miss 'ticks' from the encoder.
#include <Serial.h>

// Rotary Encoder (Interrupt Driven)
#define ENCODER_PIN_A       2 /* must be pin2 for interrupt */
#define ENCODER_PIN_B       3 /* must be pin3 for interrupt */
#define ENCODER_OPTIMIZE_INTERRUPTS
#include <Encoder.h>
Encoder encoder(ENCODER_PIN_A,ENCODER_PIN_B);

void setup()
{
    Serial.begin(115200);
    // Gentlemen, start your encoders
    pinMode(ENCODER_PIN_A,INPUT_PULLUP);
    pinMode(ENCODER_PIN_B,INPUT_PULLUP);
}

void loop()
{
    unsigned long start_time = millis();
    Serial.println("Dear Matlab...");

    while (1)
    {
        unsigned long now = millis();
        unsigned int encoder_value = encoder.read();

        // Do whatever angular velocity processing is needed here
        unsigned long ticks_per_ms = encoder_value / (now - start_time);

        // Send the result back to Matlab
        Serial.println(ticks_per_ms,DEC);
    }
}

I think for your encoder the "A" and "B" outputs are where the grey code will be coming from.  These would be connected to Arduino pins 2 & 3.
Obviously the code above is not a complete solution, and needs to take care of edge-conditions like overflow of millis() after some time, etc. etc.

Hmm... Interesting. Do you know how many iterations per second that could run? I'm just afraid that a serial connection would be too slow. Could I do it over USB somehow?

115200 baud gives you over 10,000 bytes per second.


text:
Connecting Arduino Yun to wifi with 802.1X authentication
Is it possible to connect the Yun to wifi using 802.1X authentication?  802.1X is WPA2-Enterprise that uses a username and password (per user) instead of one password (for every user).  I don't see a way to do it from the Yun web interface, but is there a way to do it from the linino terminal?
As far as I know, the Atheros AR9331 chip should be capable of this, but I don't see a way to do it with the software included on linino, there must be a way to install something for this?

The question would ultimately be if this is requires any hardware changes, and if not if it is implemented in code which is open source and modifiable, or some propriety binary-blob chipset firmware or driver.


text:
Arduino Yun Serial Terminal Overflow Issues?
EDIT: after reading up on some stuff and with the help of the comments people left, I'm certain that it's an overflow issue, but I'm not sure how to solve that...
So I just got an Arduino Yun today and have been figuring out how to use it.  I seem to have run into a problem though and haven't been able to solve it...
I stripped down the YunSerialTerminal sketch that allows accessing the yun linux terminal over a usb com port:
void setup() {
  Serial.begin(9600);      // open serial connection via USB-Serial
  Serial1.begin(250000);   // open serial connection to Linux
}

void loop() {
  if (Serial.available()) {             // got anything from USB-Serial?
    int c = Serial.read();              // read from USB-serial
    Serial1.write(c);                   // write to Linux
  }
  if (Serial1.available()) {            // got anything from Linux?
    int c = Serial1.read();             // read from Linux
    Serial.write(c);                    // write to USB-serial
  }
}

It works for the most part, but has some odd differences from connecting via ssh over wifi.
It seems to be dropping random characters from the screen (due to buffer overflow):

As you can see, it's messed up some of the text such as md5um which should be md5sum and the formatting is all off.
It gets even worse when launching elinks terminal web browser (which works beautifully when connecting via ssh over wifi):

I've also tried different programs (other than putty), including the arduino ide serial monitor, and they all produce the exact same result (and yes I'm setting them to the correct port speed as well).
Does anyone have any idea what I'm doing wrong?  I've tried many different port speed combinations and they all produce the same result.  It seems that the atheros-atmel link is set to 250000 baud (Which is why I have to use that speed on Serial1 in my sketch), but can that be changed?  I've read some things about how 250000 is way too fast when the atmel is involved, but is there a way to change that speed without losing the Bridge library functionality?
Also, could someone else with a yun try this sketch and verify that it works? Load it, and connect with putty via serial (using whatever com port arduino bound to) and double tap tab key to see if the command listing is missing letters.

Are you sure you only have one application reading serial data?

Nearly positive, all I have open is putty. Also, it only drops characters when something large is printed out, when I'm typing or holding down enter to get blank prompts, it appears fine.

Looks like your serial buffer is overflowing. Does the original code work as intended? Did you remove software handshaking (XON/XOFF) by any chance?

The original code has the same issue (I stripped it down in an attempt to fix it. I noticed the software handshake settings in putty and left it set to xon/xoff, is there something in the code I need for it to work?

I'd agree with Jippie on overflow, specially the atheros-to-atmel channel is fast enough that linux can easily overwhelm any possible buffer in the atmel before the data can drain at the drastically slower USB-serial baud rate.  You could try increasing the external baud rate.  XON/XOFF might work, but it would need to be applied to the atheros-to-atmel link.

@ChrisStratton I've read up on a bunch of stuff, and I agree it's definitely overflow.  However, I've tried running both serial connections at 250000 and it still has the exact same issue.  I'm thinking that maybe the USB-serial isn't capable at running at 250000?  In which case I'd need to lower the atheros-atmel link to a slower rate.  Do you have any idea how to do this or XON/XOFF for that link?


text:
Serial characters are corrupted
I try to send an "a" string via serial with
Serial.println("a");

and I receive "Oy=" in Ascii or {4F}{79}{3D} in Hexa.
Where should I start investigating? What could be wrong?  Baudrate is 9600 on all sides.
PS: I suspect the cable. Any hints how to check it?

It sounds like wrong baud rate. If you set them both the same then maybe the Arduino is running at the wrong speed.

On your setup function
Serial.begin(115200);//<- 115200 is the baud rate, serial monitor must match this speed
while(!Serial);//<-- wait for Serial to be ready

see: https://electronics.stackexchange.com/questions/9264/what-standard-uart-rates-are-there for more baud rates


text:
Advisability of Using Bit Fields in Structs
I have to track a large amount of data (for an Arduino) in a program while taking care of a fair amount of other business.
I started with a struct like this:
struct MyStruct
{
   // note: these names might as well be foo bar baz
   uint8_t color;
   boolean state;
   uint8_t area;
   uint8_t number;
   uint8_t len;
};

I have an array of 800 of these. At 5 bytes each, that's 4Kb, or half the ram on the Arduino Mega.
I changed to a struct like this:
struct MyStruct
{
   uint8_t color : 3; // max value 7
   // uint8_t state : 1; *** moved, thanks Ignacio ***
   uint8_t area : 5; // m.v. 31
   uint8_t number;
   uint8_t len : 5; // m.v. 31
   uint8_t state : 1; // m.v. 1
};

I understand this reduces the size of each instance to 3 bytes, for a total of 2.4Kb in my array.
I have read that in some implementations / chipsets using bit fields in structs can lead to less efficient execution. Obviously this is a more efficient use of memory, but my question is:
How does the Arduino handle bit fields? Will it be better, worse, or negligibly different in terms or speed when iterating through an array of bit field structs? Is there a good way to test this?

That order will use 4 bytes. Get that 1-bit field out from between the other 8.

@Ignacio Amazing... you just shaved another 9% off my total memory usage.

The reason bit fields in structs can lead to less efficient execution is because of word alignment restrictions. E.g. if they cross the natural 32/64 alignment, causing multiple accesses. This should not be a problem for the ATmega

The question you need to ask yourself is if you are most worried about running out of RAM, program memory, or CPU cycles - this is a situation where you can optimize quite a bit for one at cost of another and some impact on the third.  At a certain point you should also ask if an ATmega-based Arduino is really the right platform.

I was able to restructure the program to use the array index where I was using the 8 bit number, so down to 2 bytes per struct, another 9% shaved. It looks like I can spare the cycles. I iterate through the 800 structs every 50 milliseconds while also handling intermittent http requests. No problems. I've been pushing the ATmega limits with this one, but I seem to be coming in well under.

Here's some further reading I happened upon later: http://www.catb.org/esr/structure-packing/

What you are facing is the classic time-memory tradeoff.  The bit fields will be smaller in memory,  but will take more time to operate on.  You can count that no matter what processor, the bit fields will be slower.
You use the word efficient, but that word has no certain meaning without a metric for what is good or bad.  When you only have 8 k of RAM, using memory is bad, time may be cheap.  If you have real time constraints, then using time is bad and memory may be cheap.  In general, you can only buy your way out of this tradeoff.  In other words, when you find both time and memory bad, spend cash and use a bigger chip.  There is no single answer for what is good or bad.  This is part of why there are so many choices for microcontrollers, people fit the chip to the application and application to the chip.
Populating the bits of a bit field will be slower than filling of complete bytes.  Take for example
x = 5;
...
asimplestruct.len = x;
// vs
abitfield.len = x;

The first simple case will just:

load value of x to a register
store it to the byte for len

The second does something like:

loads the current value of abitfield
loads a mask
clears the bits for len
loads current value of x
loads a mask
clears off unused bits of x
shifts the bits of x
or's x with the abitfield
stores the current value back to memory

If all your operations are packing data into the bit field, or unpacking out of the bitfield, you should expect slower execution.  Bit fields are a type of compression - they cost ticks.
But moving around bit fields will be faster because there are less bytes to load and store.  If you where sorting this array, the smaller byte count could be an advantage.  If you where transferring them over a serial port, the compressed size of the bitfield might be a winner.
So with respect to your question:

Is there a good way to test this?

The only good way to test this is to write test cases for both approaches using a pattern that closely matches your application.  It really matters what mix of operations you perform to decide whether the difference is negligible or significant.
When doing this sort of optimization experiment, definitely use source control on your project.  You can create a local GIT or Mercurial repository with just a few clicks.  Keeping a chain of checkpoints allows you to tear up your code exploring the effects of different implementations.  If you take a wrong turn, the repository allows you to simply go back to the last good point and try another path.
(Side note:  This time memory tradeoff exists in the opposite direction also.  If you look through the compiler options for desktop class processors, you will find something called structure packing.  This option allow you to add blank bytes between single byte fields such that they stay aligned at word or double word boundaries.  This may seem crazy to throw away RAM on purpose, but on processors with 16 or 32 bit wide registers and buses, so called word or dword aligned memory operations can be faster than byte wise operations.)

A discussion of bit-fields wouldn't be complete without mentioning that:

Structures with bit-fields may be used as a portable way of attempting to reduce the storage required for a structure (with the probable cost of increasing the instruction space, and time, needed to access the fields), or as a non-portable way to describe a storage layout known at the bit level.

[Kernighan & Ritchie, The C Programming Language, Second Edition, Appendix A-8.3]
Other posters, including yourself, have addressed the space/time tradeoff. But what is sometimes missed (possibly not relevant to your application - ?) is the complete implementation-dependence of the storage layout. This matters when applications share this data with another process: Reading or writing hardware, whose register bit-assignments are necessarily fixed; communicating the data to another system (via network or storage device doesn't matter); or to another application on the same system, that may have been compiled with a different compiler or version of the compiler.

A little tip - I see that the struct is not a 1B aligned for 8bit CPU. At the end of your struct you can add padding 2bit length or rethink increase of the size of state.
struct MyStruct
{
   uint8_t color : 3; // max value 7
   // uint8_t state : 1; *** moved, thanks Ignacio ***
   uint8_t area : 5; // m.v. 31
   uint8_t number;
   uint8_t len : 5; // m.v. 31
   uint8_t state : 1; // m.v. 1
   uint8_t padding : 2;
};

Adding the padding does not change the dynamic memory at compile time. Forgive my ignorance here, but it seems like the compiler takes care of the padding. Or is something happening at runtime to compensate if I don't include the padding?

That's true. In this case is more like a good practice.


text:
Using an Adafruit Trellis to control a set of relays
I've been going through my program again and again, and I can't figure out what is causing it not to work as intended.  First, the story: I'm trying to use an Arduino to control a bunch of relays which are controlling sockets (8 of them). I want to use an Adafruit Trellis LED panel/switches to do this. Basically, when the button is pressed, the LED lights up and the relay gets tripped.  Pressing it again does the reverse.
I will provide my code for inspection.
#include <Wire.h>
#include "Adafruit_Trellis.h"

/***************************************************
This example shows reading buttons and setting/clearing buttons in a loop
"momentary" mode has the LED light up only when a button is pressed
"latching" mode lets you turn the LED on/off when pressed

Up to 8 matrices can be used but this example will show 4 or 1
****************************************************/

#define MOMENTARY 0
#define LATCHING 1
// set the mode here
#define MODE LATCHING

Adafruit_Trellis matrix0 = Adafruit_Trellis();

// uncomment the below to add 3 more matrices
/*
Adafruit_Trellis matrix1 = Adafruit_Trellis();
Adafruit_Trellis matrix2 = Adafruit_Trellis();
Adafruit_Trellis matrix3 = Adafruit_Trellis();
// you can add another 4, up to 8
*/

// Just one
Adafruit_TrellisSet trellis = Adafruit_TrellisSet(&matrix0);
// or use the below to select 4, up to 8 can be passed in
//Adafruit_TrellisSet trellis =  Adafruit_TrellisSet(&matrix0, &matrix1, &matrix2, &matrix3);

// set to however many you're working with here, up to 8
#define NUMTRELLIS 1

#define numKeys (NUMTRELLIS * 16)

// Connect Trellis Vin to 5V and Ground to ground.
// Connect the INT wire to pin #A2 (can change later!)
#define INTPIN A2
// relay pins
#define relay1 2
#define relay2 3
#define relay3 4
#define relay4 5
#define relay5 6
#define relay6 7
#define relay7 8
#define relay8 9
int i = 0;

// Connect I2C SDA pin to your Arduino SDA line
// Connect I2C SCL pin to your Arduino SCL line
// All Trellises share the SDA, SCL and INT pin!
// Even 8 tiles use only 3 wires max

void setup() {
    Serial.begin(115200);
    Serial.println("Trellis on");

    // INT pin requires a pullup
    pinMode(INTPIN, INPUT);
    //relay pins
    pinMode(relay1, OUTPUT);
    pinMode(relay2, OUTPUT);
    pinMode(relay3, OUTPUT);
    pinMode(relay4, OUTPUT);
    pinMode(relay5, OUTPUT);
    pinMode(relay6, OUTPUT);
    pinMode(relay7, OUTPUT);
    pinMode(relay8, OUTPUT);

    digitalWrite(INTPIN, HIGH);

    // begin() with the addresses of each panel in order
    // I find it easiest if the addresses are in order
    trellis.begin(0x70);  // only one
    // trellis.begin(0x70, 0x71, 0x72, 0x73);  // or four!

    // light up all the LEDs in order
    for (uint8_t i = 0; i < numKeys; i++) {
        trellis.setLED(i);
        trellis.writeDisplay();
        delay(50);
    }
    // then turn them off
    for (uint8_t i = 0; i < numKeys; i++) {
        trellis.clrLED(i);
        trellis.writeDisplay();
        delay(50);
    }
}

void toggleLight(int i){
    if (trellis.isLED(i))
        trellis.clrLED(i);
    else
        trellis.setLED(i);

}

void loop() {
    delay(30); // 30ms delay is required, dont remove me!
    //init relay states
    static int relay1state = 0;
    static int relay2state = 0;
    static int relay3state = 0;
    static int relay4state = 0;
    static int relay5state = 0;
    static int relay6state = 0;
    static int relay7state = 0;
    static int relay8state = 0;

    if (MODE == MOMENTARY) {
        // If a button was just pressed or released...
        if (trellis.readSwitches()) {
            // go through every button
            for (uint8_t i = 0; i < numKeys; i++) {
                // if it was pressed, turn it on
                if (trellis.justPressed(i)) {
                    Serial.print("v"); Serial.println(i);
                    trellis.setLED(i);
                }
                // if it was released, turn it off
                if (trellis.justReleased(i)) {
                    Serial.print("^"); Serial.println(i);
                    trellis.clrLED(i);
                }
            }
            // tell the trellis to set the LEDs we requested
            trellis.writeDisplay();
        }
    }

    if (MODE == LATCHING) {
        // If a button was just pressed or released...
        if (trellis.readSwitches()) {
            // go through every button
            for (i; i < numKeys; i++) {
                // if it was pressed...
                if (trellis.justPressed(i)) {

                    switch (i)
                    {
                    case '0':
                        relay1state ^= 1; // xor current value with 1 (causes value to toggle)
                        if (relay1state) {
                            delay(100);
                            digitalWrite(relay1, HIGH);
                            toggleLight(i);
                            Serial.println("Outlet 1 on");
                            break;
                        }
                        else {
                            delay(100);
                            digitalWrite(relay1, LOW);
                            toggleLight(i);
                            Serial.println("Outlet 1 off");
                            break;
                        }

                    case '1':
                        relay2state ^= 1; // xor current value with 1 (causes value to toggle)
                        if (relay2state) {
                            delay(100);
                            digitalWrite(relay2, HIGH);
                            toggleLight(i);
                            Serial.println("Outlet 2 on");
                            break;
                        }
                        else {
                            delay(100);
                            digitalWrite(relay2, LOW);
                            toggleLight(i);
                            Serial.println("Outlet 2 off");

                            break;
                        }
                        //...add case 3-8 & 9-15
                    }
                    trellis.writeDisplay();
                }
            }
        }

    }
}

Relay1 one doesn't work because it's commented out //digitalWrite(relay1, HIGH);. Could you also post the serial output you get?

I commented it out to test.  It should be on. I will correct it in the original post.
Output from serial monitor:
Opening port
Debug on
Port open

Specifically, i'm not seeing the LED's light when I press button 1. Nor am I getting any serial feedback that I included ( when it lights, it prints on the serial).

You should see "trellis on" in the console. Try adjusting the baud rate (bottom right).

Yup, that's showing.

Port open
Debug on
Debug on
Trellis on
0 on
Outlet 1 on

relay1state ^= 1 is just a hack. Just write relay1state = !relay1state. Compilers are smart enough to make these kinds of optimizations. Using XOR might even be slower. Though this will probably not fix your problem.

Stepping back from your code problems, why are you using relays? Do you mean electromechanical relays? Those draw a lot of current and you need to wire them with a protection diode so they don't destroy the control circuit when you disconnect the power and the inductive field on the relay coil collapses.
If you're switching AC power, mechanical relays are a reasonable way to go, but for DC like motors/LEDs, etc, it's usually better to use electronic switches of some kind (e.g. transistors).

I am using the relays to switch on electrical outlets. Mainly for centralized control of the lighting in our office/workspace. It has been done as safe as can be (i.e. fuses in place, proper grounding).I've done this already with a Spark Core controlling 4 relays. I can turn on the relay from the cell network and get my soldering iron preheated, as an example.

Gotcha. Like I said, for switching AC power, relays are a reasonable choice. Remember to put flyback protection diodes in parallel with your relay coils to prevent damage to your switching transistors.

There's an issue with your switch case statement. You switch on int i but your cases use chars like '1'. This is comparing the value of i to the integer value of the character 0 or 1 which are actually 48 and 49 respectively. Check out an ASCII table for more info on this.
Try removing the single quotes and just have something like this:
switch(i) {
    case 0:
        //case 0 stuff
        break;
    case 1:
        //case 1 stuff
        break;
}

This will compare the value of i to the number that you expect.
I suppose another way to fix this would be to add 48 to i every time you check it. I would change the case statements though.
UPDATE
You should be declaring the ready state variables outside of your loop() function and then initializing them in setup().
Something like this:
int ready1state;
void setup() {
    //setup stuff
    ready1state = 0;
}

void loop() {
    //loop stuff
    ready1state ^= 1;
    //use ready1state
}

That was a stupid mistake on my part.  Now I have the relay and the light turning on but doesn't respond when pressed again. (i.e. light stays on, relay stays in position)

No worries, we all make silly mistakes! As for the lastest problem, does the code enter the else block? Does it ever print out "Outlet 1 off" or "Outlet 2 off"?

No, it doesn't print when it is supposed to switch off. I would gather that the else block isn't being entered.

Oh, should have seen this earlier. You declare your ready states equal to 0 at the beginning of the loop() function. So every time the code loops, your ready states get set to 0 and then xor'ed with 1 which equals 1. So it will never enter the else statement. Declare them outside of a function (like where your defines are) and then set them equal to 1 in setup(). I'll post an update in my answer.

Made your suggested change. Still looks like it's not getting to the else part. Lights up and relay trips, but after the one press of the button, no other buttons or relays respond (nor does that same one turn off).

Hmm... Maybe add a serial print out of the value of relay state to see if it actually toggles. If that isn't the issue, you have to verify that the trellis functions that you are using are working as expected. The fact that no other buttons respond after the first one makes me wonder about the readSwicthes() function.

@Doowybbob relay1state is declared static, so that wasn't a problem.

It's actually a good point. This library has nil for documentation, just examples, and so I'm working with it by looking at the Python version of it (which does have some documentation in comments of the library). I'll look around and see if I'm misusing this function.  You guys have been a fantastic help!


text:
Unable to terminate "void loop"
I have loaded an example sketch that came with the installation of the Arduino software onto my Uno.
void setup() {
   Serial.begin(9600);
}

void loop() {

  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
}

From this time TX light is continuously on. It's remaining on even after resetting it. How do I end void loop so that TX light goes off.

Stop outputting via the serial connection.

I need to setup multitask in a loop, so I can take a snap shoot of data from the SD reader.

HIGHLY recommend you begin by loading the Blink example program and start there.  Then modify it to suit.  As for your little program, your delay is only 1 millisecond.  You might as well not even have it there because the Serial.println takes longer than that.  Change it to 5000 for 5 seconds, maybe.  Also, you never set the A0 pin to be of type INPUT.  But first go back to Blink and try to walk (digital) before you try to run (analog).

I'm voting to close this question as off-topic because of the age of this one and the lack of useful description in the title.

The implied question is how to turn off the Tx LED, which has already been answered and is probably the answer you're looking for. But the question you asked is how to end the loop() function. Not to be pedantic but to clarify the use of loop, the simple answer is, "you can't". loop() is called from a forever loop in the C/C++ main program, function main(), so returning from it, either with a return statement or by reaching the final close } causes loop() to be called again. This is intentional as the main() function in an embedded system is never supposed to return, thus it must keep re-running the application program.
Update (since this question just reappeared on the front page, I'll add the following to my answer):
loop() reads and prints continuously. If you had wanted that code to be executed only once, you could put in setup() and leave loop() empty. Then the sketch would initialize the serial output, read an analog value, print it - once - followed by entering the empty loop() and remaining there until power-down.
A way to execute the loop function once is to write an infinite loop at the end of it, so loop() would never return and thus never be re-executed:
void loop() {

  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);

  while(1)
     ;
}

The TX LED is on, because this sketch is periodically printing the value of the analog pin 0 onto the serial port. The LED seems to be constantly on, because the delay between two Serial.println() calls is only approx. 1 ms.
If you replace the 1 with 1000 for example, the TX LED should flash once per second. Start the serial monitor in your Arduino IDE too see the transmitted analog values. Delete the Serial. calls to remove the serial port functionality altogether.
You might want to read the documentation of the loop() and the delay() functions.

Seeing as questions about turning off the LED, and the nature of exiting loop have been answered, I'll also answer the question they both seem to lead to:
If the overall intention is to "turn off" the MCU, outside of turning off the power supply, it can be put into sleep mode.
Depending on how you configure the MCU before entering sleep mode, it can even be allowed to wake up on further USART communication.

Don't write code in the loop() that should be executed only a few times. Or use a counter. Or an external button. For the permanent light, increase the delay between calls.

Could you elaborate on how to do the stuff you say to do in this answer?

If your question is how to terminate the execution of your void loop code at some interval, I can mention 4 solutions:
1.If you want the Void loop() to execute only once (or a set number of times using for loop), you can use "exit(O);" at the end of the Void loop.
i.e.
Void loop(){
         //code
         exit(0);
         }

Disclaimer: This one might not work for all Arduino boards, but it works fine with my Arduino UNO.
2.Another way would be to keep the "Void loop()" empty and put all of your code in the Void setup function.

use a void loop at the end of the Void loop.
E.g.
void loop(){
//code
while(1){  //infinite loop }
}

The arduino will remain in the infinite loop and won't be able to rerun the Void loop.

Create your own function and call it from the "Void Setup()"
E.g.
 Void setup(){
  myfunc();   //calling your function
 }
  Void myfunc(){
//The code for the function you want to repeat only a set number of times
 }
 Void loop(){
 }

Hope someone finds it helpful.

Is there a good reason to warm up this old question? BTW: There's a difference between void and Void

@DataFiddler - Yup, answer is NFG. The entire Q+A should be deleted, or at least closed as it's obvious the OP will never mark it as answered after 8 years.


text:
LM386 module not working
I have arduino UNO hooked up with wtv020-sd-16p and it works fine, playing audio files - speaker is connected right to the WTV020's pin #4 and #5. However, volume is rather low. So I have ordered LM386 amplifier module. I have wired it's IN pin with WTV020's pin #2 AUDIO-L. But no sound comes out of speaker. I can hear only some scratches from the speaker while arduino is running.
LM386 is pretty easy, only VCC, IN and GND pins, so there is nothing much to screw up. I am wondering, what could be the problem ?
Thanks for any help or hints in advance.
EDIT: Only to note, when WTV020 is playing sound, speaker goes completely mute. When it doesn't play sound, little scratchy sounds can be heard from speaker. Maybe it could help with analysis ?

Where does the Vcc plugged into the lm386 come from? This one should be at least 1A I think.

Oh, I am powering LM386 from Arduino 5V. So it might be the problem ?

@jfpoilpret But here is shown LM386 taking power directly from Arduino's VCC as I am using, so it should be fine then ? http://arduino.cc/en/Tutorial/SimpleAudioPlayer

Try feeding your input to the module via a series capacitor to remove any DC offset.

@ChrisStratton You've nailed it. Please add your comment as answer, I will accept it. Thank you.

when WTV020 is playing sound, speaker goes completely mute. When it doesn't play sound, little scratchy sounds can be heard from speaker. Maybe it could help with analysis

Indeed - what you are describing sounds like the DC component of the Arduino's output is outside the workable range of the amplifier, effectively cutting it off.  When there is no output, the voltage is within range and little bits of noise are able to be amplified.
You should be able to fix the cutoff problem with a series capacitor to block the DC component of the input, allowing only the AC signal through - a common technique for coupling between stages in Audio and RF systems.
The value of the capacitor will depend on the impedance of the circuit it is driving.  A bare input to many chips could use a quite small value, while a circuit with feedback or a voltage-divider volume control might require a larger or carefully chosen one.


text:
How do i wire a switch to control Leds on a arduino nano
I am wiring some LED's with buttons to trigger them but i don't know if i have the wiring right?

Code
    /* switch
 *
 * Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
 * press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
 * a minimum delay between toggles to debounce the circuit (i.e. to ignore
 * noise).
 *
 * David A. Mellis
 * 21 November 2006
 */

int inPin = 2;         // the number of the input pin
int outPin = 13;       // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

void setup()
{
  pinMode(inPin, INPUT);
  pinMode(outPin, OUTPUT);
}

void loop()
{
  reading = digitalRead(inPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    if (state == HIGH)
      state = LOW;
    else
      state = HIGH;

    time = millis();
  }

  digitalWrite(outPin, state);

  previous = reading;
}

note
  The code is not set to the pins yet.

Its not working or what? The schematic looks right. Only you have 2 inputs and 2 outputs. And in code you define wrong pins

@Martynas So i have the wiring right?

Yes. Only thing. Don't use voltage from batteries 4x1.5=6 for input. Feed arduino from batteries, and use 5V output to feed buttons

@So you mean plug the battery to Ground and Vin then run the 5 volt rail to the breadboard?

Correct. Thats in case :) It should work in this way, but there is always but :)

@Martynas Like that

@Martynas Also how do i do it with a 2 pin switch??

sorry, did't understood. What do you mean 2 pin switch? you mean http://cmuems.com/2011/b/wp-content/uploads/2011/10/button_sch.png

Let us continue this discussion in chat.

The wiring is correct, but inPin in your code is set to 2, which is D4 on the Nano, while you have your signal wires going to D7 and D6 in your schematic.
Similarly, outPin is set to 13 in your code, which is D9 on the Nano, but your schematic shows the LEDs connected to D5 and D4.
I would also put the resistor going from the other pin on the switch to 5V, having the digital input connected directly to GND, but I'm not sure if that will affect power consumption, so it's probably more just a matter of personal preference.