text:
Arduino nano digital pins not working with external power source
We are using an Arduino Nano for simple serial comms to fire a relay from a Windows 10 PC.
Initial issue we had was windows not recognizing the device (COM Port) when the pc is powered off (as per this link: Arduino Nano - USB not present after reboot ) so we powered the arduino nano over a 5V pin and now when Windows starts up the device is recognized.
However, as I'm learning with these chips, nothing is ever that simple. Now the relay that we are firing does not work with external power, but if you unplug the external power then the relay does fire (powered over USB)
The units are at a mine and at the moment and I believe that the problem is that the serial chip is now not responding as per this - from the official Arduino Nano page:
The FTDI FT232RL chip on the Nano is only powered if the board is being powered over USB. As a result, when running on external (non-USB) power, the 3.3V output (which is supplied by the FTDI chip) is not available and the RX and TX LEDs will flicker if digital pins 0 or 1 are high.
Note - I included the above from another question but this no longer appears on the official arduino nano page (can't past link as it's my first post)
The question is how can we get the digital pins on the arduino nano to fire using an external power source and input from a Windows PC?
Thanks
Diagram:

"units are at a mine" I don't know what your are doing, but if you are operating an Arduino and an off-the-shelf relay in a mining environment, you are likely violating safety rules and/or laws related to electronics in hazardous environments. Have you considered the hazardous location equipment qualifications needed for electronics?

The relay is to fire a turnstyle and it's not related to any industrial equipment and the guys on site are working under supervision so I don't think that this is an issue

I think you may need to back up and start over again.
Rather than changing the power supply, you need to fix the problem that made you think you needed to change power supplies.
Following a link in a comment on the question you linked  to leads to this thread on the Arduino forums.
The suggestion there is that a particular pin on the FTDI chip on the Nano isn't connected as it should be.
To be exact, the Test pin (pin 26 on the FT232RL chip) needs to be grounded to fix the original problem you were having with communications with the Nano.
The description there fits your description.  The Nano can't talk to the PC if the Nano is connected to the PC at power on.  The same thing happens with the circuit referenced in that Arduino forum thread, but they are using another embedded system instead of a PC.
If you fix that, then you won't need to use an external 5V supply.
To back up the conclusion from the Arduino forum, here's an excerpt from page 8 (pin descriptions) of the FT232RL datasheet:

26 TEST   Input  Puts the device into IC test mode. Must be tied to GND
  for normal operation, otherwise the device will appear to fail

You need to connect pins 25 (ground) and pin 26 (Test.)
Excerpt from the Nano schematic:

Pins 25 (ground) and 26 (Test) are right next to one another, so easy to fix.
You need to put a blob of solder on the red marked spot in this picture:

Thanks. I do agree this is probably the right way to do it - but because the site is so remote we did not want to risk blowing the board. I've accepted as answer and then added what we did as a "workaround"

I accepted the answer from JRE as I believe this is the best answer. For certain reasons we weren't able to do this so I've posted this as a workaround.
We ended up splitting the USB input to the arduino nano by using a Y cable. We used the one end for the power to the device and the other end for comms from the PC (with power disabled). This solved our issue as the chip now received power and responded to comms and the USB driver also initialised correctly on Windows when starting up.
If you are unable to solder the chip then this is a workaround that we have used.


text:
Blink Adafruit_NeoPixel
I wish to blink all the strip. In the code below it just blink the first LED, how can I fix it?
Code:
#include <Adafruit_NeoPixel.h>

#define PIN 6
#define NUM_LEDS 24

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show();
}

void loop() {
  strip.setPixelColor(0, 255, 255, 255);
  strip.show();
  delay(1000);
  strip.setPixelColor(0, 0, 0, 0);
  strip.show();
  delay(1000);
}

The first argument of setPixelColor is is the number of the led. In your case 0, so the first led.
Instead use a for loop to set all the leds from 0 until (excluding) 24 (which is stored in NUM_LEDS).
void loop()
{
  for (int led = 0; led < NUM_LEDS ; led++)
  {
    strip.setPixelColor(led, 255, 255, 255);
  }
  strip.show();
  delay(1000);

  for (int led = 0; led < NUM_LEDS ; led++)
  {
    strip.setPixelColor(led, 255, 255, 255);
  }
  strip.show();
  delay(1000);

To make the code better (shorter, but more important more maintainable, and reducing code duplication), create a separate function:
void loop()
{
  setLeds(255);
  setLeds(0);
}

void setLeds(int intensity)
{
  for (int led = 0; led < NUM_LEDS ; led++)
  {
    strip.setPixelColor(led, intensity, intensity, intensity);
  }

  strip.show();
  delay(1000);
}

Thanks. In the longer script I presume it should be strip.setPixelColor(led, 0, 0, 0);

Yes, because the argument intensity decides when values 0 or 255 are used.

source: Stack Exchange

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

sort: votes


text:
Set slide potentiometer values
I am using the Grove - Slide Potentiometer (http://wiki.seeedstudio.com/Grove-Slide_Potentiometer). How can I set the potValue so that at maximum it will 128?
int potPin= A0;
int readValue;
int potValue;

void setup() {
  pinMode(potPin, INPUT);
  Serial.begin(9600);
}

void loop() {
 readValue = analogRead(potPin);
 potValue = (255./500.) * readValue;
 Serial.print("You are writing a value of ");
 Serial.println(potValue);
}

You can use the map function, see https://www.arduino.cc/reference/en/language/functions/math/map/.
Example: If your pot meter gives values from 100 to 1000 and you want to map that range to a range of 0 to 128 you can easily write:
potValue = map(readValue, 100, 1000, 0, 128);

High likely, in your case and if the potentiometer is 'perfect' it returns values from 0 to 1023 and you can write:
potValue = map(readValue, 0, 1023, 0, 128);

with potValue = map(readValue, 0, 1023, 0, 128); I get the max value of 186.

What is the maximum raw value you get? … you can increase the value of 1023 to assume a higher  maximum (set it to the maximum value you get from the pot).

the mx. value of readValue is 728

According to the documentation, map(728, 0, 1023, 0, 128) should be something like 91.  (728/1023*128). If you would use map(value, 0, 728, 0, 128) you should get values upto 128.

Consider that map is using integer arithmetics (truncating). To get evenly spaced areas, you'd rather map (readValue,0,1024, 0,129);( Will transform 0..1023 to 0..128 and everything > 1016 will show 128)   If this is really what you want.

analogRead() returns 0x0000 to 0x03ff
If the max data 0x03ff is shifted to the right by 3 bits (or divide by 8),
then 0x03ff becomes 0x007f, or 127.
I think this will do it:
desiredMax = analogRead(A0) >> 3; // divide 1023 max by 8, becomes 127 max

fast and simple, but less readable. +1

Less readable?  // add a comment to the line

No need for (less readable) bitshifting - dividing by 8 yields the same compiled code as the right shifts (https://godbolt.org/z/V82L6Z)

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


text:
Library that pulls ID3v2 info from MP3s
I'm using an Adafruit Music Maker with a TFT screen on my Mega 2560. I can pull ID3v1 data from the end of an MP3, but I'd like to get the ID3v2 data as I can then push the album cover art to the TFT along with the title/artist/album/etc.
My initial searches have turned up nothing for a library that pulls the ID3v2 headers. Before I start to crack that nut on my own, I want to make sure I am not overlooking something.
Has anyone used a library to pull ID3v2 data from an MP3?

Here's what I have written so far. This pulls data from the ID3v2 header at the start of the mp3 file.
void frameInfo(File track, char tvalue[64], char albval[64], char artval[64],
char fname[30], bool showpic) {
uint32_t start = 10;
uint32_t lastfrm = 10;
bool done = false;

track.getName(fname,max_chars);

while (!done) {
 uint8_t buff[4];
 uint32_t ltwo[4];
 char tag[5];
 uint32_t fsize;
 track.seek(start);
 track.read((uint8_t *)tag, 4);
 tag[5] = 0;

 track.seek(start + 4);
 track.read((uint8_t *)buff,4);
 ltwo[0] = buff[0];
 ltwo[1] = buff[1];
 ltwo[2] = buff[2];
 ltwo[3] = buff[3];

 fsize = (ltwo[0] << 24) | (ltwo[1] << 16) | (ltwo[2] << 8) | ltwo[3];
 start = start + 10;

if (tag[0] == 'T' && tag[1] == 'I' && tag[2] == 'T' && tag[3] == '2') {
  uint32_t i;
  int vlen = 0;
  char val[fsize];

  track.seek(start);
  track.read((uint8_t *)val, fsize);
  for (i=0;i<fsize;i++) {
    if (isAlphaNumeric(val[i])) {
      tvalue[vlen] = val[i];
      vlen++;
    }
    else if (val[i] == '(' || val[i] == ')' || val[i] == ' ') {
      tvalue[vlen] = val[i];
      vlen++;
    }
  }
  tvalue[vlen] = '\0';
}
else if (tag[0] == 'T' && tag[1] == 'A' && tag[2] == 'L' && tag[3] == 'B') {
  uint32_t i;
  int vlen = 0;
  char val[fsize];

  track.seek(start);
  track.read((uint8_t *)val, fsize);
  for (i=0;i<fsize;i++) {
    if (isAlphaNumeric(val[i])) {
      albval[vlen] = val[i];
      vlen++;
    }
    else if (val[i] == '(' || val[i] == ')' || val[i] == ' ') {
      albval[vlen] = val[i];
      vlen++;
    }
  }
  albval[vlen] = '\0';
}
else if (tag[0] == 'T' && tag[1] == 'P' && tag[2] == 'E' && tag[3] == '1') {
  uint32_t i;
  int vlen = 0;
  char val[fsize];

  track.seek(start);
  track.read((uint8_t *)val, fsize);
  for (i=0;i<fsize;i++) {
    if (isAlphaNumeric(val[i])) {
      artval[vlen] = val[i];
      vlen++;
    }
    else if (val[i] == '(' || val[i] == ')' || val[i] == ' ') {
      artval[vlen] = val[i];
      vlen++;
    }
  }
  artval[vlen] = '\0';
}

else if (tag[0] == 'A' && tag[1] == 'P' && tag[2] == 'I' && tag[3] == 'C') {
  uint32_t i;
  int vlen = 0;
  char val[30];
  char test[30];
  uint8_t raw[fsize - 11];

  track.seek(start);
  track.read((uint8_t *)val, 11);
  for (i=0;i<11;i++) {
    if (isAlphaNumeric(val[i])) {
      test[vlen] = val[i];
      vlen++;
    }
    else if (val[i] == '(' || val[i] == ')' || val[i] == ' ') {
      test[vlen] = val[i];
      vlen++;
    }
  }
  test[vlen] = '\0';

  if (fsize < 200000) {
    track.seek(start+11);
    Serial.println(fsize+11);
    //track.read((uint8_t *)pic, fsize-11);
  }

}
else {

}

start = start + fsize;
if ((start == lastfrm + 10) || start > musicPlayer.mp3_ID3Jumper(track)) {
  done = true;
}
else {
  lastfrm = start;
}

}
track.rewind();
}

This pulls the text data for title/artist/album, but the problem is how to read the image from the header without overloading the Mega. Most of the images are around 30K bytes, but there is no room in RAM on the Mega for that kind of space. I have my sketch set to read the jpeg format, convert it to BMP, then write it to the TFT. Is there some method I could use to have the sketch write the bytes to a file on the SD card, then read them from there?

There is an SD library meant for use with the VS1053 which has some extra id3 tag support. Check it out here : https://github.com/mpflaga/Arduino_Library-vs1053_for_SdFat

I did find that, but it only reads ID3v1 tags, which are at the end of the file and only contain the artist/title/album information.


text:
memory leak w/ no Strings involved
I'm trying to read data being transferred via Infrared from my Smartmeter on my ESP8266 using the following sketch:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPUpdateServer.h>
#include <Ticker.h>
#include <AsyncMqttClient.h>

#ifndef STASSID
#define STASSID "mySSID"
#define STAPSK  "myPassword"
#endif

#ifndef MQTT_HOST
#define MQTT_HOST IPAddress(192, 168, 0, 100)
#define MQTT_PORT 1883
#endif

#ifndef IR
#define SerialDebug Serial1
#define IR Serial
#endif

AsyncMqttClient mqttClient;
Ticker mqttReconnectTimer;

WiFiEventHandler wifiConnectHandler;
WiFiEventHandler wifiDisconnectHandler;
Ticker wifiReconnectTimer;

const char* host = "esp8266-webupdate";

const byte firstByte = 0x7E;
const byte lastByte = 0x7E;

uint8_t i;

ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;

void connectToWifi() {
  SerialDebug.println("Connecting to WiFi ...");
  WiFi.begin(STASSID, STAPSK);
}

void connectToMqtt() {
  SerialDebug.println("Connecting to MQTT ...");
  mqttClient.connect();
}

void onWifiConnect(const WiFiEventStationModeGotIP& event) {
  SerialDebug.println("Connected to Wi-Fi.");
  connectToMqtt();
}

void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
  SerialDebug.println("Disconnected from Wi-Fi.");
  mqttReconnectTimer.detach();
  wifiReconnectTimer.once(2, connectToWifi);
}

void onMqttConnect(bool sessionPresent) {
  SerialDebug.println("Connected to MQTT.");
  SerialDebug.print("Session present: ");
  SerialDebug.println(sessionPresent);
}

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  SerialDebug.println("Disconnected from MQTT.");

  if (WiFi.isConnected()) {
    mqttReconnectTimer.once(2, connectToMqtt);
  }
}

void array_to_string(byte array[], unsigned int len, char buffer[]) {
  for (unsigned int i = 0; i < len; i++) {
    byte nib1 = (array[i] >> 4) & 0x0F;
    byte nib2 = (array[i] >> 0) & 0x0F;
    buffer[i*2+0] = nib1  < 0xA ? '0' + nib1  : 'A' + nib1  - 0xA;
    buffer[i*2+1] = nib2  < 0xA ? '0' + nib2  : 'A' + nib2  - 0xA;
  }
  buffer[len*2] = '\0';
}

void setup() {

  SerialDebug.begin(115200);
  IR.begin(9600);
  SerialDebug.println();
  SerialDebug.println("Booting Sketch...");

  wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
  wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);

  mqttClient.onConnect(onMqttConnect);
  mqttClient.onDisconnect(onMqttDisconnect);
  mqttClient.setServer(MQTT_HOST, MQTT_PORT);

  connectToWifi();

  httpUpdater.setup(&httpServer);
  httpServer.begin();

  mqttClient.setWill("smartmeter/online", 0, true, "no");
}

