text:
Updating firmware on Adafruit Huzzah ESP8266
tldr: I'm trying to re-flash a previously working Adafruit Huzzah ESP8266 breakout module to use the latest AT firmware. The re-flash doesn't seem to be working and I'm getting rather confused. This is the first time I've re-flashed one of these modules.
What I did:
I installed the latest version of esptool.py using pip, and downloaded the latest Espressif AT firmware from github. With the Huzzah on a breadboard I grounded GPIO0 and connected the serial port header to my PC using a FTDI cable. VC on the cable is 5v. The red power light lit. I then ran the following commands:

esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m
  0x00000 boot_v1.1.bin
esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m
  0x01000 user1.bin
esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m
  0x7C000 esp_init_data_default.bin
esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m
  0x7E000 blank.bin

Each upload seemed to complete ok, but I found that I couldn't upload the next until I pressed the reset button on the module first, otherwise I got the error:

A fatal error occurred: Failed to connect to Espressif device: Timed
  out waiting for packet header

This doesn't seem right to me.
After uploading all 4 components as above I disconnected GPIO0 and cycled the power on the module. I then tried connecting using putty at 115200 baud but I get no echo back from the module, and it doesn't respond to commands.
Observations:

The module previously worked and I could connect to it with putty.
If I reset it while connected to putty at 115200, I get a consistent pattern of garbage characters, so my guess is its alive but confused somehow.
I've tried connecting at various baud rates: 9600, 14400, 19200, 38400, 57600, as well as 115200. Same result.
I've found walkthroughs that show firmware like node.mcu being uploaded as a single binary. Should I be somehow merging the four bin files into one before uploading the the Huzzah?

What am I doing wrong here?

I'm confident that I've resolved this now. I'll leave the question here in case it is useful to anyone in the future.
The problem was they way I was downloading the individual bin files from the github repo, using right click -> Save As in Chrome. This downloads a file with the correct name, but it is actually the content of the file's html page, not the binary itself. Downloading the repo as a zip file, extracting the bin files,  and then uploading them to the Huzzah using a single command gave me a properly flashed device.
What happened was I noticed that esptool can upload multiple files in one go so, with the original bin files, I tried the command:

esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m 0x00000 boot_v1.1.bin 0x01000 user1.bin 0x7C000 esp_init_data_default.bin 0x7E000 blank.bin

and got the following error

esptool write_flash: error: argument  : Detected overlap at address: 0x1000 for file: user1.bin

Thats when I noticed that boot_v1.1.bin was way to big to fit in the space between 0x00000 and 0x01000. Examining it in notepad++ revealed that it was html.
A learning experience...

this just happened to me.. so annoying, never would have thought to open the file contents


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

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

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

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

void loop() {
}

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

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

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

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

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

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

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

Beat by 11 seconds... :P

source: Stack Exchange

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

sort: votes


text:
ESP8266 and Python Communication
I'm new to networking and working with ESP8266. I have successfully setup my ESP8266 and can program it from Arduino IDE (tested a blinky code).
I want to send some data from a Python script running on my PC to ESP8266. Similar to a setup where use PySerial in Python, open a COM port and send my serial data to an Arduino. Arduino will parse my data bytes and will perform some action. Now, I am trying to achieve the same with ESP8266 and UART replaced with wireless communication.
First, I would like to connect my PC to ESP which will have its own SSID and password. Once connected, I would like to send my data bytes from Python script to ESP8266 wirelessly. Now, similarly, ESP will parse this received data and perform some function (like control its GPIOs).
How can I achieve this? It seems like a pretty simple task, but I'm really confused with what mode I've to use (AP? Client? Server?). What protocol for communication is the best (TCP? MQTT?). What do functions like Handle client/root do? I understand I've to use socket programming on Python, how to do that specifically in my case? How do I buffer my incoming data on ESP, so that I don't miss the bytes?
Could anyone please explain using an analogy with wireless communication and UART? Any links to tutorials will be helpful too. There are some tutorials online where they do this using a HTTP server and control the GPIOs from the browser, but no, I don't want this. I just simply want to send my data as I would with COM Port/UART/Arduino!

as a web dev, i find http to be the simplest interaction method: a clear req/res cycle, built-in parsers for GET params, status codes, easy debugging from other devices, etc. with streams, you have to sniff a lot out.

Check my project: "Esp 2 Python"
https://github.com/KebabLord/esp_to_python
The theori is you can create a localhost and get the sensor data or manage the module through arduino requests or urllib modules with a simple local mDNS server. This project allows you to control and read ESP.

I couldn't get your code to work

it was a literal soup, I radically simplified it, it's too easy to use now, try it again :3

The simplest IP equivalent to UART is TCP/IP sockets.  Create a listening socket on the ESP8266 and connect to it from the PC (or do it the other way around if you like). Data fed in one end comes out the other - just like a serial port.
There's examples with the ESP8266 core that do just that.

You must configure the ESP as an AP, if you want it to have its own IP.
You then set up a tcp-server on the ESP (i think there are example functions in the IDE).
Keep in mind, that the communication (server/client you mentioned) has nothing to do with the way PC and ESP are connected with (whether the ESP is providing an Access Point or logged into your WiFi). Those are different protocol layers, which means you will not need to make any changes if you want PC and ESP communicate over your router at all.
Actually the ESP (or at least for the ESP8266-12F I know for sure) is capable of running both ap and wificlient at the same time.
It's not a big difference to serial communication, you will need to poll for incomming messages in your loop if you want to run a server. Sending messages to your PC is like printing to the serial interface.

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

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


text:
Why can I measure two pins simultaneously?
I would like to do an action if both buttons on my arduino pro micro are depressed simultaneously. I'm getting some strange results:
// Buttons
Bounce button0 = Bounce();
Bounce button1 = Bounce();

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

  pinMode(2, INPUT_PULLUP);
  button0.attach(2);
  button1.interval(1);

  pinMode(3, INPUT_PULLUP);
  button1.attach(3);
  button1.interval(1);

  Serial.println("Setup Complete");
}

void loop() {
  button0.update();
  button1.update();

  if (button0.fell()){
     Serial.println("button0 fell");
  } else if (button0.rose()) {
    Serial.println("button0 rose");
  }

  if (button1.fell()){
     Serial.println("button1 fell");
  } else if (button1.rose()) {
    Serial.println("button1 rose");
  }

  if (button0.fell() & button1.fell()){
    Serial.println("buttons fell");
  } else if (button0.rose() && button1.rose()) {
    Serial.println("buttons rose");
  }
}

Here is the output to the Serial console:
Setup Complete
button0 fell
button1 fell
button0 rose
button1 rose

Why isn't this branch being executed? button0.fell() & button1.fell() For the life of me I cannot figure this out. Thank you!
EDIT
This doesn't work either, which is crazy:
void loop() {
  button0.update();
  button1.update();

  if (button0.fell()) {
    if (button1.fell()) {
      Serial.println("buttons fell");
    }
  }

  if (button0.rose()) {
    if (button1.rose()) {
      Serial.println("buttons rose");
    }
  }
}

EDIT
Thank you for the answers! Unless the person was to push both buttons in the exact same iteration of the loop, my code would never work. Here is what I ended up using:
if ((button0.fell() && !button1.read()) || (button1.fell() && !button0.read())) {

You can test it easily by calling the function twice directly after each other. If the first time a true is returned and the second time a false, the state is internally reset.
But probably because after you call the fell function, the internal state is reset, so after the call not a new fell has been happened.
So store the return value of the fell and rose functions and use those instead.
Update:
I'm not sure if this is the actual implementation but I found for fell/rose and see this:
bool Bounce::rose()
{
    return ( state & _BV(DEBOUNCED_STATE) ) && ( state & _BV(STATE_CHANGED));
}

bool Bounce::fell()
{
    return !( state & _BV(DEBOUNCED_STATE) ) && ( state & _BV(STATE_CHANGED));
}

So as long as the state has not changed it returns false (which is similar/equal as 'resetting the internal state'. Except this reset is done at a different location (but checked in the fell and rose function).
Update:
See remarks from gre_gor below

The fell function doesn't reset the state.

@gre_gor ... it checks if the state has changed, which is functionaly similar.

@MichelKeijzers The state is changed in update. Multiple calls to fell don't affect it.

@gre_gor than it's strange that storing the boolean would work.

https://github.com/thomasfredericks/Bounce2/wiki
I'm not familiar with the Bounce(2) library, but looking at the above site, it looks like "fell" is more of an "instant" thing, where it isn't something that maintains state over the Arduino loop.
Seeing as we are human, we can't (normally) push buttons at the same exact time.  This means that we would usually end up pushing the buttons within milliseconds, plural, of each other, but your simple example could loop multiple times between the first button and the 2nd button being triggered.
Don't forget that the Arduino Uno runs at 16mHz.  This is extremely slow compared to today's computers, but it's still running millions of operations a second.  My first computer, the IBM XT, ran at 4.77 mHz and that was the standard computer for years.
https://en.wikipedia.org/wiki/IBM_Personal_Computer_XT
I suggest putting in a loop counter to help you discover if this is the case.  Trying to display it every loop may slow the loop down, so only display the counter on your current displays.  If your "button0 fell {#}" display shows a different number than your "button1 fell {#}", then you know what's going on.  You may also want to display the actual contents of "button{01}.fell()".
IDK if this library does it, but in app programming, sometimes getting the value of an event like this will cause the event to be flushed and reset the value.  This would mean that calling a method the first time would render a different value than calling it a second time, even if the second time was immediately following the first call.  Setting "button{01}.fell()" to a variable might be a better option than trying to call it twice.

I'm getting some strange results:

your code doesn't really measure the two pins "simultaneously". instead, it measure the two pins sufficiently fast and it appears to be simultaneously.
use input capture for that.

Maybe I missed something but the branch doesn't execute because
button0.fell() & button1.fell()

should be
button0.fell() && button1.fell()

the else if clause also never executes.


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

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

  attachInterrupt(0, zero_crosss_int, RISING);
}

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

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

    switch (ser)
{

  /* Lamp Control  */

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

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

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

  /* Fan Control  */

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

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

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

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

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

    }
  }
}