void loop() {
  httpServer.handleClient();

  uint32_t timeout = 2000;

  int readCnt = 0;
  uint32_t start_time = millis();
  byte tempChar = 0;
  byte *readMessage;
  uint32_t messageLen = 0;

  while ((tempChar != 0x7E) && (millis() - start_time < timeout)) {
    if (IR.available()) {
      tempChar = IR.read();
    }
  }

  start_time = millis();
  timeout = 1000;
  bool done = false;

  if (tempChar == firstByte) { // if first byte == 0x7E
    while ((millis() - start_time) < timeout && !done) {
      if (IR.available()) {
        tempChar = IR.read(); // second byte must be 0xA0
        if(tempChar == 0xA0) {
          while ((millis() - start_time) < timeout && !done) {
            if (IR.available()) {
              tempChar = IR.read(); // 3rd byte tells the legth of the message

              readMessage = new byte[tempChar+2];
              memset(readMessage, 0, tempChar+2);
              readMessage[0] = firstByte;
              readMessage[1] = 0xA0;
              readMessage[2] = tempChar;
              messageLen = ((uint32_t)(tempChar))+2;
              readCnt = 3;

              while ( readCnt < messageLen && ((millis() - start_time) < timeout)) { // minimum len 120 chars for 0x7E format
                if (IR.available()) {
                  readMessage[readCnt] = IR.read();
                  readCnt++;

                  if(readCnt == tempChar+2 && readMessage[readCnt-1] != lastByte) { // correct len but last byte not 0x7E
                    done = true;
                    SerialDebug.printf("Wrong end byte found - %d\n", readMessage[readCnt-1]);
                  } else if(readCnt == tempChar+2) { // correct len and correct last byte
                    done = true;
                    char str[251] = "";
                    array_to_string(readMessage, readCnt, str);
                    mqttClient.publish("smartmeter/raw", 0, false, str);
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  mqttClient.publish("smartmeter/online", 0, true, "yes");
  char heap[6] = "";
  itoa(ESP.getFreeHeap(), heap, 10);
  mqttClient.publish("smartmeter/freeHeap", 0, false, heap);
}

I'm getting the encoded HEX-data published on my MQTT Topic as desired, the outputs length is 250 characters long (= 125 Bytes) which is correct:

7ea07bcf000200231362b1e6e700db08534d536770075f626120000e32e62addedaede38e64c8c3173035a0a853851a28efc57f7fd76a9df59dbb152f796939328ff0f28df7f257d20b5cb2a458c4eb9188e2c1c251701c891244d859ed9c159714bb4451c090d9b1ed3bbb1fc89785ebafbf59ec4f9d540eb4c90d47e

As I found out, the ESP's heap is decreasing by 100-300 by each iteration of the loop (data is being transmitted every second via Infrared from the power-grid Smartmeter) until the ESP will eventually be rebooted by the watchdog after like 5-8 minutes.
I explicitly did not use String variables in the sketch but I legit cannot find the reason for the memory leak. Tried turning off wifi, webserver and mqtt one after each other which didn't actually made a difference.
The heap-size stays at a constant level though when there is no data being received via the Infrared serial port, so I imagine something is fishy when storing the data in the byte array "readMessage".
Anything obvious that immediately pops into someones eye that I missed?

the 'problem with Strings' is a problem with new hidden in String class. your use of new is not hidden

You do a new inside the loop
 readMessage = new byte[tempChar+2];

which causes the heap to be filled with tempChar+2 bytes, but you never delete this.
Try reusing this memory (making it a local, or make it 'dirty' global).
Probably (not tested) the above line can be rewritten as:
byte readMessage[tempChar+2];

By now I was already convinced it's something so obvious sigh
A simple delete[] readMessage; after the MQTT publish of the "str" variable did the trick!
Even if I went a different path so actually solve the problem, you gave the actual hint that guided me there, so I'll mark your answer as accepted.
Thank you very much!

You are welcome ... however, take in mind that a new and delete is not needed in this case, as the data only lives within one function. Typically new / delete is used when the life span of data is higher than one function, or when the amount of data is not known beforehand/varies.

True that - I will definitely take it into account when I will be implementing parts of this sketch to the final code!


text:
Does setting a value always mean setting a Arduino pin?
One thing that always confused me was why we use int or other commands to set the variables to have pin numbers as if those commands were always restricted to pin numbers only. For example
int ledPin = 13;

Does putting a random number in place of 13 that isn't a pin number cause an error? Right now I haven't checked yet.
I've only begun to realize that if you want to use variables in relation to pins or push buttons you have to set values first and then do associated functions like digitalRead. The commands like int are not like in other programming languages where you can set any values and do mathematical computations. I know it might seem obvious to someone who is used to Arduino, but this perspective is something that helped me grasp things better. Before that, I totally could not understand how things worked because of being confused with how int or other similar variables worked.

What is your question? Do you understand what the statement int ledPin = 13; does in C++? This actually does two things:1) It declares the variable ledPin as a variable of type "integer" and 2) It assigns the value 13 to that variable. It could also be written as two separate commands int ledPin; and ledPin = 13;. It has nothing to do with port numbers until you use the variable to refer to an IO port like with digitalRead(); or digitalWrite();.

what other languages do you know?

int is not a “command”, it's a data type. The whole line is a variable declaration: int ledPin = 13; means “let ledPin be an integer initially having the value 13”.

Thank you for the comments. I'm just new to learning Arduino and I find it hard currently to grasp since the professor explaining does not do it in detail. That's why I didn't get how the int had completely nothing to do with the port numbers. Although off topic, I would want to ask for references that would help me grasp the correct terminologies and concepts since searching in Google generally did not help my particular understanding.

Note that this is just a C/C++ integer declaration, assigning a value to a variable, like any variable (irrelevant if it is for pin numbers).
You don't have to use a variable, there are similar variations:
Variable
int pinNumber = 13;

in begin:
pinMode(pinNumber, OUTPUT);
digitalWrite(pinNumber, HIGH);

Const
Preferably I like to use a const:
const int PIN_NUMBER = 13;

Or even better, since it always is a low value:
const uint8_t PIN_NUMBER = 13;

And use it with capitals.
pinMode(PIN_NUMBER, OUTPUT);
digitalWrite(PIN_NUMBER, HIGH);

#define
#define PIN_NUMBER 13

pinMode(PIN_NUMBER, OUTPUT);
digitalWrite(PIN_NUMBER, HIGH);

The reason variables are used, is that when you want to use another pin number, you only need to change it in one place, making the sketch better maintainable/adaptable.
I don't know what happens when you give an illegal number (you can try it out yourself).


text:
inconsistent digital output on simple code
so im new on arduino coding, and i made this code, where i input from serial monitor and then use it as a command for digital write. the problem is, sometimes the code work perfectly but then when i input 4, both D3 ad D4 is high and that also happens in D5 and D6. but its inconsistent, and i also print the 'out' value and also which digital pin is high to make it easier.
byte b;
int out;
int D3 = 3;int D4 = 4;int D5 = 5;int D6 = 6;int D7 = 7;int D8 = 8;
void setup() {
  Serial.begin(9600);
  pinMode(out, OUTPUT);
  digitalWrite(D3, LOW);digitalWrite(D4, LOW);digitalWrite(D5, LOW);digitalWrite(D6, LOW);digitalWrite(D7, LOW);digitalWrite(D8, LOW);

}

void loop() {
  while (Serial.available() == 0) {}
  b = Serial.read() - 48;
  out = b;
  Serial.print("\n Out is ");
  Serial.println(out);
  digitalWrite(out, HIGH);
  delay(600);
 if (digitalRead(D3) == HIGH)
{
   Serial.print("D3 HIGH");
}
 if (digitalRead(D4) == HIGH)
{
   Serial.print("D4 HIGH");}
 if (digitalRead(D5) == HIGH)
{
   Serial.print("D5 HIGH");
}
 if (digitalRead(D6) == HIGH)
{
   Serial.print("D6 HIGH");
   }
 if (digitalRead(D7) == HIGH)
{
   Serial.print("D7 HIGH");
}
 if (digitalRead(D8) == HIGH)
{
   Serial.print("D8 HIGH");
   }
  digitalWrite(out, LOW);
  delay(1000);

}

does anyone know why this happens? or can anyone recommend another method to do what im tryinng to do? thank you guys!!!

If I look at the first 5 lines:
byte b;
int out;
int D3 = 3;int D4 = 4;int D5 = 5;int D6 = 6;int D7 = 7;int D8 = 8;
void setup() {
  Serial.begin(9600);
  pinMode(out, OUTPUT);

You see that pinModeout, OUTPUT)uses a variableoutwhich is not initialized (it's only declared inint out`'.
I assume D3 to D8 are all output pins, so you have to replace the last line with:
pinMode(D3, OUTPUT);
pinMode(D4, OUTPUT);
pinMode(D5, OUTPUT);
pinMode(D6, OUTPUT);
pinMode(D7, OUTPUT);
pinMode(D8, OUTPUT);

Also, since you are using all pins in the same way, I suggest you use two variables: startPin and endPin. Then you can use a for loop to iterate through all pins. Also

always initialize variables.
use '0' instead of 48 when you convert from a byte value to a character (since you don't need to know the ASCII value of '0').

I don't have an Arduino compiler at hand, but it should look something like:
byte b = 0;
int out = 0;
const byte startPin = 3;
const byte endPin = 8;

void setup() {
  Serial.begin(9600);
  for (byte pin = startPin; pin <= endPin; pin++)
  {
      pinMode(pin, OUTPUT);
      digitalWrite(pin, LOW);
  }
}

void loop() {
  while (Serial.available() == 0) {}
  b = Serial.read() - '0';
  out = b;
  Serial.print("\n Out is ");
  Serial.println(out);
  digitalWrite(out, HIGH);
  delay(600);

  ...

However, from here you are using the pins as INPUT pins. You cannot change those on the fly, you might change them manually (by using pinMode(pin, INPUT)), but it does not seem normal to switch input and output pins, so maybe you should explain what you are intending with your application.

Hey, thank you so much, your recommendation actually solve the problem so far lol, and the intention of the program is fairly simple, i just need to input number to serial monitor and made the digital pins give out the output according to the numbers, (3456 in serial monitor means pind D3 til pin D6 gives out high value one by one.

but I still don't understand why you need to read the pins; if you write a HIGH you can assume the pin will be HIGH, no need (or you should) not read them, as they are configured to be output pins, not input pins.

yeah i dont need to, but i just need to check whether my code is working as intended, and i have limited resources where im at right now due to corona so i stuck in a place where nobody even sell resistor or LED

I doubt it will work this way, because if you change the pin mode, it will not output the signal anymore. Better use a multimeter to check the pin voltages.

yeah, its just temporary, thanks for the advice!!! i really appreciate it! :)

Ok, good luck. If the answer helped, upvote it (up arrow next to my answer), if a problem is solved, also accept the answer (check box next to the answer). Welcome to Arduino stackexchange.

At least on AVR, digitalRead() on an pin configured as OUTPUT is perfectly fine. pinMode() controls the output buffer, the input buffer is always active.

@EdgarBonet Thanks for the comment, good to know.


text:
Simple Multiple RX/TX SoftwareSerial?
In this project I will be using multiple ESP8266 WiFi modules (4) connected by software serial to an Arduino Leonardo Micro (1 UART). I plan to rotate between all 4 (starting with 2): Open port, write, read response, close port, move on....
This is a very barebones version of my code to address this one issue. Works flawlessly with a single (always open) connection, but it does not work when I close Ser1 (even if I don't start Ser2!!!)
Is the xxxx.end(); command broken or something?
Or am I doing something wrong? :/
Note: This code sends "AT" to the module, it responds with "OK"
When adding Ser2, LED flashes on Arduino periodically indicating it is writing to serial monitor, but nothing appears...
Code:

#include <SoftwareSerial.h>

SoftwareSerial Ser1(10, 8);
SoftwareSerial Ser2(16, 7);
SoftwareSerial Ser3(14, 4);
SoftwareSerial Ser4(15, 2);
//Set up (RX, TX) pins^

void setup() {

  pinMode(10, INPUT);
  pinMode(16, INPUT);
  pinMode(14, INPUT);
  pinMode(15, INPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(2, OUTPUT);
  Serial.begin(9600);
  //Set up Serial Monitor on host computer

}

void loop()
{

  delay(1000);

  Ser1.begin(9600); // open Ser1

  Ser1.write( 'A' );
  Ser1.write( 'T' );
  Ser1.write( '\r' );
  Ser1.write( '\n' );   // sends the line: "AT" with appropriate format

  Ser1.listen(); // make sure it's listening

  while ((Ser1.available() > 0)) { //Read entire string
    Serial.write(Ser1.read()); //Dump it to serial monitor
  }

  //Should Respond with "OK"

  Ser1.end(); //close Ser1 port
  //This breaks the code for some reason....

  Serial.println(); // Extra line in Serial Monitor for neatness

  Ser2.begin(9600); // open Ser2

  Ser2.write( 'A' );
  Ser2.write( 'T' );
  Ser2.write( '\r' );
  Ser2.write( '\n' );

  Ser2.listen();

  while ((Ser2.available() > 0)) {
    Serial.write(Ser2.read());
  }

  Ser2.end();

}

Why are you beginning and ending the object each time instead of just beginning once?

@Ignacio,  Software serial is only capable of one connection at a time, so it must be closed before I switch to a different port. Problem is my attempt to close it breaks the code. :(

No, it is capable of only receiving on one connection at a time.

@IgnacioVazquez-Abrams Do you suggest beginning them all in setup? Then how can I switch the receiving from port to port?

Exactly how you already are.

As Ignacio mentions, you should not be stopping and starting the serial ports. Instead just switch between them with .listen():

Enables the selected software serial port to listen. Only one software serial port can listen at a time; data that arrives for other ports will be discarded. Any data already received is discarded during the call to listen() (unless the given instance is already listening).
SoftwareSerial::listen() Manual Page

So your code would be written as:
#include <SoftwareSerial.h>

SoftwareSerial Ser1(10, 8);
SoftwareSerial Ser2(16, 7);
SoftwareSerial Ser3(14, 4);
SoftwareSerial Ser4(15, 2);
//Set up (RX, TX) pins^

void setup() {
  Serial.begin(9600);
  Ser1.begin(9600); // open Ser1
  Ser2.begin(9600); // open Ser2
}

void loop()
{

  delay(1000);

  Ser1.listen(); // Select Ser1 for receiving
  Ser1.print(F("AT\r\n"));

  delay(1000); // Give it time to send a response or you'll get nothing!

  while ((Ser1.available() > 0)) { //Read entire string
    Serial.write(Ser1.read()); //Dump it to serial monitor
  }

  //Should Respond with "OK"

  Serial.println(); // Extra line in Serial Monitor for neatness

  Ser2.listen(); // Select Ser2 for receiving
  Ser2.print(F("AT\r\n"));

  delay(1000); // Give it time to send a response or you'll get nothing!

  while ((Ser2.available() > 0)) {
    Serial.write(Ser2.read());
  }
}

I really appreciate how you fixed my problem AND optimised my code at the same time!! I think the main issue was not waiting for a response (I tried your fix lol). Amazing work!!

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


text:
Peer to Peer using Ethernet Module
I'm beginner here at arduino stuff. i just started learning arduino and i have this small homework where i NEEDED to connect 2 arduino using ethernet shield or module ONLY over a distance of 20 meters.
I don't have my modules yet but i want to atleast study it now while i'm waiting for it. I can't seem to see any tutorials about it nor anyone tried it. How can i do this? i hope you can help me and give some insights, links, etc reference. Thanks :)
EDIT:
I had in mind where these arduino will have their own identity, 1st arduino will be receiving only some data coming from 2nd arduino. The 2nd arduino will have sensors and read them then sends them to 1st arduino. Now, i like my 2nd arduino to have a power source coming from the 1st arduino to save power supply installation and since it'll be like a remote arduino. Thus has anyone has experience applying PoE on arduino?

PoE uses 48V ... if you want to use actual PoE injectors, then you will need to use a power supply at each arduino

You will need a crossover cable to connect two Ethernet shields peer to peer.
Then you configure the Ethernet library to use static IP address. Use 192.168.1.1 and .2 address. (Or other 192.168.x.x address). Set subnet 255.255.255.0. Gateway should be the IP address of the other Arduino.

hi juraj, :D thanks a lot, never knew i need to consider that, i thought i just have to buy ethernet cable, i'll drop by my progress here and notify if it work

i was thinking also regarding PoE application, goal was 1st arduino is like the server and only reads send messages from 2nd arduino as client since it will have sensors connected to it and i want 2nd arduino to have its power source coming from where 1st arduino is put. would that be possible?

sorry, I have no experience with PoE and having Arduino as a PoE source is not so common, I think

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


text:
Send a polymorphic object over serial
I am sending a polymorphic object over serial between two Arduinos. The transmission should be fine, indeed if on the receiver side I static_cast the pointer to the Derived class it works properly. On the other hand if I try to call virtual functions on the Base pointer, Arduino resets. What is causing this behaviour?
Some samples of the code follows.
Sender:
RS485_Serial bus;
void loop ()
{
  Random r(1); //targeting device 1 in the bus
  if (r.request(bus)) { blink(r.val); } //make a request for a random number
                                        //blink the led the given number of times

  delay(1000);
}

Receiver:
RS485_Serial bus;
bus.set_address(1);
void loop ()
{
  listen(bus);
}

Selected common parts:
struct Action {
  byte target_address;

  Action(byte addr): target_address(addr) {}
  virtual ~Action() {}

  virtual size_t size() const { return sizeof(*this); }
  virtual int  vrequest(RS485_Serial &) = 0;
  virtual void vrespond(RS485_Serial &) = 0;

  int request(RS485_Serial & bus) {
    bus.write(reinterpret_cast<byte*>(this), size());
    return vrequest(bus);
  }
  void respond(RS485_Serial & bus) {
    vrespond(bus); // <--- This virtual call makes the sender reset
  }
};

struct Random: Action {
  size_t size() const override { return sizeof(*this); }
  int val;
  Random(byte address): Action(address) {}

  int vrequest(RS485_Serial & bus) override {
    return bus.read(val);
  }
  void vrespond(RS485_Serial & bus) override {
    bus.write(static_cast<decltype(val)>(random(2,5)));
  }
};

void listen(RS485_Serial & bus) {
  byte * data = nullptr;
  byte length = 0;
  if ( bus.read(data, length) ){
    Action & a = *(reinterpret_cast<Action*>(data));
    if (a.size() == length) blink(3);
    if (a.target_address == bus.address) {
      a.respond(bus);
      //static_cast<Random*>(&a)->vrespond(); works but it has no point
    }
  }
}

My doubt is that if the vtable is stored in different positions, than the vtable pointer in the object obtained by the receiver will be off, causing the crash.

Please edit your question to include complete, minimal sketches that demonstrate the issue.

@LookAlterno could this be moved to stackexchange?

You are accessing a Null pointer and getting a segmentation fault.  Suggest you test you code under Visual Studio or Linux equivalent and see where the debugger flags the fault.

@LookAlterno - I agree and disagree, because there is some element of hardware (serial) that could be causing the issues, most likely because the data is being sent as binary and read as text or similar.

I think you're going to have to show your code for both sender and receiver for us to have any clue what is or might be going on.

Action::vrespond is PV and can't be called. Only Random::vrespond can be called.

@Majenko it is supposed to be like that: the call should be resolved to Random::vrespond. If it was like you said it shouldn't even compile.

How can it be resolved to Random::vrespond if it's cast to Action?

If you have super-class A that is the parent of both classes X and Y, and foo is a PV interface in A and implemented in both X and Y, and you cast an object to A, how does it know where foo is implemented? It could be in either X or Y. It can't know that kind of thing. You have to cast it to the right class to access the functions in that class.

@Majenko The point of polymorphic pointers is to avoid that cast by means of virtual functions. See: http://coliru.stacked-crooked.com/a/a5ffb8ecab28708a

@Majenko The compiler creates some machinery for that to work (vpointer and vtable) which I suspect is not created on the receiver or at least it doesn't match with the sender. I may have to write them myself to ensure that they match on both sides.

I do not agree that this question would suit StackOverflow better, this is quite Arduino specific for multitude of reasons for ex. Harvard architecture and serial implementation, just to name a few.

I suspect then that the object contains a pointer to the code for vrespond, which is at a specific (and differing from program to program) location in flash memory. An object in C++ isn't a single atomic item, it is a collection of data and pointers to functions. On a Harvard architecture system the data is in RAM and the code is in Flash (you cannot typically execute code from RAM). The compiler chooses where to place the code in Flash when it compiles (well, the linker does). That won't be the same address in different programs. All you are doing is sending over the addresses in flash that the code resides at - and those addresses are incorrect. By specifically casting it to a type that has code available you are also telling it where that code resides. Without that manual cast you are having to rely on the (incorrect) function pointers.
It is a bad idea to transfer objects like that from one system to another. It is better to transfer just the data and feed that data into an existing object created on the receiver. How you send and receive that data and feed it into the object is up to you.


text:
Instantiating bounce library inside a class
I am trying to get my head around how to instantiate objects from existing libaries inside a class object. Specifically I am trying to get the bounce2.h debouncer working.
At the moment my code compiles but i think the debounce function is not working as the button is filling my array with lots of random numbers (even from setup) whereas it works fine on a non-class based sketch, so I think that I am probably not instantiating the bounce object correctly. If anyone can help I would be very grateful!
My header:
#ifndef CandleRack_h
#define CandleRack_h

class CandleRack
{
  public:

    CandleRack(byte candleRackStatus);
    void begin();
    void pushButton();
    void selectRandomCandle();
    void turnOnCandle(byte candlePosition);
    void burnCandlesForMs();
    void fadeOutCandle(byte candlePosition);

  private:
    Bounce _debouncePushButton;
    byte _pushButtonPin;
    byte _candleRackStatus;
    byte _candlePosition;
    byte _candleStatus[];
    elapsedMillis _candleTimeElapsed;
    unsigned int _candleOnForMs;
};
#endif

My cpp
#include "Arduino.h"
#include <FastLED.h>
#include <elapsedMillis.h>
#include <Bounce2.h>
#include "CandleRack.h"

#define NUM_LEDS 50

CandleRack::CandleRack(byte candleRackStatus)
{
  _candleRackStatus = candleRackStatus;
}

void CandleRack::begin()
{
  randomSeed(analogRead(0));

  _debouncePushButton = Bounce();
  _pushButtonPin = 3;
  _candleOnForMs = 20000;
  pinMode(_pushButtonPin, INPUT_PULLUP);
  _debouncePushButton.attach(_pushButtonPin);
  _debouncePushButton.interval(10);

  for (byte b = 0; b < NUM_LEDS; b++)
  {
    _candleStatus[_candlePosition] = 0;
  }

  Serial.println("Candle Array: ");       // Debug ************************
  for (byte b = 0; b < NUM_LEDS; b++)     // Debug ************************
  {                                       // Debug ************************
    Serial.print(_candleStatus[b]);       // Debug ************************
    Serial.print(", ");                   // Debug ************************
  }                                       // Debug ************************
  Serial.println("");                     // Debug ************************
  Serial.println("Begin Complete");       // Debug ************************
}

void CandleRack::pushButton()
{
  // Look for a button push
  if (_debouncePushButton.update())
  {
    if (_debouncePushButton.fell())
    {
      selectRandomCandle();
    }
  }
}

void CandleRack::selectRandomCandle()
{
  byte randomCandlePosition;
  do
  {
    randomCandlePosition = random(0, NUM_LEDS);
  }
  while (_candleStatus[randomCandlePosition] != 0);

  turnOnCandle(randomCandlePosition);
}

void CandleRack::turnOnCandle(byte _candlePosition)
{
  // leds[_candlePosition] = CRGB::Red;
  _candleStatus[_candlePosition] = 1;

  Serial.println("Button Pushed: ");      // Debug ************************
  Serial.println(_candlePosition);        // Debug ************************
  Serial.println("Candle Array: ");       // Debug ************************
  for (byte b = 0; b < NUM_LEDS; b++)     // Debug ************************
  {                                       // Debug ************************
    Serial.print(_candleStatus[b]);       // Debug ************************
    Serial.print(", ");                   // Debug ************************
  }                                       // Debug ************************
  Serial.println("");                     // Debug ************************
}

void CandleRack::burnCandlesForMs()
{
  // See if it is time to turn the candle off
  for (byte b = 0; b < NUM_LEDS; b++)
  {
    if (_candleTimeElapsed > _candleOnForMs && _candleStatus[b] == 1)
    {
      CandleRack::fadeOutCandle(b);
      _candleTimeElapsed = 0;
    }
  }
}

void CandleRack::fadeOutCandle(byte _candlePosition)
{
  _candleStatus[_candlePosition] = 0;
}

My sketch:
#include "Arduino.h"
#include <FastLED.h>
#include <elapsedMillis.h>
#include <Bounce2.h>
#include "CandleRack.h"

CandleRack MyCandleRack(0);

void setup() {
  delay(3000); // sanity delay

  Serial.begin(9600);
  while (!Serial);

  Serial.println("Setup Starts");  // Debug ************************

  MyCandleRack.begin();

  Serial.println("Setup Complate");  // Debug ************************
}

void loop() {

  MyCandleRack.pushButton();
 // MyCandleRack.burnCandlesForMs();

  FastLED.show();
}

edit - added the code from the original debounce example for a single sketch
// Detect the falling edge

// Include the Bounce2 library found here :
// https://github.com/thomasfredericks/Bounce-Arduino-Wiring
#include <Bounce2.h>

#define BUTTON_PIN 2
#define LED_PIN 13

int ledState = LOW;

// Instantiate a Bounce object :
Bounce debouncer = Bounce();

void setup() {

  // Setup the button with an internal pull-up :
  pinMode(BUTTON_PIN,INPUT_PULLUP);

  // After setting up the button, setup the Bounce instance :
  debouncer.attach(BUTTON_PIN);
  debouncer.interval(500);

  // Setup the LED :
  pinMode(LED_PIN,OUTPUT);
  digitalWrite(LED_PIN,ledState);

}

void loop() {

  // Update the Bounce instance :
   debouncer.update();

   // Call code if Bounce fell (transition from HIGH to LOW) :
   if ( debouncer.fell() ) {

     // Toggle LED state :
     ledState = !ledState;
     digitalWrite(LED_PIN,ledState);

   }
}

Your main issue (the cause of your symptoms) is the fact that you have no size for your _candleStatus array.  Without specifying a size you end up with no memory allocated to the array, and hence no valid content.
In your class definition the line:
byte _candleStatus[];

should be modified to:
byte _candleStatus[NUM_LEDS];

and NUM_LEDS should be defined in the header, not in the CPP file. (By specifying it in the header file, since the header file is included in the CPP file, the definition ends up in both files).
Aside from that this line doesn't do what you think it does:
_debouncePushButton = Bounce();

You are copying the content of an anonymous bounce object created just for the occasion into a pre-existing Bounce object.  You don't want that line to exist since the Bounce object has already been instantiated by the construction of your CandleRack object.
However there is something you need to be aware of known as the Static Initialization Order Fiasco which can bite you on the rear end if you are not aware of it.  This is basically when you use objects in other objects and those objects haven't yet been properly created since you cannot predict the order in which objects are initialized. This may or may not be an issue in your system - it all depends on how the other classes you use behave.
One way around the issue, if you find it does become a problem (or if you just want to avoid the problem altogether) is to use pointers and what is known as Construct On First Use.  This is where you don't instantiate any objects in your constructor or the class definition - instead you just have pointers to them and use the new keyword to construct the object from within a member function (such as begin()).
For this you change your class definition object entries to be pointers, such as:
Bounce *_debouncePushButton = NULL;

(Note that not all versions of the compiler will support that assignment in the class definition. It's a modern addition to C++ and depending on your version of the Arduino software may or may not work. If it doesn't you can move the assignment into the constructor by removing the = NULL from the definition and adding _debouncePushButton = NULL; into the constructor.)
Then construct a new object in the begin() function (if it hasn't already been created):
if (_debouncePushButton == NULL) {
    _debouncePushButton = new Bounce();
}

Now you have to access the _debouncePushButton as a pointer to an object not an object, so change all your accesses to use the pointer dereference operator ->:
_debouncePushButton->attach(_pushButtonPin);
... etc ...

In case the class should ever go out of scope or be used in a dynamic way you really should create a destructor to delete any objects that have been created:
CandleRack::~CandleRack() {
    if (_debouncePushButton != NULL) {
        delete _debouncePushButton;
    }
}

Note that you should only ever try and delete objects that have actually been created - hence the test to see if it's not null.
Excessive use of new and delete though is discouraged, so it is best to use objects in a static context if possible. Too much new and delete or malloc and free can cause heap fragmentation which can lead to you running out of memory and all the associated stability problems that come with it.
Of course, all this is optional and chances are it won't be needed if the other classes behave well.

Thanks. It is still giving me the same issue though, it is adding lots of random numbers to the array. I can post the code for using the debounce object in a single sketch if it helps?

See my edit. You have a second completely unrelated problem with your code.

Agh, OK. one issue is that #define NUM_LEDS comes from my FastLED array and I need that in the main sketch I think. I'm not sure how to reference/point to a #define though (which it needs to be).

If it is in CandleRack.h then it is also in CandleRack.cpp since CandleRack.h is included in CandleRack.cpp.

Great. Just tried it and it's sorted the problem! Huge thanks :) Now for the tricky bit which is using FastLED in the object :)

one question... I had read that it wasn't good to use new in arduino sketches. Is this old adivce?

I've been reading up on new and should i be using delete somewhere as well as per http://arduino.land/FAQ/content/4/24/en/mixing-malloc-and-new.html ?

Only if you ever delete the CandleRack object, and since you statically create that it never gets deleted.  You can make a destructor for CandleRack if you really want and delete the Bounce object (if it has been created) but if you are always going to statically create it there's not really any need.

And it's not the use of new that is bad - it's the repeated new and delete that causes heap fragmentation - and when you only have a tiny heap fragmentation is very very bad. Using new in a static way (never using delete and never wanting to use delete) never causes heap fragmentation.

Should I also be using pointers for my other library object - elapsedMillis? it works fine at the moment but thinking about your last advice, there might be an advantage in using a pointer there as well?

You can do, yes. It is possible to do the whole thing statically and not use new at all - just revert back to how it was and remove the line that assigns a Bounce object in the begin function - however there is risk of static initialization order problems then if you don't know what the constructors of the other objects are doing. By using pointers for your objects you are getting what is called "construct on first use" from them which means that they will always be constructed after the system has completely initialized.

Makes sense - I understand now that error I was having from the beginning of the thread was with the randomNumber array issue - the rest is more 'best practice'. So all I need to do is change (in the header) elapsedMillis _candleTimeElapsed[NUM_LEDS]; to elapsedMillis *_candleTimeElapsed[NUM_LEDS];? as I can't use the -> notation in this case as now I look more closely it doesn't actually instantiate an elapsedMillis object to reference in this case. Is that right?

Personally I'd fix this answer, since it is misleading. You should definitely remove the pointer (and new) part, since it is not related to the actual problem. If, on the other way, you want to keep it, change the words around (it is not a mandatory thing to do, it's just something you suggest) but, then, you will need to 1) initialize the pointer to NULL 2) check if the pointer is null (protect against multiple begin calls, or there will be memory leaks) before making a new 3) explicitely delete it (otherwise there are memory leaks if the object is used in a reduced scope)

@frarugi87 yes, I wrote it just before bed. It's not a wonderful answer.

Thanks for the updated answer, it makes a huge difference to my understanding. Especially as I assumed before that using new would be the preferred way to instantiate an object.

@Majenko now THIS is a good answer.. +1


text:
Using #define and multiple classes
I am using the FastLED library in my program and the basic usage is that the following lines go at the top of the main sketch:
#include <FastLED.h>
#define NUM_LEDS 60
#define DATA_PIN 6

You can see the documentation at https://github.com/FastLED/FastLED/wiki/Basic-usage
However, I am using the FastLED library in several different objects in my program and I would like to be able to reference NUM_LEDS in different header files for each object so that the number of LEDS can be controlled just by changing the value in the main sketch.
I am also intending that my own objects can be made into libraries for others to use, so they will then define the settings in their main sketch, that my libraries will then use.

Sure.. Create a header file containing those three lines (call it, for instance, FastLedInclude.h) and then, in each file you need the FastLed library, write #include "FastLedInclude.h" instead of #include <FastLed.h>

This won't work as someone using my library in their own fastLED sketch won't then be able to define their own size of project from the main sketch. I'll alter my question to make sure that is understood.

You will need to have NUM_LEDS defined in every file you compile; that's why you need it in a header file to be included by every cpp or ino file. Now, if you want to make a library, that file should either be in 1) the library folder, or 2) the sketch folder. The second approach is, IMHO, very bad, since it requires the user to create the file in its sketch folder and requires the library to know where the sketch is, which is against the definition of "library", i.e. a piece of code that can work by itself. My personal advice is to ask the user to modify the library file or, if you don't want

to force/allow him to modify your files, edit the code using dynamic allocation instead of compile-time static allocation. I mean, instead of defining DATA_PIN you can store a uint8_t variable in your class containing the data pin. You can do the same with NUM_LEDS, and then allocate the matrix dynamically (with mallocs or news) in the code. It can have lower performances, but it will work better

That's very helpful. I wonder if I could I ask the user to add const byte numberOfLeds = NUM_LEDS to their sketch and then use numberOfLeds in my library rather than NUM_LEDS ?

and then add a pointer to const byte numberOfLeds in my library header?

Well, your library will contain at least one class, won't it? Consequently you can store the variable in your class, then either make it public (bad) or private (better) and set it in the constructor. So the user will have to allocate your object dynamically yourclass *obj = new yourclass(60); (or, if he defined #define NUM_LEDS 60, he can write yourclass *obj = new yourclass(NUM_LEDS );) or statically yourclass obj(60); (or yourclass obj(NUM_LEDS );). In either case you will have the value stored in your object

This is very helpful, many thanks. I tried to implement the #include "FastLedInclude.h" version that you first suggested and I realised that I didn't give all of the information in the question. The FastLED setup also needs me to add struct CRGB leds[NUM_LEDS]; into pages where the code is used. If I include that in FastLedInclude.h then I get a compile error multiple definition of 'leds'

I have tried using struct CRGB leds[NUM_LEDS]; in the main sketch and extern CRGB *leds; in my cpp files and it compiles but the program does not work

Of course you can't DEFINE a variable in a header, otherwise you can happen to define it more than once. You definitely can DECLARE it, and you should declare it extern, then define it in only one cpp or ino file. The usual way is to 1) write extern struct CRGB leds[]; in the FastLedInclude.h file. 2) choose a ino or cpp file (probably the main ino file is not the most indicated, but should work) and write struct CRGB leds[NUM_LEDS];. If this does not work, post your code and I'll try to have a look at it

This works perfectly! Thank you so much for your assistance, feel free to contribute this as an 'answer'

I added the answer with some more examples..

As the OP suggested, I'm posting a summing up of the comments under his question since the answer was found.
In order to make a common define for those parameters in different source files, the easiest solution is to make a shared header. To do this, just create a new file called FastLedInclude.h and, inside of that, write
#include <FastLED.h>
#define NUM_LEDS 60
#define DATA_PIN 6

Then in every source file you will just have to #include "FastLedInclude.h" to be able to use that library.
The FastLED library also requires the programmer to create a struct. Now, placing the definition of the struct (i.e. struct CRGB leds[NUM_LEDS];) into the header file leads to compilation errors, since the compiler writes the code to allocate it once for every object file.
The correct way to share this among different object files is to declare it extern in the header, then define it just once in one of the cpp or ino files:
// into FastLedInclude.h
extern struct CRGB leds[];

// into any cpp or ino file (but just once)
struct CRGB leds[NUM_LEDS];

This can also be done in the main ino sketch file, but personally I prefer to define it into another one (it depends, however, on how you choose to divide the program).
If you want to create a library, some other problems arise. The easiest solution is to ask the user to manually modify the header file which will be in the library folder. This solution is a bit uncomfortable, but it is the safest one.
Another solution is to force the user to create a header file into the sketch folder. Then the library should know the sketch folder path to back-include it. But.. This is a very discouraged option, since it will require the library to know the sketch location, thus violating the consistency principle at the base of a library-based approach.
The third solution is to modify the approach, from a compile-time static definition to a dynamic one. In order to do this, instead of defining NUM_LEDS and DATA_PIN at compile time you save them as variables in the library class.
For instance, in your library class definition you have
class yourclass
{
    public:
        yourclass(uint8_t data_pin, uint8_t num_leds);
        ~yourclass();
    private:
        uint8_t _data_pin;
        uint8_t _num_leds;
        struct CRGB *leds = NULL;
};

And the implementation can be
yourclass::yourclass(uint8_t data_pin, uint8_t num_leds)
{
    _data_pin = data_pin;
    _num_leds = num_leds;

    // Dynamic allocation of the array
    leds = (struct CRGB *) malloc(num_leds * sizeof(struct CRGB));
}

yourclass::~yourclass()
{
    // you should free the leds array when done
    free(leds);
}

Then the user can write
yourclass *obj = new yourclass(6, 60);

// or, if he wants to define,
#define NUM_LEDS 60
#define DATA_PIN 6
...
yourclass *obj = new yourclass(DATA_PIN, NUM_LEDS);

or, in the case of a statically allocated object,
yourclass obj(6, 60);

// or, if he wants to define,
#define NUM_LEDS 60
#define DATA_PIN 6
...
yourclass obj(DATA_PIN, NUM_LEDS);


text:
add 0x to a byte
I have a byte variable CardNumberByte with a value of E8 if i print out as HEX:
Serial.println(CardNumberByte, HEX)

which returns E8.
What I would like to do is to "append 0x as prefix" so that it is equivalent to
Char CardNumberByte=0xE8;

how should i concatenate 0x to CardNumberByte?
here is the reason i need to do so.
Thanks

Did you try just printing it first?

no, i need a char variable with the value of 0x28, not just 28 printed out using HEX format in the example. 0x28 will be an address for the sensor

That's a completely different question from what you're asking.

Please edit your question to reflect what you actually need help with.

"How do I convert a string with two hexadecimal digits to a byte?"

I think there is a serious basic misunderstanding of very elementary C (and even basic programming and even "what a computer is") concepts here. You need to go right back to basics and learn how to count (metaphorically) before you start tacking calculus.

The whole idea of "add a prefix to a byte variable and store it in the byte variable" is completely meaningless.

I've looked at you question and the question you linked two and I've tried to join the dots to give you an answer, so I might be well off the mark, but...
I think you might have misunderstood what 0x28 means.
0x?? means that the ?? represent a hexadecimal number rather than a decimal number.
So 10 (Ten) in decimal is the same as 0x0A in hex or B00001010 or in binary or even 012 in octal.  (See https://www.arduino.cc/en/Reference/IntegerConstants for more details)
So you want to have some code that says:
char Address = 0x28;

This is assigning the hexadecimal value 28 to the variable Address.  You could also write:
char Address = 40;

In this case you are assigning the value decimal 40 (which is hex 28) to the variable.  If you want to write strange code that is misleading you could write:
char Address = '(';  // ( is ASCII character 0x28 or 40 - Don't do it like this!

One other important thing here is that the char type in this case is not being used as type that holds a printable character, its being used as a signed 8 bit number.

The answer to the question you asked is:
Serial.print("0x");
Serial.println(CardNumberByte, HEX);

But what you want to do according to the comment you posted is parse "E8" to give you 0xE8.
int parseHex(char* input){
    int result = 0;
    while(input && *input){
        if(*input >= '0' && *input <= '9'){
            result <<= 4;
            result+= *input - '0';
        }
        if(*input >= 'a' && *input <= 'f'){
            result <<= 4;
            result+= *input - 'a'+10;
        }
        if(*input >= 'A' && *input <= 'F'){
            result <<= 4;
            result+= *input - 'A'+10;
        }
        input++;
    }
    return result;
}

You forgot to advance input and check if it's \0 before shifting.

Why are you using: input <<= 4; on pointer?

@KIIV because I was far too hasty...

I think you should use: result = result<<4 + ... or at least move that bitshift before the result += ....


text:
How to make Arduino to stop updating i2c data when meet a condition and wait until it receives another serial input from processing?
I am currently making a robot with Arduino Uno, D6T omron thermal sensor (i2c sensor) and some other sensors. My thermal sensor will always update the data in array form. It will display 4 data arrays every 1 second.
I wish to have my Arduino send out a string "found" over serial when it meet a condition, and thermal sensor will stop updating my data. Thermal sensor and Arduino will just have to wait until the user sends a selection, jump to the selected function, and thermal sensor will start updating data again after that. I am new to coding, any suggestion on how to make my arduino and sensor to wait? Thank you guys! =)
Attached below is my code. (Arduino Sketch):
#include <Wire.h>
#include <WireExt.h>

#define D6T_addr 0x0A
#define D6T_cmd 0x4C

int rbuf[35];
float tdata[16];
float t_PTAT;

const int S_DATATRANSFER = 0;
const int S_WAIT = 1;
const int S_STOPTRANSFER = 2;
const int S_CONFIRMATION = 3;
const int S_ALLSTOP = 4;

float left_sum, right_sum, center_sum;

//-----------------------------------------------------------------------------

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  Serial.flush();

}

void loop()
{

static int state = S_DATATRANSFER;

    switch(state)
    {

    case S_DATATRANSFER:
        //Calculate temp
        //serialprint temp
        int i;

        if (Serial.available() > 0)
        {
                      char inByte = Serial.read();
                      if (inByte == '1')
            {  //processing will send one byte to arduino if ready

                Wire.beginTransmission(D6T_addr);
                Wire.write(D6T_cmd);
                Wire.endTransmission();

            if (WireExt.beginReception(D6T_addr) >= 0)
                {
                    i = 0;
                    for (i = 0; i < 35; i++)
                    {
                        rbuf[i] = WireExt.get_byte();
                    }
                    WireExt.endReception();

                    t_PTAT = (rbuf[0]+(rbuf[1]<<8))*0.1;
                    for (i = 0; i < 16; i++)
                    {
                        tdata[i]=(rbuf[(i*2+2)]+(rbuf[(i*2+3)]<<8))*0.1;
                    }
                }

                right_sum= tdata[0]+ tdata[4] + tdata[8] + tdata[12];
                left_sum= tdata[3] + tdata[7] + tdata[11] + tdata[15];
                center_sum= tdata[5] + tdata[6] + tdata[9] + tdata[10];
                output_csv();

               }
                      }
        state = S_WAIT;
        break;

    case S_WAIT:
        if (center_sum > 35*4)
        {
        state = S_STOPTRANSFER;
        }
        else
        {
        state = S_DATATRANSFER;
        }
        break;

    case S_STOPTRANSFER:

        Serial.println("F");
                delay(300);

        state = S_CONFIRMATION;

        break;

    case S_CONFIRMATION:
        while (Serial.available())
        {
         char val = Serial.read();
            if (val == '2')
            {
                state = S_ALLSTOP;
            }
            else if (val == '3')
            {
                state = S_DATATRANSFER;
                }
                        else if (val == '1')
                        {
                                state = S_DATATRANSFER;
                        }
                }

        break;

        case S_ALLSTOP:

        break;

    }
}

void output_csv()
{
  for (int i = 0; i < 16; i++)
  {
    Serial.print(tdata[i]);
    if (i < 15)
    {
      Serial.print(",");
    }
    else
    {
      Serial.println();
    }
  }
}

Attached below is my code in processing:
import processing.serial.*;
import controlP5.*;
import javax.swing.JOptionPane.*;
import com.onlylemi.processing.android.capture.*;
ControlP5 cp5;
javax.swing.JOptionPane JOptionPane;

AndroidCamera ac;
PImage img;
Textlabel myTextlabelA, myTextlabelB;
boolean canStart = true;
boolean canInput = false;
boolean Start = false;
boolean Start_camera = false;
String typedText = "Comments: ";
PFont font;
String command = "";
String confirm;
String found;

PImage carImage;
float[] tdata = new float[17];
float tptat; // PTAT
String portName;
//int serialport = 0;

String buf;
float colourGreen; //change green in relation to temperature

int lbTemp = 25; //lowest relative temperature
int hbTemp = 35; //highest relative temperature
Serial myPort;  // Create object from Serial class

void setup() {
  size(1366,768);
  //background(#FFFFFF);
  background(ControlP5.BLACK);
  //println(Serial.list());
  //portName = Serial.list()[serialport];
  myPort = new Serial(this, "COM15", 9600);
  myPort.clear();
  cp5 = new ControlP5(this);
  ac = new AndroidCamera(720, 480, 30);
  ac.start();

  myTextlabelA = cp5.addTextlabel("label")
                    .setText("GUI of Alive Human Detection System.")
                    .setPosition(120,10)
                    .setColorValue(#FFFAF0)
                    .setFont(createFont("Georgia",20))
                    ;

  cp5.addButton("Start")
     .setPosition(115, 670)
     .setSize(100,30)
     ;

  cp5.addButton("Stop")
     .setPosition(375, 670)
     .setSize(100,30)
     ;
  cp5.addButton("Start Camera")
     .setPosition(799, 670)
     .setSize(100,30)
     ;
}

public void Start(int theValue) {
  println("Initialising...");
  println("Connected.");
  //start displaying
 // carImage = loadImage(".png");
  Start = !Start;
}

public void Stop(int theValue) {
  println("Shuting Down...");
  //finish = loadImage("robot.png");
  //image(finish,30,64);
  myPort.write(0x02);
  Start = !Start;
  //strokeWeight(0);
}

public void Start_camera(int theValue) {
  println("Initialising...");
  println("Connected.");
  //start displaying
 // carImage = loadImage(".png");
  Start_camera = !Start_camera;
}

void draw()
{
  //if (Start_camera){
  //img = ac.getCameraImage();
  //image(img, 610, 0);
  //}
  if (Start){

    myPort.write('1');
    delay(100);
    while (myPort.available() > 0) {
    delay(300);
    buf = myPort.readStringUntil('\n');
    if (buf.equals("F")){
    int dialogResult = JOptionPane.showConfirmDialog (null, "Human found? Please Confirm!!", "Alert!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    if(dialogResult == JOptionPane.YES_OPTION)
    {
    fill(255,0,0);
    rect(100,670,50,30);
    myPort.write('2');
    }
    else if(dialogResult == JOptionPane.NO_OPTION)
    {
    fill(0,255,0);
    rect(100,670,50,30);
    myPort.write('3');
    }
    }
    else{
    myPort.clear();
    tdata = float(split(buf, ','));
    for (int i = 0; i <16; i++) {
    colourGreen = map(tdata[i],lbTemp,hbTemp,255,0);
    fill (255,colourGreen,0);

      if (i == 0)
    { rect(450,64,150,150);}
      else if (i == 1)
    { rect(300,64,150,150);}
      else if (i == 2)
    { rect(150,64,150,150);}
      else if (i == 3)
    { rect(0,64,150,150);}
      else if (i == 4)
    { rect(450,214,150,150);}
      else if (i == 5)
    { rect(300,214,150,150);}
      else if (i == 6)
    { rect(150,214,150,150);}
      else if (i == 7)
    { rect(0,214,150,150);}
      else if (i == 8)
    { rect(450,364,150,150);}
      else if (i == 9)
    { rect(300,364,150,150);}
      else if (i == 10)
    { rect(150,364,150,150);}
      else if (i == 11)
    { rect(0,364,150,150);}
      else if (i == 12)
    { rect(450,514,150,150);}
      else if (i == 13)
    { rect(300,514,150,150);}
      else if (i == 14)
    { rect(150,514,150,150);}
      else if (i == 15)
    { rect(0,514,150,150); }

    if (tdata[i]<5) {fill(255);} else {fill(0);}
      if (i ==0)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),525, 139);}
      else if (i == 1)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),375, 139);
      }
      else if (i == 2)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 225, 139);
      }
      else if (i == 3)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),75, 139);
      }
      else if (i == 4)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 525, 289);
      }
      else if (i == 5)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 375, 289);
      }
      else if (i == 6)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 225, 289);
      }
      else if (i == 7)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 75, 289);
      }
      else if (i == 8)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 525, 439);
      }
      else if (i == 9)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 375, 439);
      }
      else if (i == 10)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 225, 439);
      }
      else if (i == 11)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 75, 439);
      }
      else if (i == 12)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 525, 592);
      }
      else if (i == 13)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 375, 592);
      }
      else if (i == 14)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 225, 592);
      }
      else if (i == 15)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 75, 592);
      }
    }
    delay(350);
  }
    }
    }
}

Implement a state machine first in your code for each state:
1) Sending i2c data.
2) Not sending i2c data.
And identify the conditions necessary to switch states:
1 to 2 when condition meet.
2 to 1 when command received.
Then drop your code into the state machine's code.
Read about state machines here and here.

Thanks a lot for the tips! I shall go and try it out. @st2000

Hi there, I successfully asked my arduino and sensor to wait when it meet the condition by implementing FSM into my code. Thank you very much. However, I faced another problem here whereby my processing doesn't seems to read my string sending from Arduino when condition meet. My GUI in processing freeze when program jump into this state case S_STOPTRANSFER: . Any idea how to solve this? Latest coding is edited in the post. Thanks a lot in advance!

There might a logic problem in your code.  I'm going to leave that up to you to find.  However, I will suggest you approach the problem in parts.  First, determine if you can send a found message to your "GUI".  Do this unconditionally when you start the Arduino.  If that does not work, perhaps your Arduino logic is good but your "GUI" can not understand the message.  If it does work, then, second, start eliminating some of the conditions in the Arduino code which prevents sending the message to the "GUI".  Perhaps the logic of one of the conditions is incorrect.

Thank you very much for all the suggestions given! It's working now! =D i found the mistake in my coding.
I should be using Serial.print to print my string in Arduino instead of Serial.println because Serial.println will return in \r\n instead of \n. Manually adding \n after my text in both Arduino and Processing coding.
In Arduino,
Serial.print("FOUND\n");
In Processing,
buf = myPort.readStringUntil('\n');     if (buf.equals("FOUND\n"))
Program in processing is now able to detect my string from Arduino. Thanks again! =)