The circuits it controls is based on these :
Lamp

Fan

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

dimming should be volatile.

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

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

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

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

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

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

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

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

Well, what wattage is on the lamp?

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

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

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

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

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


text:
How to pass 'Serial' as an input argument in Arduino function?
I have one integer value which I should pass through Serial1, Serial2, Serial3, and Serial4 after performing some algebraic operation on this integer. For this algebraic operation, I made a function and input arguments is an integer and Serial number.
Simple code is given below: (I deleted every extra part of my code to make easy to understand)
String stringG; int d1; int d;

#include<SoftwareSerial.h>
//Software Serial #1: Rx = digital pin 10, Tx = digital pin 11
SoftwareSerial Serial4(10, 11);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  Serial4.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available() > 0)
  {
     String  XX = Serial.readString();
    int d1 = XX.toInt();
    Serial.println(d1);
    int yy;
    yy = compareFunction (d1, Serial4);
    Serial.println("Now the final values are:");
    Serial.println(d1);
    Serial.println(yy);
  }

}
int compareFunction (int d, String Serialx)
{

  int ZZ = Serialx.readString(); // I will receive some values from motor using serial4
  //to avoid long code I deleted unnecessary parts
  // I will use ZZ and d values and output will be yy
  return yy;
}

As you see in  compareFunction I receive value using Serial (it may be 1,2,3 or 4) So I have to pass Serial as an input argument in this function. If I can't pass Serial then I have to write 4 functions each for Serial1, 2, 3 and 4 which I want to avoid. Is it possible? How can I do it? when I tried with above code it shows error

exit status 1 could not convert 'Serial4' from 'SoftwareSerial' to
  'String'

It's obviously not a String. Did you try to find out what type it actually is?

The Serial object is the end of a chain of classes, each with a different set of functionality.
Print -> Stream -> HardwareSerial => [Serial]

Since you are reading from it the best class to use is Stream since that is the one that is the one that contains the reading functionality.
You should pass it by reference or as a pointer since you don't want to copy the object.
int compareFunction (int d, Stream &Serialx)
{

  int ZZ = Serialx.readString(); // I will receive some values from motor using serial4
  //to avoid long code I deleted unnecessary parts
  // I will use ZZ and d values and output will be yy
  return yy;
}

By using Stream you can use any object type that also uses Stream in its class inheritance chain - even things like a WiFi socket connection.
This behaviour is called polymorphism and is one of the more powerful features of classes in C++ (and other OO languages).

Thanks @Majenko. It works i.e. now I am able to use Serial as input argument in function. But there is one little problem. When, I used Serial1 or  2 or 3, in comapreFunction, in codeString ZZ = Serialx.readString();   Serial.println(ZZ); it gives accurate value like P214 or P417 etc. But when I used Serial4, it gives values like P‚’j or “‚j. What is wrong with Serial4. I used Serialx.println("P"); to get current position of motor.

Well, Serial4 seems to be SoftwareSerial - and it's any one's guess what would happen with that. I never used it. Ever. It's crap. Try one of the replacements, like AltSoftSerial.


text:
Arduino force feedback vibration gamepad
I'm projecting a gamepad with Arduino Micro. I'm using the Arduino Joystick Library.
I'm building this gamepad for racing games so I need to catch signal like hit_the_wall, hit_another_car.
I wonder how the PC game output the signal of the vibration/force feedback and send throw USB to the gamepad.
I already know that the gamepad drivers and the game have to support this function, but I'm completely lost about how I can catch the input to trigger the vibration engine with Arduino.
I was thinking something about (pseudocode):
input = Serial.read();

if(input == hit_something_signal){

   digitalWrite(engine, HIGH);

}

Now my question is which is this magic hit_something_signal?
UPDATE
I'm reading the PID document and I notice on page number 24 the register addresses to implement the force feedback.
;Start Force Feedback command definitions
USAGE_PAGE (Physical Interface) 05 0F
;Effect Report Definition
 USAGE (Set Effect Report) 09 21
 COLLECTION (Logical) A1 02
 USAGE (Effect Block Index) 09 22
 LOGICAL_MAXIMUM (127) 25 7F
 REPORT_SIZE (7) 75 07
 REPORT_COUNT (1) 95 01
 OUTPUT (Data,Var,Abs)
 .......

In the Joystick.cpp file I notice the HID implementation:
// USAGE_PAGE (Generic Desktop)
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x05;
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;

// USAGE (Joystick - 0x04; Gamepad - 0x05; Multi-axis Controller - 0x08)
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;
tempHidReportDescriptor[hidReportDescriptorSize++] = joystickType;

// COLLECTION (Application)
tempHidReportDescriptor[hidReportDescriptorSize++] = 0xa1;
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;

// REPORT_ID (Default: 3)
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x85;
tempHidReportDescriptor[hidReportDescriptorSize++] = _hidReportId;
.......
......

Do you think should be possible to implement the force feedback part? I do not need to catch all the forces, but run the vibrator engine every time the game sends and input of every kind of force.
The problem is that I'm not an expert about low-level programming and drivers. Do you have any idea?

Do you plan on creating your own game or do you want your joystick to work with existing games?

existing games, like dirt 4 or F1 2017

That library has no support for vibration.
The HID report descriptor has to include the correct OUTPUT items for the PC to send the vibration instructions to the Arduino - and of course the library has to be able to handle that incoming data - none of which is implemented.
So you can't unless you massively expand that library. And that takes intimate knowledge of USB and HID protocols.


text:
Reconnect to I2C with a different address (ATTiny85)
My project requires to reconnect to an I2C bus as a slave. I can't reset my ATTiny physically because I2C + my project + a pin to trigger the reset isn't possible due to the limited amount of pins available on the ATTiny85. I searched the reference and different forums. If there was an answer to my question, I couldn't find one.
Thanks in advance.
(I want to try to make a plug-and-play kind of experience with a product. I want the chip to join with a defined address (100 or so), get a new address from the master and then reconnect to the I2C bus).

A jump to 0 can "fake" a reset, but no guarantees that it does what you want.

I considered that before but i'm not sure if it stops the i2c connection aswell

Or you could use the watchdog.

The Watchdog works perfectly. I had to use modified code that works with the ATTINY that I found on a Blog. https://bigdanzblog.wordpress.com/2015/07/20/resetting-rebooting-attiny85-with-watchdog-timer-wdt/

USI is used to implement I2C on an ATtinyX5. The I2C address is not a hardware register instead this is done in software. It easy both to change address but also listen for several address. Please read the library source code and USI hardware manual for further details.

You only need to reinit the I2C slave.
The TinyWireS lib I found lets you just call TinyWireS.begin() with the new slave address. Though it doesn't have a way to stop the I2C connection. But the lib is hackable enough that with the ATTiny's specsheet you can add an end() to it.
However I believe that it may be better if the newly connected ATTiny acts as a master first and requests a free address from a known fixed slave acting as a dhcp server.


text:
Arduino Uno to Arduino Uno Word.doc file transfer
I have written a 2 sets of code for the transmitter and receiver section. I am trying to send a word document file from 1 arduino uno to the next arduino uno through serial TX and RX. The file is initially loaded into a micro sd card module at the transmitter section. I would like to transfer that file to the receiver section's sd card module. I am able to receive an empty word document at the receiver section. There is no information in the document. I would like some help with this. I will attach the transmitter and receiver code below.
Transmitter code:
#include <SD.h>
#include <SPI.h>

File fileIn;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
   while (!Serial){
    ; //  wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");
  if(!SD.begin(4)){
    Serial.println(F("Initialization failed!"));
    return;
  }
  Serial.println("Initialization done.");
  if(!SD.exists("student.txt")){
    fileIn = SD.open("student.txt", FILE_WRITE);
    fileIn.println(F("abc.txt"));
  }
  fileIn = SD.open("student.txt", FILE_READ);

  while(fileIn.available()){
    Serial.write(fileIn);
  }
  delay(1000);
  fileIn.close();
}

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

}

Receiver code:
#include <SD.h>
#include <SPI.h>

File fileOut;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial){
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");
  if(!SD.begin(4)){
    Serial.println(F("Initialization failed!"));
    return;
  }
  Serial.println("Initialization done.");
  if(SD.exists("student2.txt")){
    SD.remove("student2.txt");
  }
  fileOut = SD.open("student2.txt", FILE_WRITE);

  while(fileOut.available()){
    Serial.write(fileOut);
  }
  delay(1000);
  fileOut.close();
  Serial.println("It worked!");
}

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

}

  while(fileOut.available()){
    Serial.write(fileOut);
  }

This doesn't quite do what you think it does.
Instead you should send the file length first and then do:
for(unsigned long size = 0; i< fileLength; i++){
    Serial.write(fileOut.read());
}

You should also investigate some kind of rate limiting to avoid overwhelming the reciever and having to drop some bytes.

Is it possible to read the line and take that as a file length in the 1st arduino and how would I implement this with the receiver arduino?

File has a size() member function. And just send 4 bytes with the length before you send the rest of the file. on the recieve side the first 4 bytes read will be the size of the file you will be recieving.


text:
Rfid is not working
I am making a rfid card cognition code to find out what id does my card have.
I used rfid-rc522 module. And I set the pins like this picture.

I'm using a genuine Arduino uno. and my code is this:
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN   9                            // reset핀은 9번으로 설정
#define SS_PIN    10                           // SS핀은 10번으로 설정
                                               // SS핀은 데이터를 주고받는 역할의 핀( SS = Slave Selector )