Create a flow chart of the entire process you want to happen. Once you proof your flow chart to cover all possible functions, you can create the logic, control, and subroutines that are needed. If you have a good book on Arduino programming, and how I2C works, you will know that the I2c display will hold whatever data you wish until you change it. Also, you probably know that you can chain a whole bunch of I2c devices, no matter if they are displays, or anything else, so each device will hold its own data independent of the others. Any updating is under your control in programming. You might also look into using interrupts for some of your program control. Sensors don't push data, the processor reads the data, and your program is in control of how often and when the data is read, and what it does with the data.  The exception to your program being in control, is when you use interrupts. You should be storing the data so you will always have access to it for program examination and possible decision making. Lastly, to increase the abilities of your system, consider using one master Arduino, and several slave Arduino's. Some of the slaves, depending on what you want them to do, can be very small. Look at the tiny85. Some of the boards with the Tiny85 are the size of a postage stamp. I hope some of these suggestions are helpful to you.


text:
Stepper Motor not Stepping Properly
I have an Arduino Uno connected to the Adafruit Motorshield v2. I have it hooked up to a stepper motor(27BYJ-48). I am trying to make the motor do one complete revolution. However, the number of steps I specify to the stepper motor(200 in the code) doesn't affect the motor steps. For example, the 2200 step in this code, is roughly one rotation and is completely unaffected by change the steps/revolution specified when instantiating the motor. How do I get the motor to do one exact revolution?
Here is the code on the arduino:
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Stepper test!");

  AFMS.begin();  // create with the default frequency 1.6KHz

  myMotor->setSpeed(2000);  // 10 rpm
}

void loop() {
  Serial.println("Single coil steps");
  myMotor->step(2200, FORWARD, DOUBLE);
  myMotor->step(2200, BACKWARD, DOUBLE);
}

Edit:
Wiring:

What happens if you disconnect the red wire?

Also change the 200 at AFMS.getStepper(200, 2); to 64.
The spec sheet says 5.625 degrees per step -> so the motor does 64 steps for 1 revolution.

Nothing changes, motor turns same as before. Changing the the code also did not change anything.

That's the RPM, so with 10 it does 10 a minute, however, it is painfully slow and goes much slower than that. So yes, setting the RPM there does not actually convert to the real RPM.

This motor is a unipolar type, right? Wiring is thus a bit different than a bipolar. The AFMS expects bipolar by default if I remember correctly. In any case, double check their doc for more info on how to connect unipolar/bipolar steppers.

https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/using-stepper-motors says the common terminal of 5-wire unipolar motors should be connected to the GND terminal, which is how it appears from the pics.

What happens, if you raise the baudrate to 115200?

Ok so I'm not familiar with the sheild or API (or motor lol) but going off the spec sheets etc
Leave the red wire disconnected [see 1] and try this code and report back what happens:
  #include <Wire.h>
  #include <Adafruit_MotorShield.h>
  #include "utility/Adafruit_MS_PWMServoDriver.h"

  Adafruit_MotorShield AFMS = Adafruit_MotorShield();
  Adafruit_StepperMotor *myMotor = AFMS.getStepper(64, 2); // 64 steps pr revolution
                                                           // Using M3 and M4 of shield

  void setup()
  {
    AFMS.begin();  // create with the default frequency 1.6KHz
    myMotor->setSpeed(30);  // 30 rpm, so 1 full turn every 2sec
  }

  void loop()
  {
    // 64 steps per motor shaft revolution,
    // 64 revolutions of motor per output shaft revolution
    myMotor->step(4096, FORWARD, DOUBLE);    // Should be 1 rev in one direction
    myMotor->step(4096, BACKWARD, DOUBLE);   // and 1 rev in other direction
  }