MFRC522 mfrc(SS_PIN, RST_PIN);                 // MFR522를 이용하기 위해 mfrc객체를 생성해 줍니다.

void setup(){
  Serial.begin(9600);                         // 시리얼 통신, 속도는 9600
  SPI.begin();                                // SPI 초기화
                                              // (SPI : 하나의 마스터와 다수의 SLAVE(종속적인 역활)간의 통신 방식)
  mfrc.PCD_Init();
}

void loop(){
  if ( !mfrc.PICC_IsNewCardPresent() || !mfrc.PICC_ReadCardSerial() ) {
                                               // 태그 접촉이 되지 않았을때 또는 ID가 읽혀지지 않았을때
    delay(500);                                // 0.5초 딜레이
    return;                                    // return
  }

  Serial.print("Card UID:");                  // 태그의 ID출력

  for (byte i = 0; i < 4; i++) {               // 태그의 ID출력하는 반복문.태그의 ID사이즈(4)까지
    Serial.print(mfrc.uid.uidByte[i]);        // mfrc.uid.uidByte[0] ~ mfrc.uid.uidByte[3]까지 출력
    Serial.print(" ");                        // id 사이의 간격 출력
  }
  Serial.println();
}

And I used library rfid-master which is in the github
So, when I try to get the card to the reader see video, it doesn't work like the video. What is the problem?

You have to explain in what way it doesn't work like the video.

Can you read the key fob using the DumpInfo.ino sketch that came with the library?

This would be a good question if you explained a little more on what you expect to happen and what exactly isn't working.


text:
Can an accelerometer be used to detect heart sound?
I've recently come across accelerometer and how it can detect electrical mechanical response. I was wondering can it be used to detect heart sound? Lets say you attach the device close to your chest (where heat lies) and detect sounds and send it over bluetooth? LPMS-B2 OEM

An accelerometer detects motion (acceleration) of the physical device.
If you can convert the sound of the heart into physical vibration then the accelerometer can detect that vibration.
Converting the tiny amount of sound the heart produces into a large enough vibration for the accelerometer to detect would entail (realistically) using a microhone, amplifier, and speaker, with the accelerometer attached to the speaker cone.
So while theoretically yes, you can do it, practically why would you when you can just use the microphone and amplifier that you'd be using anyway. It's pointless.
So in reality: no, you can't.

Well said Majenko, I was thinking the same, and quite frankly, most people agree with your reasoning! Cheers!


text:
Auto Fish Feeder
Good day, I am new to Arduino, but have made some nice projects work.
I have a n issue with a Auto fish feeder. I have used a servo that I modified to run 360. I am having a issue when the Nano board starts. It runs the time I have set between feeds, and then it stops. If I set it to feed every 10 sec, it starts up and run for 10sec and then the LED flashes and it stops. From there it works perfect. But if I lose power and it comes back, its going to feed for 10sec and that will kill the fish.
Here is my sketch I am using now, please can someone look at it and tell me where I am going wrong. I just want it not to run when it starts up, or just for the to that it feeds, not continues like now for 10sec, or 12 hours !!!
//--Setting Vars

   //Fish Feeder Vars.
int pinOutMotor = 3;
int pinOutLed = 5;
int pinInButton = 2;
int MotorRunDuration = 1000;
float AutoWaitDurationHours = 0.;
//--Program Vars
unsigned long currentMsSinceStart = 0;
unsigned long msValueAtLastRun = 0;
float HoursSinceLastRun = 0;
int buttonValue = 0;

void setup() {
  Serial.begin(9600);             //Turns on serial monitor.
  pinMode(pinOutMotor, OUTPUT);   //Is controlled by a 3906 npn transistor to switch the motor off and on.  When program started I need to add a line to turn off motor when program was started.
  pinMode(pinInButton, INPUT);    //Manual feed.
  pinMode(pinOutLed, OUTPUT);     //Shows motor is on when lite.
}

void loop() {
  //HoursSinceLastRun = AutoWaitDurationHours - 0.05; //this will make it run 3 minutes after turned on.

//Fish Feeder
  //get miliseconds since program start and calc.
  currentMsSinceStart = millis();
  HoursSinceLastRun = (currentMsSinceStart - msValueAtLastRun) / 10000; //10000 millis= 10 seconds.  To change the time to vary feeding times set for 12hrs type in 43200000 or 6hrs tyoe in 21600000.
  //check for button press
  buttonValue = digitalRead(pinInButton);
  if(buttonValue == HIGH){  //had to change state because of button from LOW to HIGH.
    //run motor for button press.
    RunMotor();
    Serial.println("Feed Fish Manually");  //serial print funtion completed by button

  } else if(HoursSinceLastRun > AutoWaitDurationHours){
    RunMotor();
    msValueAtLastRun = currentMsSinceStart;
    Serial.println("Feed Fish Auto");      //serial print funtion completed by auto wait duration hours
  }
  //slow the loop down so it isn't running at full CPU Utilization for nothing.
  delay(50); //delay 1/20th of a second.
}

void RunMotor(){
    analogWrite(pinOutMotor, 0);   // turn on motor
    analogWrite(pinOutLed, 80);        // turn on green led to show motor is on.
    delay(MotorRunDuration);   // wait for motor run duration to expire
    analogWrite(pinOutMotor, 255);    // turn off motor
    analogWrite(pinOutLed, 0);        // turn off green led to show motor is off.
}

I do not know what's wrong, as I copy and past from my sketch and mine is compiling 100%

I am using Arduino 1.8.5, if that helps

If I correctly understand, your problem is really with the restart, that will always feed the fish.
You can use the EEPROM to save the last time you feed the fish. You also need a RTC to get the real time.
Every time you feed the fish, you also write in the EEPROM the current hour:minutes (from the RTC). When you restart, you read your last feed from the EEPROM and uses it to initialize msValueAtLastRun. You have to change your time recording to hh:mm instead of millis from start.
You code looks OK, only missing debouncing the button.
You can also use a NodeMCU, and get your time via NTP.

Thanks for the answer, I will have a look to get a RTC. I will also have to investigate how to get it working and how to right to the EEPROM.I have never done this. But it sounds like a great project.
Is there no other way to let it just do a "run" at start up and then have the delay between feeds. So it do not run 10 sec before it goes to the first feed. So feed immediately and then delay

Is there no other way to let it just do a "run" at start up and then have the delay between feeds. So it do not run 10 sec before it goes to the first feed. So feed immediately and then delay

@Loeikie Every time Arduino reset, it start from zero. No memory of what it was doing before. No way to know how long has been down.


text:
Boil water inside a small container with an arduino
I am currently working with a sciene/electronic project where i need "steam". In order to create steam i need to boil water and i plan to boil it inside a very small container [around 5cmx5cmx5cm]. What i want to do is to control this with an arduino but I am very unsure on what step i currently need to make. Are there any "heating-up" modules out there? Or would I need to order a mini-mini kettle and connect that to my arduino?
I am very grateful for every advice i can get because as u can tell i am a bit confused as of right now!

You need a little pot and a flame.  Or some small electric heater.  What role will the Arduino play in all of this?

@Delta_G Ok. It will be the one controlling when the heating should start and also im getting a module that will monitor the temperature

So there is for example not a "heating plate" module that u can connect to an arduino that u know of? @Delta_G

Just use a thermocoupler. No need for an arduino here.

I you only want the steam/smoke effect, I'd suggest using ultrasonic air humidifier (like this one). Example usage

Try to find a boiler pot on electricity (I doubt you can heat water to boiling temperature with like 5V (unless you use many amperes).
Use a relais to switch it on with an Arduino.
Use a temperature sensor (0-150 degrees or so) to decide when to switch it off.
Warning: Get first some electrical knowledge before you start with >200 volts projects since it can be deadly. And boiling water can be devestating for skin and your Arduino.

Okok. I see there are some heating pads out there that u can connect straight to an arduino but they seem to only reach a deegre of 40 degrees. I might put this project to rest since my electrical knowledge aint that high and i dont plan to die anytime soon! Thx a ton for ur answer

Good luck ... Probably 40 degrees is what can be maximaly achieved by regular/normal 5V adapters, especially those from Arduino. It's always best to give such 'high power' devices separate power as from the Arduino.

https://www.banggood.com/Waterproof-Silicone-Flexible-Heating-Pad-6060MM-DC-12V-10W-p-972464.html That product looks pretty interesting

You can try, but even for this you need a relais, so the answer will still be similar (except for the electricy / high power warning).


text:
Switch on/off LED 24V using a MOSFET
I try to switch on/off IKEA Ledberg LEDs which are powered with 24 V using the setup from this tutorial video: https://www.youtube.com/watch?v=sVyi7yWuXxs
I use a IRLB8721PBF MOSFET. When I switch the output from HIGH to LOW the LEDs shine a little less brighter. When the pin is set to HIGH I can measure 23,4 V at the LEDs and when it's set to LOW I measure 22,9 V.
So the MOSFET is not really switching off but why? I also tried to put a 100 kOhm resistor between Gate and Source which also did not help.
Do you have any hints for me?
Cheers,
Oliver

Maybe you wired the MOSFET wrong. Please show your wiring and schematic (a video that you "followed" is not good enough).

You should not treat a MOSFET like a relay.  That is, the video shows a working 12 volt circuit but you are going for 24 volts.  The amount of possible current from drain to source is dependent on the voltage of the gate with respect to the drain.  You simply doubled the drain voltage but are still using the same 5 volt swing on the gate.  If you do not want to study the MOSFET Characteristics Curves, that's fine.  But then you should consider using a solid state relay instead.  (Essentially, you are asking how to build a solid state relay.)

Heya, first of all, let me thank you for your answers. As you can see my knowledge is quite basic. The question is not whether I want or do not want to study MOSFET characteristics curves. I simply wouldn't know how to interpret them at the moment. It's like: googling is easy when you know what you are looking for...
Anyway, I think using a relay would be more suitable in this case. I'll give it a try.
Thanks again! :-)


text:
Getting wrong value from Serial.read()
I have an RGB LED, connected to my UNO R3 and would like to turn on the written color in the serial by following a table (1 for red, 2 for blue, 3 for green...) and I also want to make that if this LED is already turnt ON, I want it to turn OFF. The problem I have is that when I use Serial.read() it always returns a -1 value. Why is that?
I leave you the code here and in case you see something wrong please tell me. Thank you very much.
#define RED 7
#define GREEN 4
#define BLUE 2
  String ledcolour[] = {"RED", "BLUE", "GREEN", "YELLOW", "PURPLE", "WHITE"}; //array to match the number typed to the LED colour
  char ledstatus[] = {0, 0, 0, 0, 0, 0}; //0 if the LED is OFF and 1 if it's ON
  String ledvaluefix[] = {"HIGH", "LOW"}; //if the ledstatus[] value is 0 it will write HIGH and if it's already ON it will write LOW
  char ledstatusfix[] = {1,0}; //to update in ledstatus[] if the LED is ON or OFF
  int led = Serial.read();
void setup() {
  pinMode(RED,OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE,OUTPUT);
  Serial.begin(9600);
  Serial.println("Type the LED's colour you want to turn on following this table:");
  Serial.println("RED=1");
  Serial.println("BLUE=2");
  Serial.println("GREEN=3");
  Serial.println("YELLOW=4");
  Serial.println("PURPLE=5");
  Serial.println("WHITE=6");
}

void loop() {
  if (Serial.available()){
    Serial.println(led);
    loop();
   if (led <= 6 && led >=1){ //Checks if value is within 0-6
    if (led <=3){ //Classifies in primary or mixed colours (understand primary as just having to turn ON one single LED)
      if (ledstatus[led-1] == 0){//checks if the LED was OFF
        digitalWrite(led-1,HIGH);//turns the typed LED to HIGH
        char ledstatus[led-1] = {1};//updates the array to set the LED is now ON
        confirmer();//sends a serial confirmation message
      }else{//if it was already ON
        digitalWrite(led-1,LOW);//turns the typed LED to LOW
        char ledstatus[led-1] = {0};//updates the array to set the LED is now OFF
      }
    }else{//if it's not a primary colour
      Serial.println("YOU CHOSE " + ledcolour[led-1] + ", WHICH IS A MIXED COLOUR");
    }
    }else{//if the value is not valid (not between 0 and 6)
      Serial.println("SORRY, THE INTRODUCED VALUE IS NOT VALID");
      Serial.println("PLEASE, TRY AGAIN");
    }
  }
}
 int confirmer(){
    Serial.println("YOU CHOSE THE " + ledcolour[led-1] + " LED");//sends the serial message confirming it's been turned ON
   }

Why on earth are you calling loop from loop? That's nasty and leads to infinite recursion and crashing.

This
 int led = Serial.read();