[1] : your motor is unipolar (wikipedia on unipolar and bipolar motors), according to its documentation. The red wire is the central tap, and useless in this context.

It goes forward and back incredibly minutely, i had to up the values from 2 just to acknowledge it was working.

Try 128 steps (2 rev's)...how long in seconds for each rev?

It goes ~20 degree back and forth, each 30 degree takes about 2 seconds

Maybe there is some gearing on the motor. It might be called the speed variation ratio in the spec sheet (1/64). Let's assume thats it and so we could say 64 steps multiplied by 64 (allow for the gearing ratio for 1 turn). Can you edit the code to be... step(4096, Forward, Double);? Try that.

edited code above

It does ~2 revolutions but nothing exact.

I also tested 27BYJ-48 stepper motor with instructables source code. It works but I had the same "complete revolution" problem.
They compute on their website that a revolution contains 4096 steps.
As @James said, indeed, there is gearing inside the stepper motor.
The problem is the gearing could be different for the exact same reference !
Everything is described here : 28BYJ-48


text:
Having 3 buttons with only 2 input pins
for the purpose of learning, I'm trying to have a kind of digital/binary input where I'm using 3 buttons but only 2 input pins.
I thought of
01 = Button 1
10 = Button 2
11 = Button 3

My first attempt was like this:

I left the resistors out right now. The problem here is of course, that it doesn't matter what button I press, both LEDs are lighting up.
I used 2 Diodes in my second attempt:

This time, S1 and S2 work as expected, but S3 brings only one LED up.
Now I was wondering how I can wire things up correctly, using as little components as possible and having in mind, that I'm going to use an Arduino instead of the LEDs.
Thank you for any help!

The logic of your second attempt is perfectly correct.
If you put resistors in series with the LEDs you may get more joy out of it. Having two LEDs in parallel without resistors often results in one LED lighting and the other not.

Thank you for the hint with the resistence. Had some 75 ohms laying around and now it's working!


text:
Controlling 4 motors using the Arduino Uno
I've decided to make a quadcopter but since I'm a rookie, i decided against doing it from scratch. I'm planning to order this kit, first understand the dynamics and then try and make a quadcopter on my own using the components in it.
My first question are

Can I control the 4 motors using 2 H-bridges (L293D)?
Are ESC's necessary if I use the PWM pins?

Thanks in advance!

I don't think this is Uno related. I think everything the copter needs is already in the kit.

I want to make a copter on my own, with the Arduino, not with this kit.

Alright, didn't read correctly. I don't know about ECS as I don't know what it is. About the h-bridge, as far as I know you need 1 per motor.

I have used 1 L293D to control 2 motors before @Len

That's because the L293D has four half H-bridges, so 2 H-bridges in total.

So then they should be sufficient?

For 2 motors, 1 L293D is enough. For 4 motors, you need two L293D.

Beware - the L293D isn't a very high current driver. You should first check what voltage and current that kind of motor needs to work properly. (Over an amp per motor - 2 amps per L293 chip - might be too much for it.)

Can I control the 4 motors using 2 H-bridges (L293D)?

Yes. Two per chip.

Are ESC's necessary if I use the PWM pins?

There is one thing you must understand first: there are two kinds of DC motor - Brushed and Brushless.
The Brushed motor is the "normal" kind - you apply power to it and it spins.  These you control with the likes of an L293D and use PWM to control the speed.
Brushless motors are the kind you have in hard drives and the like. They consist of a number of coils that get turned on and off at the right time to pull a magnet around in a circle (to put it crudely). These require special timing and control to get the coils energised at the right time and in the right way. This is what an ESC is for.
Brushless motors are smaller and lighter for the same power than brushed ones. They also have a longer life. Because of this they are generally preferred to brushed motors on quadcopters.
Brushed motors have a very high starting torque, don't require complex control logic and use less energy when not running full speed.
If you use brushless motors, which ideally you should (though I can't tell what kind of motors those are in that kit) then you must either use an ESC or build your own ESC using an Arduino and multiple motor driver circuits. Simplest to use an ESC.
If you don't use brushless motors then an ESC is not what you want to use - just the L293D chips and PWM.

Thank you for the answer. The motors in the kit are coreless motors

I saw that. I don't quite know what that means. It looks like they have 2 wires, which makes me assume they are probably brushed.

To be clear (because I was going to answer "No, you can't"), you need 4 H bridges to control the 4 motors on a quadcopter.  It just so happens each L293D already had 2 H bridges so you only need two L293D chips to get the jobs done.  Right?

That is correct.

A coreless motor is, by the look of things, a brushed motor.

You also need to consider the current needed by your motors (they are DC brushed indeed) and the power/energy you will lose in your driver.
If you use a 3.7V power supply like provided, and the L293D "eats" 1.2V out of it, you lose nearly one third of your energy. See https://electronics.stackexchange.com/questions/108686/what-h-bridge-drivers-are-preferred-for-applications-controlling-a-low-voltage-m for an very interesting review of drivers.
If I can believe that, it looks like DRV883x is the only reasonable choice. It even allows you to use one cell (3.7V) for the logic and 2 cells (7.4V) or more for the motors. But don't do that with the motors you've got, you'd probably burn them.
Unfortunately the other ST or Allegro devices also covered in the article all need more voltage to work.
Regarding the Arduino, a UNO can't be recommended, too heavy, 5V only, power hungry etc. It won't fly. I'd recommend you use a pro mini 3V3 with some LDO power supply such as the TPS73633. Be careful that most LDO regulators (like 1117) have a too high dropout voltage to be used with a 3.7V input, more than 1V.
I'm not affiliated with TI at all, it just happens that when looking for "the right chip for the right job", I keep having to eliminate the others because of data sheet numbers.
On the SW part however, it becomes difficult to find SW for the 328P. Most addicts have moved to 32-bit CPUs. But that's another debate.

I fully agree with the answer of Majenko but I think something is missing in the explanation.
When you say "I want to control a motor" then it is not yet clear what is needed.
There are the following options
1) on/off in one direction (forward).
2) on/off in 2 directions (forward and backwards).
3) on/off in on direction with speed control.
4) on/off in two directions with speed control.
For a brushed dc motor this can be achieved with.
1) a single pole single throw relay (this is similar to a on of switch)
2) a single pole single throw relay and a double pole double throw relays (this is a on off switch and a switch to change the wires to the motor)
3) a mosfet (this is similar to a single pole single throw switch that can go on/off very fast)
4) a H bridge. That is 4 mosfets that are controlled in a certain way.
Now here comes the trick: H bridges often come in 2 half H-bridges. And with a half H-bridge you can control a motor at level 3.
In other words ... with a chip that has 4 half H bridges (an as such 2 H- bridges) you can control 4 brushed DC motors at the level 3 (forward speed controlled) or 2 brushed DC motors at the level 2 (back and forward speed controlled).

I'm planning to use an Adafruit Shield, to control a quadcopter.

This board comes with support to control 4 brushed dc motors in 2 directions. because of the latch chip and a control library you can not control the separate half bridges (easily?).

I'm sorry, but I didn't get get you @jantje

@souvik because of the hardware you selected everything is available for 4 brushed dc motors controlled in 2 directions and with speed. You can not control 8 motors on level 3. But you don't care.


text:
Bluetooth sending values from two joysticks
Is there any good way of sending values from two joysticks from arduino A to arduino B? I tried sending using if statements, so if the Y- or X-axis' value changed then it would send that, but the servo motor on Arduino B went a little bit crazy.
Here's what I've done so far:
//Master Code
void loop()
{
      yVal = analogRead(yAxis);   // read the value of the Right Joystick (value between 0 and 1023)
      yMap = map(yVal, 0, 1023, 0, 255);
      xVal = analogRead(xAxis);     // read the value of the left Joystick (value between 0 and 1023)
      xMap = map(xVal, 0, 1023, 0, 110);

  if(Serial.available() && !(xVal > 505 && xVal < 510)){
      Serial.print('X');
      delay(10);
      Serial.write(xMap);
      }
  if(Serial.available() && !(yVal > 500 && yVal < 520)){
      Serial.print('Y');
      delay(10);
      Serial.write(yMap);

    }
    delay(10);
}