is execute before setup() and loop(), just one time. All initializations outside any function are execute before the start of the program. You have not execute Serial.begin yet.
You probably want to read inside the loop ...
Edit:
Second problem: you are calling loop recursively
void loop()
{
    if(Serial.available()) {
        Serial.println(led);
        loop();

When a byte in available in the serial port, you will call loop. As you never read the serial port, Serial.available will still return > 0, and you will enter in a never ending recursion.


text:
Change Arduino Clock Speed
I want to run an arduino board at a slower - but more accurate - clock speed. What (if anything) needs to be changed in the arduino code/libraries in order to achieve this? Normally the boards I use run at 16MHz, but I wish to derive a 10MHz clock from a GPS timing module and run the ATMEL processor off the 10MHz timing clock.

What kind of timing facilities do you need? Would millis() be enough? Would you need micros() or delay() as well? millis() could be easily reimplemented on top of Timer 1, if you can spare it for this use. Depending on your needs, you could also have single-cycle timing resolution by taping directly on the hardware timers.

You have to change F_CPU only - You can add new board into the boards.txt with correct clock speed.
EDIT: Aparently millis counter will be drifting much more then expected due to "rounding" errors.
The bootloader on the other side needs to be recompiled with correct F_CPU and  reflashed, if you want it working at the same baud rate (plus it's possible to change fuses to use external clock source instead of crystal). Otherwise you have to try reduced speed (also configured in board config).
You can use MCUdude/MiniCore as inspiration. It supports many clock speeds (but 10MHz doesn't)

Note that all the timing functions will be off, as the implementation of millis() relies on some arithmetic that does not work well for arbitrary clock speeds. See this comment in the source: “for the clock speeds we care about - 8 and 16 MHz - this doesn't lose precision.” Since the OP seems to care about accuracy, this could be a deal breaker.

Looking at that source code, it turns out that, with F_CPU set at 10 MHz, millis() will assume a frequency of 512/51 ≈ 10.039 MHz. It will then run about 3900 ppm slow, which is a huge error: more than 5 min/day.

@EdgarBonet I'm not sure about this, but ISR handler is adding 1ms and 638us every interrupt instead of 1ms and 638.4us (those values are counted from F_CPU). Somehow it gives me about 21.1s every day:  (1 - (1/0.0016384)*0.001638) * 24* 3600. But maybe I'm calculating this completely wrong.

Okay, I've missed that bitshift... Well, then it will be much worst (337.5s)


text:
Using Li-Poly battery to run UNO + Adafruit data logger
I want to power Arduino UNO+Adafruit data logger (https://www.adafruit.com/product/1141) with a 3.7V 2000mAh Li-Poly battery. I am providing an excitation voltage of 3V, through one of the digital pins and a potential divider arrangement, to a sensor which is providing output signal in analog (voltage) form. I am using ADC to read that voltage. My question is, since the battery voltage is going to drop during its operation, would the voltage output from the digital pin, and thus the potential divider, also drop? Could this voltage drop also affect the reference for the ADC?

The UNO is a 5V board. How do you plan to run it from 3.7V?

I have read on the forums about different methods to power a Arduino from a Li-Poly battery:

Using a boost converter to boost the voltage beyond 5V and then using Vin pin to power the board (not preferable as the boost converter +linear regulator connected to Vin pin will decrease efficiency)

Directly connecting the battery to 3.3V pin on the board (the 3.3V pin is connected to a regulator)

You can't run the Arduino UNO directly from 3.7V.
You can use a boost regulator to step up to 5V and feed that into the 5V pin - in which case your question becomes null and void, since you are running at 5V, not 3.7V.
Or you can perform some hardware and/or fuse modifications and run the board directly from 3.7V into the 5V pin:

You will have to change the surface mount resonator to an 8MHz one instead of the normal 16MHz, or
Switch the clock to use the internal RC oscillator by reprogramming the fuses.

Either way you will then have to also modify the board configuration in the IDE to run at the new clock speed.
So given all that the simplest thing to do is to invest in a 5V boost regulator. Personally I'd suggest the LiPower Shield from Sparkfun. It also has a "fuel gauge" chip to monitor the batter charge.
Either that or scrap the Uno and invest in a development board that is designed to run from a Li-Poly / Li-Ion / LiFePO4 battery.


text:
ESP8266 Websocket issue
I realize it might be dumb question, but I've been at it for a few hours and I'm going nowhere. I am trying to figure out the standard Websocket library, however I have an issue casting the uint8_t to a String, so I can work with it easily, how do I do that and is it even possible? What I want to do is, get the payload from the main function as shown in the standard library and give it as a parameter to a function I have. This is the part I need, this is part of the switch statements in the standard library.
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {

   switch(type) {
     case WStype_DISCONNECTED:
     Serial.printf("[%u] Disconnected!\n", num);
   break;
   case WStype_CONNECTED:
    {
      IPAddress ip = webSocket.remoteIP(num);
      Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);

      // send message to client
      webSocket.sendTXT(num, "Connected");
    }
   break;
   case WStype_TEXT:
      Serial.printf("[%u] get Text: %s\n", num, payload);
      move(payload);

Yes, I have. I have tried with.
String text = String((char *) &payload[0]); and just String text = String(payload);  and other ways of trying, this wasn't the first place I stopped at.

you can't cast it. payload is an array of received bytes and length is the size of received data in that array. if the bytes are characters and you would know that there is one more position allocated in that array, you could put a 0 to payload[length] and by cast to char* it would become a zero terminated string. but you can't know if there is that one byte allocated, so you must copy the payload to your buffer of chars and set a zero at the end.

Thanks, ended up doing this:
char clientCommand[length];             for (uint8_t i = 0; i < length; i++) {                 clientCommand[i] = payload[i];             }             clientCommand[length] = '\0';             Serial.print(clientCommand);


text:
Set clockspeed of Arduino Pro Micro a. k. a. AtMega32u4
Is it possible to change clock speed when running sketch?
Low-power lib drops the current consumption from 20mA to 9.5mA at 8MHz, it is still too much. Is there a way how to set clockspeed (for example) to 1MHz, go to sleep, after interrupt wake up, set clockspeed back to the 8Mhz (for 3v3), do some stuff and then go sleep again?
Thanks

Absolutely. The built-in prescaler can dynamically change the clock speed for most of the systems on the chip (USB still needs to run at full speed in order to operate properly).
#include <avr/power.h>

 ...
clock_prescale_set(clock_div_32);
sleep();
clock_prescale_set(clock_div_1);
 ...

See the datasheet and AVR Libc documentation for more details.

Thanks, I've just tryed this, but it didn't help. The power consumption is the same as before.
clock_prescale_set(clock_div_8);   attachInterrupt(INTERRUPT_PIN, wokenUp, RISING);   LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

Probably because most of the clocks are off in that power mode, so aren't running in the first place.

What should I do then do achieve the lowest power consumption with wake up by interrupt?

Disable unneeded peripherals. Reduce overall clock speed. It's all in the datasheet and application notes.

Also remove the power led from the Arduino board, as that is also using power without doing anything useful.


text:
Arduino Mega 2560 not recognized/overloaded
I pulled my Arduino set out of storage yesterday and was very upset to find that it is not working for some reason.  Before I explain the problem, let me explain the situation.
Hardware (all DFRobot):
Arduino Mega 2560
Arduino Mega 2560 4x-platform breakout board
GPIO Expansion Shield V1.0
I/O Expansion Shield V7.1
8 Channel 5V Relay Board
4 LED/Resistor set up
1 digital speaker
1 digital humidity/temperature tester
7 analog chemical air chemical testers
The whole project:

LED Portion:

Relay Portion:

Sensor Portion:

Pin Connections:

In this 4th photo, the two analog pin sets in use right in front are the ones I remove in order to gain control again.  if those are plugged in then it doesnt work.  It has nothing to do with those pins specifically, If I remove any two it works again, those ones are just easiest to remove to get it to work:

Explanation of project:
This is basically a test station, where I can hook up what ever I want and see how it works and then move onto another peripheral piece of hardware and make them interact.  I went with the 4x-platform breakout board as to maximize I/O space.  Once a project is done, I Velcro band them together as to not get them confused and move on.
Explanation of problem:
When I plugged the Arduino into my PC the first time, the lights came on the Arduino and then after about 15 seconds it powered down and the lights went off.  My PC did recognize it while it was powered up and the port option under tools in the Arduino IDE was available and I could select the port.  After the power down and problems I realized something must be up.
I considered the fact that maybe the Velcro was constricting the wires and causing them to short circuit through the rubber insulation, but couldn't find any info on that online.
After this I decided to cut the PC out of the equation and try just plugging it into the wall, 1st, via USB to 5V1A wall charger, it stayed on for a few seconds and then turned off, 2nd with a 5V2A wall charger, same scenario, 3rd via the barrel jack with the same wall chargers, with no success.
I undid all of the wire bundles to rule out a short circuit, which it did.  I then found out after much trial an error that if I removed any 2 of any analog or digital wires, the lights would stay on and it would work.
Now, with two cables removed so it did not lose power, I plugged it into my PC and am now able to program it again and see it in the port in the IDE, but as soon as I plug in another 2 analog or digital peripheral devices it will lose all power and stop working.
I also tried plugging my DFRobot Beetle micro-controller in with the same USB cable and it worked perfectly.  I also tried resetting the micro-controller, to no avail.
Conclusions so far:
A short between rubber insulation at 5v is extremely unlikely
one would think that if a mega board was designed to have so many I/O pins you could actually connect to all of them with out any problem.
Since this happened on both the PC and wall charger scenarios, and the problem seems to be associated when disconnecting any 2 sensors, the problem is most likely at the micro-controller level.
Questions:
are all the peripheral devices draining the board so much that the USB port on the PC or wall chargers cant handle it?
How do I provide enough power to the board if this is the problem?
Or is this simply faulty board?
If it is a faulty board, what causes this and how do you avoid it?
Just to clarify, looming the wires together into bundles is OK right?
Finally, any help would be really appreciated, this is the first time this has happened and it sucks.

Pics would be nice here.  Try using something like Gimp to resize the images you have so they are smaller.  You can also use a free image storage site and post links to them.

I was able to do it by print screening, hope that helps.

Thank you for the pics.  Thank helps, and yet it doesn't...  Soooo many wires!  :-)

Is that bad practice?  I honestly don't know, the plan was to fill all the pins eventually.

Actually, I was just poking a little fun at you.  Sorry if that didn't come across that way.  AFAIK, it's not bad practice, it just makes it hard to trace things down.  Having a lot of wires can lead to EMF across the wires, but twisting them or otherwise shielding them helps.  I built a CNC machine using an Arduino Mega and I have Waaaaay more wires than you do, so you're not alone.

ah haha ok, well thats good to know.

First off, that is one heck of a rig.  I'm impressed to the point of "I gotta get me one of those."
Bundling your wires shouldn't have the kind of impact you are seeing, unless there are bare wires touching.  You might get induction interference, but not a total shut down.
From what I can see here, it looks like there's so much stuff connected to the Arduino that it's probably starving it for power.  You should look into using power rails for Gnd and +5v.
You will also need to check if you are supplying it with enough amps, too.  Your computer's USB port only supplies 0.5A, unless it happens to be USB3, then it's 0.9A.  Even your 5V1A PSU might not be enough.  Consider finding a 2-5 amp wall wart to do some more testing with.  There are usually spec sheets with components, so you'll need to add all the power draw for all the components, including the Arduino, and make sure you have more than enough to meet that calculated power draw.  Exceeding it by at least 10-20% is usually considered good practice, even for a test rig.
Consider powering your rig's new power rails with the extra PSU even when the Arduino is plugged into your computer.  As long as you make sure you aren't trying to take power from the computer and the PSU at the same time with the same component, you should be fine.  (Don't cross the streams.)
There could be a short or feedback loop somewhere in your sensors that's causing the extra drain.  There are so many wires here that it'd be easy to hook up something backwards.  Along with the number of wires, the bundling doesn't let SE-us help you track that down.
You might want to look at the direction your pins are facing.  It was an odd situation for me, but having two of the metal clips facing each other was enough for a short.  In your "Relay Portion:" pic, they are all facing the same way, which is good.  See if there are places where that's not the case and fix it.  Like I said, it was an odd situation, but it's a phantom problem you can avoid.

Oh ya I love the DFRobot stuff, its really cool, I saw that Multi-platform shield and immediatly went for it.
So when you say use a power rail do you mean buy a separate wall PSU and run the power to a separate breadboard, then run all power from this breadboard.  Or do you mean wire the separate PSU directly into the shields via the screw terminals so that all the 5v/GND pins on the shield themselves are run off the external PSU?

You'll have to forgive me, as I'm a complete novice when it comes to actual power calculations.  So you're saying calculate out how many volts & amps each piece of hardware consumes and then find a power supply which will output what I need.  The volts wouldn't be part of that thought right?  Just for example, 22 devices at 5v each would need a full 110, that cant be right can it?  I just need to make sure that the PSU has enough AMPS to push all the power through, correct?

A power rail is pretty much anything that allows you to have 1 PSU power multiple things at once, without having to go through other components first.   The screw terminals might do the same thing.  https://images-na.ssl-images-amazon.com/images/I/41t0EVwnGoL.SX355.jpg

For power calculations, as long as they are all the same voltages, you can just add the amps together.  So, 5x components that use 5v @ 0.5A, you'll need 5v @ 2.5A to power it.  If you have another 2 components that are 12V @ 1A, then you'll need another PSU to supply 12V @ 2A.

Alright, the local electronics store (the only one) only had a 5V3A power supply.  I will try hooking it up with a multi-meter and see how many amps it draws tonight and try adding them up as well to see if it matches.  I'll try a breadboard first and then try the terminals after some more research.
The PSU he gave me has a barrel jack so just out of curiosity, is there anything explicitly wrong with using the external PSU in the barrel jack while using the USB for programming?  Or is the Micro-controller not smart enough to prioritize the better power source?

I use the barrel jack PSU and USB at the same time all the time.  It's designed to do just that, so you should be good to go there.  However, the Arduino is only capable of putting out 200mA from the power outputs and 40mA from the I/O pins. You'll still need to go to the screw terminals of the breakout board or a power rail to reach the components themselves.
https://electronics.stackexchange.com/questions/67092/how-much-current-can-i-draw-from-the-arduinos-pins

Alright, well I have my homework cut out for me, I'll get back to you on this.  If each pin can only output 40mA it seems odd that any of the devices would be made to pull more and require a power rail.  Lots to consider, thanks!

Let us continue this discussion in chat.


text:
Arrays, and for loops... faster to use together, or not to use?
I'm a 4th year EE undergrad, so I'm more of a hardware guy than software. But concerning best programming techniques, is it "better" (more efficient/and/or equally effective) to use for loops when trying to change several items in an array by the same mathematical operation?
--OR--
Is it best to list each item out and have each operation performed by the rate at which the primary "void loop" cycles?
I'm using a Teensy 3.2 board and trying to get a DSP reverb effect working. I have an array of 8 delay tap lines, each with a different time multiplier. I'm trying to determine if it will take more time to process a for loop for each delay-tap line, versus multiplying each element in my array without the additional loop. I need to minimize processing time at all costs to avoid additional system lag.
Sample code:
  //Set delay times
  for(int i = 0; i < 8; i++)
  {
    delay1.delay(i, pot1*pauses[i]);
  }

versus
  delay1.delay(0, pot1*pauses[0]);
  delay1.delay(1, pot1*pauses[1]);
  delay1.delay(2, pot1*pauses[2]);
  .
  .
  .

EDIT
Added sample code.

can you give some pseudo-code for each method?

Post examples of both alternatives. I'm not sure of what are you asking.

Sure, I updated the original post. It likely seems like a trivial question since any dummy wouldn't want to write out 10 lines of repetitive code--most applications that aren't time-sensitive. But I recall trying to do something similar with my Uno board (8MHz) and drawing lines to an OLED. Using "For" loops significantly increased the drawing time.

Have a look at the compiler output.
The Loop option
The first alternative produce a preface (setting things) and the loop itself.
Preface
40201803:   21c9        s32i.n  a12, a1, 8
40201805:   3109        s32i.n  a0, a1, 12
40201807:   00a0c2          movi    a12, 0

loop
4020180a:   202cc0          or  a2, a12, a12
4020180d:   01ccc2          addi    a12, a12, 1
40201810:   ff8585          call0   4020106c <delay>
40201813:   f38c66          bnei    a12, 8, 4020180a <_Z6XYtestv+0xa>

The unfolded option
While the unfolded version is:
40201823:   020c        movi.n  a2, 0
40201825:   3109        s32i.n  a0, a1, 12
40201827:   ff8445          call0   4020106c <delay>
4020182a:   120c        movi.n  a2, 1
4020182c:   ff83c5          call0   4020106c <delay>
4020182f:   220c        movi.n  a2, 2
40201831:   ff8385          call0   4020106c <delay>
40201834:   320c        movi.n  a2, 3
40201836:   ff8345          call0   4020106c <delay>
40201839:   420c        movi.n  a2, 4
4020183b:   ff8305          call0   4020106c <delay>
4020183e:   520c        movi.n  a2, 5
40201840:   ff8285          call0   4020106c <delay>
40201843:   620c        movi.n  a2, 6
40201845:   ff8245          call0   4020106c <delay>
40201848:   720c        movi.n  a2, 7
4020184a:   ff8205          call0   4020106c <delay>

So, the loop execute 4 instructions per each array element, while the unfolded version had only 2 instructions per array element.
But you are trading speed for space and and risking an error while coding the same repetitive thing.
However, GCC (the 'Arduino' compiler) can unfold the loop by itself, so you still can write a loop but execute a sequence. Look at Tell gcc to specifically unroll a loop
Real numbers
I run a sketch (Arduino UNO) to time loop vs unfolded. The times for 1,000 execution of each method are:
loop:     6524us
unfolded: 3808us

Quit a difference!
Sketch
int pause[8] = {1, 2, 3, 4, 5, 6, 7, 8};
typedef int (*fn)(void);

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

  Serial.print("Timing loop: ");
  Serial.print(time(met1));
  Serial.println(" us");

  Serial.print("Timing unfolded: ");
  Serial.print(time(met2));
  Serial.println(" us");
}

void loop() {

}

int time(fn f) {
  unsigned long start = micros();
  int x = 0;
  for (int i = 0; i < 1000; i++) {
    x = f();
  }
  unsigned long dif = micros() - start;
  return dif;
}

int met1() {
  int sum = 0;
  for (int i=0; i < 8; i++) {
    sum += pause[i];
  }
  return sum;
}

int met2() {
  int sum = 0;
  sum += pause[0];
  sum += pause[1];
  sum += pause[2];
  sum += pause[3];
  sum += pause[4];
  sum += pause[5];
  sum += pause[6];
  sum += pause[7];
  return sum;
}

is it "better" (more efficient/and/or equally effective)

depends on your definition of "better", or "efficient", ...
for example unrolling a loop is typically more efficient speed-wise, but less so space-wise. or vice versa.
on top of that, you have other potential definitions for "efficiency", like readability, etc.


text:
How do I combine a variable and characters into a string with Arduino?
I am building some sensors with Arduinos, which each have a unique integer address from 1-9 (This address is an int variable stored in a struct 'Matrix', the variable name is Matrix.Address). The sensors will all be connected to a PLC via SoftwareSerial (BitBanging) through an RS232 converter. Since all of the Sensors will be connected to the same RX & TX ports on the PLC, I need a way to address each sensor through a unique string.
My plan is the following:
*If the PLC wants a reading from sensor #1, it will send the string: "1,read"
All of the sensors should receive this string, but I only want the sensor with address '1' to respond.
*What I am trying to do is come up with a line of code similar to the following:
    if (plcCommand == (Matrix.Address + ",read<CR>")) {
  mySerial.print(GenerateEquation());

Basically, I need to insert that 'Matrix.Address' variable into a string which will be compared to the incoming string.
It seems like a very simple thing to do, but I am having trouble coming up with a solution.
Any help would be appreciated!

what type are those variables?

You're thinking backwards. Instead of building up one string and comparing it to another, you should instead be splitting down the string you are being sent and dealing with the different parts of it separately.
Say you are being sent the string 32,read\r. Instead of making another string 32,read\r and comparing it to what you have received you should instead be splitting the incoming string up.
That way you then have a string containing 32 which can be converted to an integer, and a string containing read. It now becomes very simple to do your comparisons without messing with building strings in RAM wasting precious memory.

it will send the string: "1,read"

Fairly simple:
1) the dumbest would be to use serial print to print the number, and then ",read".
2) a close 2nd (in terms of dumbness) is to use s/printf(): simple but costly on a mcu.
3) a smarter approach is to convert the number to a string - you can use standard c routines if your compiler supports them, or hand-roll your own.
4) if the number of sensors are limited, a look-up table or a switch/case statement would work well.

If the PLC wants a reading from sensor #1, it will send the string: "1,read" All of the sensors should receive this string, but I only want the sensor with address '1' to respond.

Is your question about sending the "1,read".  If you're using a serial line like you say then there is no difference between sending that as a single string in one print command or sending first the number and then the text part using two print commands back to back. The exact same thing will end up going out over the wire either way.  So just use two separate print commands.


text:
Using typedef to declare a buffer type which then to pass by reference as function argument
I'm new to Arduino, but I'm a C/C++ veteran (not to mention some other languages).
Now I was under the impression that the code I'm typing into the Arduino IDE was a C or C++ dialect. However, just now I ended up puzzled because the compiler wouldn't swallow either of the following:
#define RFID_SIZE 5
#define CSUM_SIZE 1
typedef unsigned char rfidbuf_t[RFID_SIZE+CSUM_SIZE];

or my first attempt:
#define RFID_SIZE 5
#define CSUM_SIZE 1
typedef byte rfidbuf_t[RFID_SIZE+CSUM_SIZE];

Now I figure that a #define ought to be cheaper than a constant, so that's why I went for defines. The fact that #include is supported suggested to me there'd be a cpp in the Arduino development environment as well.
What struck me as odd was the fact that I get to see the error only on the next code line (not on the line with the typedef):
rfid_serial.ino:6:18: error: ‘rfidbuf_t’ was not declared in this scope
rfid_serial.ino:6:29: error: ‘code’ was not declared in this scope
rfid_serial.ino: In function ‘bool ReadRFIDTag(byte (&)[6])’:
rfid_serial.ino:15:33: error: ‘bool ReadRFIDTag(byte (&)[6])’ redeclared as different kind of symbol
rfid_serial.ino:6:6: note: previous declaration ‘bool ReadRFIDTag’
rfid_serial.ino: In function ‘void loop()’:
rfid_serial.ino:96:21: error: ‘ReadRFIDTag’ cannot be used as a function

The code I came up with was an attempt at optimizing the way this works. In particular I noticed that String (a class, it seems?!) Increases the size of my code quite a lot. So I thought a reference to the buffer would be a sensible choice here.
Here's the complete code:
#include <SoftwareSerial.h>
#define RFID_SIZE 5 // the code size (digits) of the RFID tag.
#define CSUM_SIZE 1  // the csum size (digits) of the RFID tag.
typedef byte rfidbuf_t[RFID_SIZE+CSUM_SIZE];

SoftwareSerial RFID(2, 3); // RX and TX

void setup()
{
  RFID.begin(9600); // start serial to RFID reader
  Serial.begin(115200); // start serial to PC
}

/* From: https://efxa.org/2013/05/23/simple-function-implementation-for-parsing-rfid-tags-in-arduino/ and adjusted. */
bool ReadRFIDTag(rfidbuf_t& code)
{
  byte value = 0;       // temporary data received from RFID reader.
  byte checksum = 0;    // checksum data of RFID tag received.
  byte bytesRead = 0;   // number of received data from RFID reader.
  byte tempByte = 0;    // temporary value used for checksum calculation.

  bool handled = false; // flag indicating if an RFID tag was handled.

  // if there are any data coming from the RFID reader.
  if (RFID.available () > 0)
  {
    // check for the STX header (0x02 ASCII value).
    if (0x02 == (value = RFID.read ()))
    {
      // read the RFID digits & the checksum digits.
      while (bytesRead < (RFID_SIZE + CSUM_SIZE))
      {
        // if there are any data coming from the RFID reader.
        if (RFID.available () > 0)
        {
          // get a byte from the RFID reader.
          value = RFID.read ();

          // check for ETX | STX | CR | LF.
          if ((0x0D == value) || (0x0A == value) || (0x03 == value) || (0x02 == value))
          {
            // stop reading - there is an error.
            break;
          }

          // convert hex tag ID.
          if ((value >= '0') && (value <= '9'))
          {
            value = value - '0';
          }
          else if ((value >= 'A') && (value <= 'F'))
          {
            value = 10 + value - 'A';
          }

          // every two hex-digits, add byte to code.
          if (bytesRead & 1 == 1)
          {
            // make some space for this hex-digit by shifting
            // the previous hex-digit with 4 bits to the left.
            code[bytesRead >> 1] = (value | (tempByte << 4));

            if (bytesRead >> 1 != 5)
            {
              // if this is checksum byte, calculate the checksum (XOR).
              checksum ^= code[bytesRead >> 1];
            }
          }
          else
            tempByte = value;

          // ready to read next digit.
          bytesRead++;
        }
      }

      // handle the RFID digits & the checksum digits.
      if (bytesRead == (RFID_SIZE + CSUM_SIZE))
      {
        // check if the RFID code is correct.
        if (code[5] == checksum)
        {
          // set that the tag was handled.
          handled = true;
        }
      }
    }
  }

  return handled;
}

void loop()
{
  rfidbuf_t buf = {0};
  if(ReadRFIDTag(buf))
  {
    Serial.println(buf[0]); // TODO
  }
}

Is it impossible to use typedef the same I'm used to from C and C++? Because what I am attempting isn't all too unusual in C or C++ code, but of course references only exist in C++.
Does it mean I should rather into working with avr-gcc directly? I was under the impression that the Arduino IDE is basically built atop avr-gcc and avrdude (and possibly other backend programs).

Side-note: I do know that there are still some issues in the code and it's not a faithful conversion of the linked code, yet. Problem is that I got stuck with the typedef, a seemingly trivial thing.

Compiles fine for me. What version of the IDE / compiler are you using?

@Majenko: 2:1.0.5+dfsg2-4 (latest version on latest Linux Mint).

1.0.5 is preancient. Please consider using something modern, even if you have to download it yourself.

Latest... that'a s a laugh...  You mean the ancient version that got left in APT a decade ago...

@Majenko: no, I meant latest available. Thanks for setting my head straight, nevertheless.

The latest in APT - not the latest available. That is version 1.8.5

Yes, I realize that. But keep in mind, if you don't rely on a  package manager to some extent you're usually a lost case as an admin. But duly noted, apparently I cannot trust that there are reasonably recent versions available via apt.

Your version of the IDE (1.0.5) is incredibly ancient (just because it's in APT doesn't mean it's up to date - only that at some point within the last 20 years someone submitted it).
That version suffers from the problems that Ignacio describes in his answer. More modern versions (we're up to version 1.8.5 now...!) use a different build system which is far more intelligent about how it lays out its function prototypes.
Go to the Arduino website and download the latest version and you won't have these kind of problems and have to work around them with strange things like unnamed namespaces.

The Arduino IDE (un)helpfully copies function declarations towards the top, but fails to handle custom types properly. The solution is to hide the declarations in an unnamed namespace.
 ...
typedef byte rfidbuf_t[RFID_SIZE+CSUM_SIZE];

namespace {
  bool ReadRFIDTag(rfidbuf_t& code);
}
 ...


text:
Trying to determine the phase difference between two square signals
I have been looking for the phase difference between two square signals and this is the code:
#include <avr/io.h>
#include <avr/interrupt.h>

void setup() {
  //Serial.begin(9600);
  pinMode(2, INPUT);    //set pins 2 and 3 as inputs and 11 as output
  pinMode(3, INPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);

  cli();           // disable all interrupts
  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);  //set up timer2 to generate a PWM
  TCCR2B = _BV(CS20);    //set prescalar value to 1
  //TCCR1A = 0;
  //TCCR1B = _BV(CS20);
  //TCCR1B |= (1 << CS12); //256 values
  TCNT2  = 0;
  sei();             //enable all interrupts

  attachInterrupt(digitalPinToInterrupt(2), t1_ISR, RISING);     //enable interrupt service routines on pins 2 and 3
  attachInterrupt(digitalPinToInterrupt(3), t2_ISR, RISING);

  //Serial.print(OCR2A);
  //Serial.print(OCR1A);

}

volatile uint8_t t1, t2;

void loop() {
  if (t2 == t1)
  {
    OCR2A = 0;
    OCR2B = 0;
  }
  //compare time that one signal goes high to time the other signal goes high
  else if (t2 > t1)
  {
    OCR2A = (t2 - t1); //output PWM based on phase difference on pin 11
    OCR2B = 0;
  }
  else if (t2 < t1)
  {
    OCR2B = (t1 - t2);  //output PWM on pin 11
    OCR2A = 0;
  }
}
}

void t1_ISR() {         //interrupt if signal on pin 2 goes high and store counter
  t1 = TCNT2;           //value to variable t1
}

void t2_ISR() {         //interrupt if signal on pin 3 goes high and store counter
  t2 = TCNT2;           //value to variable t2
}

I want to operate the input pulses at 40 kHz, how can I do this and read the difference of phase? I am using the Arduino Mega2560

Was there a question to go with this?

I do notice that the interrupts() and noInterrupts() right before loop are pointless.  That's at global scope.  You don't need to disable interrupts there, only in executing functions.  You should also be declaring any variables shared by your code and the ISR as volatile.

oh yes sorry! i took those off but the code won't work and I have declared t1 and t2 as volatile unsigned longs. I just wanted to ask what is wrong with the code?

What's wrong with this code?  Or the code you just described with a lot of things changed?  Please post the code that you actually want help with.
What does it do or not do when you run it and how does that compare with your expectations?  You haven't described any symptoms yet.  "It doesn't work" is a really useless statement.  It does something, and it's not what you wanted.  So you have to fill us in on what those things are.  Doesn't that make sense?

I posted again and this time its correct

No, they're still not volatile in the code posted.

i changed it with volatile int8_it

No you didn't.  The code in this question still doesn't say volatile.  You seem to have started another question, but I marked it as a duplicate so they should close that one.  You need to edit this question and put the code here.

It's suppost to read the phase difference as a PWM signal from 0-5volt and -5  to 0 volts

DO NOT REPOST, use the "edit" button to fix this, your original question.

"and -5 to 0 volts" an Arduino has no support for negative voltages!

Your re-post deleted. The "edit" link is there for a reason - edit the question if necessary to improve it.

I have declared t1 and t2 as volatile unsigned longs - no, you haven't.

I re-edited it, sorry I’m new. But for negative I just want the arduino to spit out the voltage so we can use a circuit to reverse voltage on that output so then it is negative

Maybe make t1 and t2 unsigned byte (ie. the byte type). If the high-order bit is set you may well get unexpected results.

I will try that. Thanks! Anymore suggestions on why it wouldn’t work?

Your timer 2 outputs on pins 10 and 11? Which Arduino is this? Please, add to your question the tag appropriate for the Arduino board you are using.

I am using pin 9 and 10 since I switched to arduino mega, it should be updated now, thanks!

There are a few things very wrong here.
First problem: you are clocking Timer 2 with the prescaler set to 1.
This means the timer will roll over every 256 CPU cycles. Your
input signal, on the other hand, has a period of 25 µs, which is
400 CPU cycles (I am assuming a 16 MHz Arduino). Unless you
know beforehand that the phase difference is within some window less
than 16 µs wide, your readings will be ambiguous.
You have to make sure the rollover period of your timer is larger than
the period of the input signal. This means either using a larger
prescaler (8 should do), which will decrease your phase resolution,
or using a 16-bit timer instead of an 8-bit timer.
Second problem: you are using a signed integer type for the timer
readings. This makes little sense. Worse: you are computing differences
like t2-t1, which can overflow. Signed integer overflow is undefined
behavior in C++, and
invoking it is always a bug.
You should declare t1 and t2 as unsigned, i.e. either
volatile uint8_t, or volatile uint16_t (if using a 16-bit timer).
Then you don't get overflows: you get instead a well-defined rollover
behavior.
Third problem: you are doing comparisons like if (t2 > t1). This,
again, makes no sense, if only because the timer is repeatedly
rolling-over to zero. You should instead just compute t2-t1 and work
your way from that.

how can I do this and read the difference of phase?

a few simple ways:
1) poll the input signals: For example, once a pin has gone high, wait for the other pin to go high as well.
2) xor the input signals: wait for the XOR of both inputs to go high, wait for it to go low. essentially the 1st approach;
3) use interrupts: once the first signal goes high, start a timer; once the 2nd signal to go high, stop the timer.
4) use input capture: ...
...