And the Slave code:
//Slave code
void loop(){
  while(Serial.available())
  {
    c = Serial.read();
    delay(5);
    val = Serial.read();
    if(c == 'X'){
        digitalWrite(13, LOW);
        myServo.write(val);
    }else if(c == 'Y'){
        digitalWrite(13, HIGH);
    }
    }

}

Edit: I was thinking that maybe I should do something like a start and stop bit for X and Y?
Edit2: I wrote an if statement in Arduino B because it was reading the value -1, I don't know why, but after the if statement the servo motor hasn't been going crazy and the program works now. I still would like to know if I can do this in a better way. Thanks in advance!

There are a number of possible issues in the code.  1) Can the sender and receiver get out of sync.  That is, can the sender send the "x" character when the receiver is expecting a servo-position-number?  Perhaps you might map to 0 through 254 and reserve the value 255 as a synchronization marker.  Then send "marker", X then Y over and over again.

Arduino A
You can read the values from two joysticks as normal and send it like this. This method ensures of no data loss. Ensure that you read the values and store them in appropriate variables and then send it over serial.
// Setting Sensor pins
const int potPin = A0;
const int pot1Pin = A1;

// Creating variables
uint8_t pot;
uint8_t pot1;

void setup() {
// Declearing the pinModes' for sensors
  pinMode(potPin, INPUT);
  pinMode(pot1Pin, INPUT);
// Begining Serial Communication
  Serial.begin(9600);

}

void loop() {
// reading from the sensors
  pot = map(analogRead(potPin),0 ,1023, 0, 255);
  pot1 = map(analogRead(pot1Pin),0 ,1023, 0, 255);

//Packing the Serial message
  Serial.print("U*"); //A header
  Serial.print("A");  //a token to indicate the message payload
  Serial.print(pot);
  Serial.println("");

  Serial.print("U*"); //A header
  Serial.print("B");  //a token to indicate the message payload
  Serial.print(pot1);
  Serial.println("");

}

Arduino B
After the data are packed and sent over the serial. You need to unpack it with the other Arduino/device
The code will look like this:
String data; //Store each line of Serial communication
String pot1String = "0", pot2String = "0";
float pot1, pot2;
void setup()
{
  //initialize Serial communication
  Serial.begin(9600);
  //read first package
  if (Serial.available() > 0)
  {
    data = Serial.readStringUntil('\n');
  }
  //Disregard the first reading
  data = "0";
}

void loop() {
  //start reading from serial
  if (Serial.available() > 0)
  {
    data = Serial.readStringUntil('\n');
  }
  String payload = "";
  if (data != "0")
  {
    int offset = data.indexOf("U*"); //This is the header (0x552A)
    if (offset >= 0)
    {
      payload = data.substring(offset + 3, data.indexOf('\n'));
      char value = data.charAt (offset + 2);
      switch (value)
      {
        case 'A':
          pot1String = payload;
          break;
        case 'B':
          pot2String = payload;
          break;
      //Add more case as the project grow
      }
    }
  }
  //convert strings to float
  pot1 = pot1String.toFloat();
  pot2 = pot2String.toFloat();

// Continue with the rest of your project

}

Make sure to use the same baud rate in both sketches

Hope this helped. Ask me if you have farther questions

Oh wow, thank you for posting this. I'll see if I can get this to work :)

I've been trying to look on Arduino B's serial monitor to see if the values of pot1 and pot2 change, but they don't. I haven't changed anthing in the code except for the baud rate. The values change the very first time I touch my joysticks, but after that it just prints those values over and over again.

Can you tell me how you read the joystick values? Did you change the baud rate in both sketches? Is your baud rate in serial monitor the same?

Try connecting the Rx, Tx of two Arduino together (Rx, Arduino A => Tx, Arduino B & Tx, Arduino A => Rx, Arduino B)

I connected Rx to Tx and Tx to Rx and I read the joystick values with analogRead. I've set the baud rate of both bluetooth modules to 115200, but so far no luck.

the Serial can be used by one device at any given time. Even when you programming the Arduinos you should disconnect both Rx and Tx so the boot loader won't get confused. I'd try connecting the arduino's Rx and Tx pins directly with no Bluetooth modules just to make sure that the serial connection is initialized fine and then try adding the Bluetooth modules.

Thank you. I used a battery with low current to power my arduino, that is why I never got it to work. I am now using two USB-B cables connected to my computer and it works flawlessly. I can't thank you enough for this code, it really is well-written and easy to understand :)

When using the ADC to control servos I get much better results when I process the ADC values through an exponential smoothing function:

There is less jitter.  However there is more lag.  You can tune the function by changing alpha between 1 (no history, effectively no smoothing at all) to 0 (no new data is averaged in, effectively not changing).  Pick 0.5 to start with.  If there is too much jitter pick smaller numbers until the jitter is reduced and the lag is still tolerable.


text:
ESP8266-01 connected to Arduino Mega - Current output?

I was thinking of powering my arduino with an external 9 V power source, but I am still trying to figure out the best way to get the right amount of current for the Wi-Fi module. Should I use an external power supply for the ESP8266-01 module that can output about 500mA or amplify the output from the arduino pins using a transistor?
If there is an easier way to do this I am all ears. I will be using Arduino Mega, not uno as shown in the picture.
EDIT: Voltage divider will be used on the RX pin and I might go for a logic level converter instead of the voltage regulator

you don't need 500ma supply current for ESP01s. If you use a 1000u cap, it doesn't even spike above 100ma.

Should I use an external power supply for the ESP8266-01 module that can output about 500mA or amplify the output from the arduino pins using a transistor?

Either way you're going to need a power supply that can supply the current. A transistor doesn't magically create more current, it merely allows a small current to control the flow of a larger current.
So you will need an external power source that can provide enough current.

I might go for a logic level converter instead of the voltage regulator.

Incorrect. A logic leven converter cannot provide anywhere near enough current to power a device. It can barely provide enough to light an LED.
You are right to want to ditch the voltage regulator though.
As it stands you have a chain of regulators, each one wasting power. At 500mA that's lots of power.
9V -> [REG] -> 5V -> [REG] -> 3.3V

That's 4V dropped in the first regulator at ~500mA, and 1.7V dropped in the second regulator at ~500mA. Since P=VI, 4×0.5 = 2W, and 1.7×0.5 = 0.85W. Since you are providing 9×0.5 = 4.5W of power from the battery, you have 1-((2+0.85)÷4.5) = 0.366, or 36% efficiency. That's about two thirds of your battery power wasted just in heat.
Instead you want to use a switching voltage regulator. These are far more efficient and convert voltage into current rather than voltage into heat. This means that you draw less current from your battery, meaning you can use a battery with a higher internal resistance.
Ideally you would use two - one to convert the 9V into 5V to power the Arduino, and another to convert the 9V directly into 3.3V to power the ESP8266. That would be the most efficient arrangement.
There are plenty of breadboard friendly modules on eBay that can do that, or other small modules you can wire in to your circuit without a breadboard (I myself sell one on eBay that I designed).