text:
Use mobile charger as power suppy to ESP8266 wifi module with 3.3v converter
I am using this FTDI connector to power and flash code inside ESP8266 module.

Now I am done with adding code to ESP8266, now I just want to power it.
but when I connect the mobile charger(5v output) instead of FTDI connect it gives only "?????? ???? ????" this output.
can't I use this as VCC and GND ??

If you've replaced the FTDI with a mobile charger, where are you seeing this output?

I am only replacing vcc and GND, Rx and Tx are as it is connected to FTDI.

But not GND to the FTDI board...? Where is your circuit then? How can electrons flow...?


text:
Why char 0x80 == 0xFFFFFF80?
As far as I know a char is an 8 bit variable

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

void loop() {
  char x = 0x80;
  if(x != 0x80){
    Serial.println(x, HEX);
  }

  delay(1000);
}

To illustrate the reasons better let's look at the actual content of the data.
0x80 is 0b10000000 in binary. A char is a signed variable, which means that the most significant bit is the sign bit, with two's complement representation
So in 8-bit signed representation the value 0b10000000 is a sign bit and zero value - which is -128 in decimal notation, which is "-128 + the 7 least significant bits", or -128 + 0 in this case.
When you print a signed value on the Arduino as HEX there is no 8-bit specific function for it. Neither is there a 16 bit function. However there is a 32-bit signed function, which is the closest match available. So the compiler performs type promotion to 32-bit signed, then represent it as hexadecimal.
Now -128 in signed 32-bit is calculated in the same way - take the value of the most significant bit, negate it, and add the value of all the other bits to it.  With 32-bits the value of the most significant bit, in decimal, is 2147483648, so negate that into -2147483648. Now we need to make that into -128, so we need the difference between the two to add to it. That's 2147483520.
So you get the MSB + 2147483520, which in hexadecimal, is 0xFFFFFF80.
Of course, the compiler doesn't go through that whole routine - instead it uses something called sign extension. This method basically means copying the sign bit from the original smaller (char) type into every bit to the left of it in the larger type:
                           10000000 8 bit signed
                  11111111 10000000 16 bit signed
11111111 11111111 11111111 10000000 32 bit signed

All those are -128 in two's complement, just stored in different size variables. So when you come to print it, that is just what you get - the two's complement representation of -128 in the variable size that has been accepted by the print function.
You might find this site useful for experimentation and furthering your understanding of variable data storage.

Sign extension. Try this:
void loop() {
  char x = 0x80;
  if(x != (char) 0x80){
    Serial.println(x, HEX);
  }

Before any operation involving different types, the lower ones must be promoted to higher ones.
The constant 0x80 is an integer value, so x must be promoted to int before the test. The first bit of an int value is the sign bit. Sign bit is extended (copied to the left side bits). So x become 0xFFFFF80 and then you compare it against 0x0000080.
Every time you put a char where an int is excepted the same thing happen.
See? Programming is hard, programming in C is harder, programming in C++ is the hardest.
C is full of traps.

char is signed so 0x80 is really -0x80 (==-128). When promoted to a higher width the sign gets copied into the new bits 0xffffff80 (still ==-128).
if you put unsigned in front of char you won't get that issue (though may encounter others).
void setup() {
  Serial.begin(9600);
}

void loop() {
  unsigned char x = 0x80;
  if(x != 0x80){
    Serial.println(x, HEX);
  }

  delay(1000);
}


text:
Analog input draws current when Arduino is turned off
I am using a Arduino Pro Micro from SparkFun (similar to Arduino Leonardo, cpu: Atmega 32u4). It has a analog input: A0, which I use to keep track of the battery voltage in my battery powered project (via analogRead).
I found out that the red LED on the board lights up, even if there is no supply voltage on the usual inputs (micro-USB or Vcc). If I use a multimeter to measure the current between the battery and A0, I see that the analog input is drawing about 30mA if the Arduino is not powered.
Is this the normal behaviour? Can I fix this via hardware?

Also asked at: http://forum.arduino.cc/index.php?topic=509951 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

Hi, thanks for pointing this out. Will post links in future posts!

Yes, it is normal behaviour, and it's called back-powering.
The current is flowing into the input pin and then flowing up through the ESD protection diode inside the chip to VCC.  It's bad, because the ESD protection diode can't take much current and is easy to damage.

simulate this circuit – Schematic created using CircuitLab
You can prevent it from happening by adding some isolation into the input:

simulate this circuit
MOSFET M1 will be ON when VCC has power, but off when it doesn't. The 100kΩ resistor pulls the gate to ground when VCC is off so it doesn't float. The diode is the body diode of the MOSFET added for clarity. You don't need to add a diode there.

Won't the Arduino be powered through the MOSFET's body diode then?

Depends which way round you connect the MOSFET. As long as the diode is facing the power source it won't conduct.

https://electronics.stackexchange.com/questions/134157/jtag-circuit-to-prevent-back-powering

@EdgarBonet But yes, I needed to flip the symbol there - had it backwards. I have also added the diode for clarity.

I am totally new to mosfets. Can you recommend a type?

One with a suitable logic-level threshold voltage.

I often use the BSS138P.

Did i read your schematic correctly? According to wikipedia you use a N-channel, normally unconductive mosfet.

My schematic uses an n channel enhancement mode (normally unconductive) MOSFET.

To get the MOSFET around the right way you want the input on the Drain and the Source goes to the Arduino. The Gate is connected to Vcc. The MOSFET wants to be N-channel enhancement mode "logic level" (that is, it will turn fully on with 5V on the Gate).

That's probably due to the clamping diodes. To protect the chip against ESD, there are diodes between the pins and Vcc and ground. This is to make sure that when charge builds up on a pin, it can flow to Vcc (when it's higher than the supply voltage) or to ground (when it's lower than ground level).
If you supply a voltage to a pin without a voltage on Vcc, current will flow through the pin to the supply line, powering the circuit.
You could probably solve this by adding a relatively large resistor in series with the pin.

How I calculate the required resistor?

This is normal, if you abuse the chip in this fashion.
But you must take into consideration that it is strictly prohibited to apply a voltage to any I/O pin when the chip itself is unpowered.
This is because the protection diodes are not rated to supply power to the chip, and relying on them to do so may cause damage.
The literal statement of this rule is in the data sheet as

Voltage on any Pin except RESET with respect to Ground . . . . . . . . . .-0.5V to VCC+0.5V

If VCC is 0v, then the maximum voltage you may apply to any I/O is half a volt which is approximately (or just below) the point where a protection diode would begin to meaningfully divert current from the I/O to trying to lift the Vcc net of the chip, and likely the entire board.


text:
I fried my arduino. Can I upload code wirelessly?
So, I'm a complete arduino newbie. I left a live wire close to my arduino and part of it burnt (underneath the USB output). The LED that indicates power still turns on when I plug it into my computer, and a simple LED circuit on my breadboard, when hooked up to the arduino, still works. The only thing that's wrong is that my computer doesn't recognize the Arduino serial port any more, so I can't upload any code onto it.
I also own a bluetooth HC-05 module. Is there any way I could upload code onto my Arduino wirelessly, using that? Or am I better off just buying a new one?

If the main MCU is still functioning fine then yes, sure you can.
The only caveat is that you may have to manually reset the Arduino at the right moment in order to enter the bootloader for programming.

Connect the bluetooth module to TX/RX/GND (TX->RX, RX->TX)
Configure the bluetooth module to work at the bootloader baud rate (115200 baud) - you may need to wire it to your PC to manage this part.
Connect a virtual COM port to it and program through that.
Press RESET just as it's about to run AVRDUDE in the IDE.

You did not say which Arduino you are using.
Most Arduinos abstract the complexities of the USB interface, format and protocol by using a 2nd processor on the Arduino board.  If damaged, you will essentially have to replace this function.  It is unlikely that a Bluetooth radio will act similar enough to do this.
If the main processor and supporting circuitry is not damaged, it would be easier to program the Arduino from another Arduino such as described here.

It sounds like you have fried the Atmega16U2  which is programmed as a USB-to-serial converter, as seen in the picture below.

You can still program the Atmega328P microcontroller using the ICSP and an appropriate Atmel programmer such as the Atmel Ice or the AVRISPmkII. Alternatively you can use another Arduino Uno as a In-System Programmer.
I cannot say about using a bluetooth HC-05 module,however I imagine it would be a fair bit of effort and hence would be easier to buy a new one. Keep the current one though because you can use the new one as an in-system programmer as per the link above.


text:
Does 12v 5A power supply is okay to operate motor shield external power
I am new to arduino.

Recently purchased motor shield V1.0 which have two l293 and can run 4 DC motors simultaneously.
But here the problem comes: when I purchased the shield I was not aware that it can only supply 2A peak current.
However, my DC motor rating is 12v 5A. So I purchased a 12v 5A power supply.
But now I am not sure to operate shield with external power of 12v 5A.
Does it works or will it burn?

It looks very much like this motor which isn't 5A - it's 300mA. Where did you get the idea of 5A from?

@Majenko actually it is written in motor 125A , so the shop owner told me that it is 12V and 5A motor

Well, my eyes don't lie to me - there is no 5A motor from Vega Robot Kit - certainly not in that style. So the shop keeper probably has no clue what he is talking about.

Thanks @Majenko, I understood your point of view.
So now I what should I use to power my motors, I tried the computer usb to arduino and placed the jumper so its moving slowly at 255 speed and 64 frequency

You can use your 12V 5A power supply and your motor shield. The motor should never draw more than 300mA, which is far less than both the motor shield and the power supply.

You mean to say remove that jumper and connect the power supply to motor shield directly

Yes. The motor needs 12V. You have to power the shield with 12V so the motor can get that 12V it needs.

So my motor shield will not burn by supplying 12V 5A external power supply?

@Majenko please reply

Only if you try and use more current than the shield can cope with. The 5A for the supply is the maximum it can supply, not what it will supply. The current draw is determined by the load, not the supply.

The shield will "burn". You need a shield that can provide minimum 5A per channel to run a 5A motor.
However, your motors aren't 5A. They have a stall current of 300mA, which is well within the capabilities of the motor shield, and the 5A power supply you have would barely even notice they were there.

What if the 5A is the average current ? If the stall current is 50A, then a motor driver of 50A is required.

@Jot We can only go by what we are told by the OP...

I updated my question, please review and provide appropriate answer

@Majenko please review my question

UmarAta, thanks for the photos. I think that is a 12V motor with 60mA or 70mA without load and 300mA stall current. Why do you think it is 5A ? Do you have specifications for that motor ?


text:
Arduino Digital Pins Control with ESP8266
I am currently working on my FYP. I need to control 15 servos (13 for x2 Robotic Arms + 2 for Camera) and 4 motors of my Robotic kit via webserver. I have the following options:

NodeMCU
Arduino Mega + ESP8266

Now since NodeMUC has only 10 digital pins the only option I am left with is (Arduino Mega+Esp8266).
I have used the following code to control servo on a NodeMCU.
#include <Servo.h>
#include <ESP8266WiFi.h>

Servo servo;

const char* ssid = "ssid";
const char* password = "password";
WiFiServer server(80);
void setup() {
  servo.attach(4); //or any pin

  servo.write(0);

  Serial.begin(115200);
  delay(10);

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();
  if (request.indexOf("/?30") != -1)  {
    servo.write(30);
  }

//
  if (request.indexOf("/?90") != -1)  {
    servo.write(180);

  }

  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("");

  client.println("

");
  client.println("<button>30</button>");
  client.println("<button>60</button>");
  client.println("<button>90</button>");
  client.println("<button>120</button>");
  client.println("<button>150</button>");
  client.println("<button>180</button>");
//  client.println("<button>Thirty Mins</button>
");
  client.println("");

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");

}

My question is that the can the code written for NodeMCU be used with ESP8266 to control Arduino Digital Pins? I want the same code to be used.
PS : I don't want to use SoftwareSerial library and ATC commands.
Or some alternative to NodeMCU with same functionality as NodeMCU but with more GPIO pins.

you could try Standard Firmata sketch in Arduino and FirmataMaster library in ESP8266

thanks!
but can the same code for NodeMCU be used for ESP2866 also.

your sketch looks like you use the Arduino core for esp8266 on the NodeMCU hardware