text:
How to measure room light without LEDs interfering?
I'm trying to measure the light in a room with a simple circuit: a phototransistor connected in series with a resistor. An LED strip changes brightness according to the brightness level in the room.
The problem here is that the phototransistor also picks up the light from the LEDs. It is not an option using an IR phototransistor because I also need to measure the light from the room's light bulbs. Also, because of the device's casing, I need the sensor to be surrounded by the LED strip. Finally, I tried turning off the LEDs before measuring does not seem to work, as either the Arduino or the sensor is too slow, to turn off, perform the measurement, and turning back on the LEDs, without a human eye perceiving it.
Is there any standard or well known solution to this problem?
I will appreciate any help you can provide.
Additional Information
The LED strip is the WS2812B.
The phototransistor I'm using operates between 420 nm and 1130 nm, with peak sensitivity around 850 nm.
Furthermore, to specify the functionality I'm trying to achieve: whenever the room is dark, I want the LEDs to be not too bright. If the room is too bright, I want the LEDs to shine brighter as well.

do not measure brightness with LEDs off .... measure the overall brightness of the room and adjust the LEDs to keep it at a set level

Can you add some more information such as the LED strip you're using, and the photodetector?

Put the phototransitor in a tube so you can direct where the light can come from. Point it away from where the leds point. But I think you should look into your failed solution some more. Try playing with the value of the series-resistor. Try it with just a single led instead of a whole strip with mosfet(?), to figure out which is the culprit.

@jsotola, thank you very much. The issue, which I failed to mention, is that I don't want to keep the overall brightness at a certain level. What I wish to do is to have the LEDs to shine bright if the room is very bright, and to lower their brightness if the room is dimmer.

Normally you should be able to switch LEDs off, make a measurement and switch LEDs back on without a noticeable delay. Brightness variation is noticeable below 100Hz, which translates to 10ms period.
What you need is a photodiode with fast response time (under 0,1ms or so, though there are devices responding in nanosecond range). Phototransistors and LDRs are considerably slower.
LEDs response time is in single-digit microseconds even for white LEDs, and RGB LEDs are even faster. Below is a response of typical LEDs to a 200ns pulse:

Regular AnalogRead takes about 0.1ms (and, again there are faster alternatives), so you can easily achieve kHz measurement frequencies where brightness variation is completely unnoticeable.

My favourite answers are always "Have you tried turning it off and back on again"

Thank you. I did some timing tests, and I think the issue here is that the LED strip is relatively slow. To control it I use the FastLED library.

@DAVID You could make a "kill switch" for all LEDs in the strip with a BJT/MOSFET which you'd drive directly from a pin. That should be sufficiently fast.

@DAVID Alternatively, try to shield the phototransistor from direct LED light, maybe you get it working as is, without toggling the LEDs.

What you can try is to use a color sensor. Since you know the color of the LEDs you control, if the color sensor picks up a different color, you know it is because of other light.
Since this is not full proof (ambient color might be exactly as the LED color), you can check color differences (also with a non color sensor). If it differes without you changing the LED, you know there is ambient light (either increasing/decreasing).
It also will help if you put the sensor in a tube which is in a different direction than the LEDs to prevent as much as possible picking up the light from the sensors if possible.
(if you don't have color sensors you can use a normal sensor with some colored plastic above/around it).

Thank you very much, I will try this. However, in the long run I would like to be able to change the LED strip's color, so I guess using a color filter would not help in this situation.

In that case you need an RGB color sensor, or 3 LEDs with a red, green and blue 'filter'.

Ahh, perfect. I didn't think about it. Thank you very much.

Good luck with your project. I also might use something similar myself.


text:
How to improve response time of this sound operated LED?
I have written the following code for lighting an LED on a  clap ( using sound sensor)   that I have connected via a resistance of  330 OHM on pin number 4.
However, when I clap once,  close to the sound sensor,  it does not lights  the LED. But it only lights the LED if  I provide prolong exposure to sound  ( more than 6 seconds) on the sound sensor.
How can I improve this , so that even if I clap once for a seconds duration, the LED glows?
int soundSensor=10;
int LED=4;

void setup()
{
 Serial.begin(9600);
 pinMode(soundSensor,INPUT);
 pinMode(LED,OUTPUT);
}

void loop()
{
  int SensorData=digitalRead(soundSensor);
  if(SensorData==1)
  {

     digitalWrite(LED,HIGH);
  delay(3000);

     Serial.println("LOUD, LOUD");
     delay(1000);
  }
    else
  {

     digitalWrite(LED,LOW);
     Serial.println("SLOW, SLOW");
     delay(1000);
  }
 }

One thing is that your program does a lot of waiting, the loop only runs once every second when there's no sound. Also the delay could be in the sensor itself, make clear what sensor you're using. Ideally you would also include a schematic to show how it is connected.

We need to see the circuitry for your sound sensor as well.

I think the problem is in the times you check the sensor. If you clap exactly when you check it will glow even if clapped for 1 ms, but if it checks in between two claps it doesn't detect it.
So check more often (reduce the delays) and check for so many sound detections within one second.
Or, as JRE below proposes, use an interrupt, this is even better but needs a bit more programming skills. Still interrupts are used a lot in microcontroller programming so it is worthwhile to check into this.

Or use an interrupt.

@JRE Thanks for the good remark, I updated my answer.

Interrupts are useful for making things happen automatically in microcontroller programs, and can help solve timing problems. Good tasks for using an interrupt may include reading a rotary encoder, or monitoring user input (like clapping).
Using the attachInterrupt() function is the way to go here!
https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

Depending on sensor , simple modification with series diode to detect impulse and hold decaying slow with say 0.01uF to  and 10 MOhm to 0V will detect 1st time and stretch pulse ~ 0.01u*10M =0.1s

source: Stack Exchange

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

sort: votes


text:
Analog inputs showing value even there is nothing connected to it
After watching something weird on the serial monitor I wrote a simple code to monitor the analog pin input values. There was nothing connected to the analog pins still they where showing decimal representation of some analog values.
the code is
float ana [] = {A0,A1,A2,A3,A4,A5};
float dec [6];

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

void loop()
{
  for(int i = 0; i<6 ; i++)
  {
    dec[i] = analogRead(ana[i]);
    Serial.println(dec[i]);
    delay(1000);
  }
}

How is this even possible?
this is the output result

You have an array of 6 analog pins, but are reading from 7.

It was a mistake.. i corrected it

read the docs https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/ section "Notes and Warnings"

Your input is floating if nothing is connected.  It is reading whatever random noise it happens to pick up.  That's what it is supposed to do.  For it to read 0 it would need to be connected to ground.  Google "floating input" for more info.

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


text:
I2c device disappear from bus after writing
I am currently experiencing a really odd I2C problem on a Atmega32u4 based card. I'm trying to use a TLV493D connected by I2C. I know from this thread that before using this device, I have to set the powermode :
Wire.beginTransmission(HallAddressWrite);       // Address the sensor
Wire.write(configReg);              // Address the Configuration register
Wire.write(powerMode);              // Set the Power Mode to Low
errorCode = Wire.endTransmission();             // Stop transmitting

But each time I'm trying to write on the TLV493D register, the device simply disappear from I2C bus ! I know it sounds strange, but I can demonstrate it with a modified version of default I2C scanner
if (error == 0)
{
  Serial.print("I2C device found at address 0x");
  if (address<16)
    Serial.print("0");
  Serial.print(address,HEX);
  Serial.println("  !");

  Serial.println("Beginning write test...");
  Wire.beginTransmission(address);
  // no register writing
  errorCode = Wire.endTransmission();
  Serial.print("Test ended with code : ");
  Serial.println(errorCode);

  Serial.println("SECOND Beginning write test...");

  Wire.beginTransmission(address);       // Address the sensor
  Wire.write(0x00);              // Address the Configuration register
  Wire.write(0x05);            // Set the Power Mode to Low
  errorCode = Wire.endTransmission();
  Serial.print("Test ended with code : ");
  Serial.println(errorCode);

  nDevices++;
}

which gives the output:
I2C device found at address 0x5E  !
Beginning write test...
Test ended with code : 0
SECOND Beginning write test...
Test ended with code : 0

And next scan doesn't find anything. As you can see, I don't lost my device when I don't write anything. But it disappears from my bus as soon as I write something (here, it's for setting low power mode, but any value will do the same).
More informations :

My code is correct. I know that because I don't have any problem when using an Arduino Uno or Arduino Mega. Unfortunately, I don't have an Arduino Leonardo to see if my problem comes from Atmega32u4.
My wiring is correct. I checked the signal on SDA and SCL pin on the TLV493D with an oscilloscope and everything is as expected : 3.3V and 100kHz.
I also have a SRF02 on my I2c bus : it is working as expected.
I don't think my TLV493D is damaged. In deed, I thought it was because of that. So I changed it for another one but the problem is still here.
I noticed than when beginning an I2C transmission at address 0x00, I am able to see my TLV493D again. But it is pointless since I have to set power mode again and thus, it disappears from bus once again.

Have you checked, that the supply voltage doesn't fall too low, when writing to the TLV via I2C? During reading the datasheet I thought, this maybe would show the seen behavior by resetting it everytime, you write to it.

Hi chrisl, thank you for replying. That actually was a good point, but unfortunately, supply voltage stay constant at 3.3V.

To sum up this problem :
TLV493D configuration work by writing two bytes with I2C. You must begin by writing 0x00, which will be ignored since the first register is reserved. Then, you write a second byte that will actually do the configuration (second register).
The three smalest bits enable or disable INT, FAST and LOW mode.
I still don't understand why I am not able to enable INT mode on my Atmega32u4 while it doesn't seem to be a problem on Uno or Mega (on LOW mode). Anyway, two configurations work for me :
0x07 --> INT, FAST and LOW are all enabled
0x01 --> only LOW is enabled
I don't think it's a issue to disable INT. If I understood correctly, it will make the device send an interrupt pulse to request microcontroller reading. If you manage readings by yourself, I don't think you need INT to be enabled.
Many thanks to CodeGorilla for his support.
UPDATE:
I managed to get an Arduino Leonardo. Indeed, all my obsevations on my Atmega32u4 based card are still corrects (writing 0x05 second register make the device disappear from bus, but not with 0x01 or 0x07). But again, it works normally on Uno or Mega... Really odd ! If anyone has an explanation to offer, it would be greatly appreciated.

By default the FAST register is set to 0 at power up.
When the FAST mode is 0 and you set LOW to 0 you are entering Power Down mode.
Looking at your code it looks like you are not altering the FAST register which means I can simplify your question to "Why does my device disappear from the I2C bus every time I turn it off".
Just looking at page 34 of the English User Manual I would say you have to set FAST to 1 before setting LOW to 0.
Also - Do you have pull-up resistors on the I2C bus?  You might encounter problems without them.  They are normally around 4.7K for 5V, but I don't know what they should be for 3.3v systems.

Thanks for your answer. I am not quite sure I understand though. At which point of my code am I setting LOW to 0 ?
I do have a pull-up resistors on my I2C bus.
And finally, what I really don't understand is why I have to do all that, knowing that my code is working just fine on Uno and Mega ? I mean, what is the Atmega32u4 difference ?

@erenaud , that is the wrong kind of question. You should do everything right, and then solve any remaining problems. Is your atmega32u4 running at 3.3V? Then you don't need a level shifter. Use pullup resistors. Follow the datasheet.

@Jot As I said, I am using pullup resistors.

Sorry I missed the fact that it was "working" on a Uno and Mega.  When using it with a Uno/Mega do you use a 5V or 3.3V I2C bus?  According to the code you have included above and the datasheet you link to you are writing to Write Register 0 with the value 5.  Register 0 is reserved and must not be written to or have I misread the data sheet?

@CodeGorilla I am using 3.3V bus. Indeed, I thought I was writing to register 0 with value 5, but I got mislead by the comment on the code snippet I found on the arduino forum's thread I linked. Actually, I am doing exaclty as the example in page 13 of the user manual. The first writing (0x00) is for the first reserved register. Then, I write (0x05)) to the second register, which set FAST to 0, INT to 1 and LOW to 1.

@CodeGorilla I noticed something interesting: when writing 0x07 to the second register (so FAST, INT and LOW are all set to 1), I don't loose my communication with the device. But of course, my readings are totally wrong since the code I currently used  doesn't support FAST mode.

@erenaud - Could it be that enabling INT ("not recommended for I2C") and disabling Fast are causing the problem, have you tried a value of 0x01? for the second reg?

@CodeGorilla Indeed, it is working as well and I think you are absolutely right, INT shoudln't be put enabled. Thank you for your help !


text:
Print with round towards zero instead of round to nearest
When printing with one decimal place, Arduino's Serial.println() rounds numbers like 123.89 to “123.9”. Is there any way to change the rounding mode? For some reasons I want the value to be rounded towards zero (i.e., truncated) to one decimal place, like 123.89 → “123.8”.
here is the code
void setup() {
Serial.begin(9600);

}

void loop()
{
float A = analogRead(A0);
A = (A/1023)*5.0;
Serial.print("A = ");
Serial.println(A,3);
float B = A*10;
Serial.print("A * 10 = ");
Serial.println(B,1);
delay(1000);
}

the output is
A = 2.473
A * 10 = 24.7
A = 2.488
A * 10 = 24.9
A = 2.517
A * 10 = 25.2
A = 2.527
A * 10 = 25.3
A = 2.507
A * 10 = 25.1

instead I want the output to be like this
A = 2.473
A * 10 = 24.7
A = 2.488
A * 10 = 24.8
A = 2.517
A * 10 = 25.1
A = 2.527
A * 10 = 25.2
A = 2.507
A * 10 = 25.0

is it possible ?

We can't tell you what you're doing wrong if we don't know what you're doing.

This is not the serial monitor.  It is the serial output statements in your sketch, or more likely the floating point format itself.  You might perhaps consider using a double instead of a float.  But it's also unclear that the value being printed is not already the most accurate decimal approximation of the value internally stored.   Without your code this is unanswerable.

I have written it I was monitoring some analog values and printing it on the serial monitor for example let the values be like 2.59 and when I was printing it upto one decimal place it was getting rounded to 2.6 for some reasons I need the value to be like 2.5

Analog values in Arduino (and just about all MCUs) are integers, so you have done something to turn them into floating point values and something else to print them.   You must show your code by editing it into the body of your question.  If you do not, the question will probably be closed and deleted from the site.  (Additionally, analog values are expected to show noise variation)

check it @ChrisStratton

@IgnacioVazquez-Abrams

So you want the output to be truncated instead of rounded? 2.59 as 2.5 instead of 2.6?

yes truncated @Craig

What you are describing is by no means a value that is "exact up to one decimal place"   Your major problem here is that you've failed to really articulate that you want a value that is intentionally inexact.  Do you have any actual justification for distorting your data like this???

Note that most decimal numbers are not exactly representable as floats. For example, if you type float x = 23.40;, the compiler rounds that number to the nearest representable float, which happens to have the exact value 23.3999996185302734375. If you truncate this to one decimal place, then 23.40 ends up being printed as “23.3”!

A cheap trick to round a number to one decimal place (in "chop-off mode") is to multiply it by 10, convert it to an integer, and divide by 10.0f again:
float myVal = 123.89f;
myVal = (long)(myVal * 10) / 10.0f;
// = ((long)1238.9) / 10.0f
// = 1238 / 10.0f
// = 123.8

You can then print this modified number to the serial monitor.
This method can also be generalized to other precisions. For 2 decimal places, we just have to multiply by 10^2 (100) and divide by 10^2. A macro would be:
#define TRUNCATE(val, numDecimalPlaces) \
    (float)(((long)((double)(val) * pow(10, (numDecimalPlaces) * 1.0f))) / (pow(10, (numDecimalPlaces)* 1.0f)))

Note: You don't have to actually dynamically compute pow(10, numDecimalPlaces), you can also create macros for each decimal precision from 1 to x and simply precompute that value (100, 1000, 10000, ..).
The same can also be achieved by using the standard library function trunc from math.h:
#define TRUNCATE_TO_ONE(val) \
    (trunc((val) * 10.0f) / 10.0f)

See http://www.cplusplus.com/reference/cmath/trunc/.
Here's a small sketch in which it is demonstrated:
#include <Arduino.h>

#define TRUNCATE(val, numDecimalPlaces) \
    (float)(((long)((double)(val) * pow(10, (numDecimalPlaces) * 1.0f))) / (pow(10, (numDecimalPlaces)* 1.0f)))

#define TRUNCATE_TO_ONE(val) \
    (trunc((val) * 10.0f) / 10.0f)

void printValueFormatted(float value, int numDecimalPlaces) {
    //format correctly
    char buf[20];
    char* res = dtostrf(value, sizeof(buf)-1, numDecimalPlaces, buf);

    //skip over empty chars
    while(*res == ' ')
        res++;

    //print buffer
    Serial.println(res);
}

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

void loop(void)
{
    float myVal = 123.8978f;
    printValueFormatted(myVal, 4);
    printValueFormatted(TRUNCATE(myVal, 1), 1);
    printValueFormatted(TRUNCATE(myVal, 2), 2);
    printValueFormatted(TRUNCATE(myVal, 3), 3);
    printValueFormatted(TRUNCATE(myVal, 1), 4);
    printValueFormatted(TRUNCATE(myVal, 2), 4);
    printValueFormatted(TRUNCATE(myVal, 3), 4);
    delay(1000);
}

Prints
123.8978
123.8
123.89
123.897
123.8000
123.8900
123.8970

I am having some problems when I am using this piece of code.. I am using serial print to print some analog values from the A0 and A1 pin of an arduino uno and dividing the values from each other to get a ratio. Eg:  A = A0 and B = A1 after that C = A/B and printing values C * 100 on the serial monitor. Everything is working perfectly fine until I made the value of B very low. Applying this code giving me negative values of the ratio and without it it is giving perfect values which is rounded to the nearest. Is there anything else to overcome this problem?

@PeouseDutta int is a 2-byte integer with a range of about -32K to +32K. Might be too small for you if you suddenly multiply by 100. I updated the code to convert it to long instead.

Note that pow() is expensive if you don't have an FPU.

Then what do you suggest @Edgar Bonet?

I addressed this above. The pow is only needed to compute 10^x, just precompute it.

I did a small test and it turns out that a call to pow() with compile-time constant arguments gets optimized out by gcc into a constant. So you should be fine with pow(). Check the generated assembly if in doubt.

Use the given [function] for your problem. This function works on a pre-defined [algorithm].
int roundTowardZero(float number, int decimal_place) {
    float round_number = round(number);
    if(round_number > number) round_number = round_number - 1;
    float deci = (number - round_number) * pow(10, decimal_place);
    float round_decimal = round(deci);
    if(round_decimal > deci) round_decimal = round_decimal - 1;
    round_decimal = round_decimal / pow(10, decimal_place);
    total_number = round_number + round_decimal;
    return total_number;
}

Place this function above int setup()
like:
int roundTowardZero( ... ) {
    ...
}
void setup() {
    ...
}
void loop() {
    ...
}

Function syntex is like this : roundTowardZero([Enter a Decimal Value], [Enter Round Place Value])
Example :roundTowardZero(123.89, 1) //Output : 123.8
Please comment below is you find any problem or face any error.


text:
I get a redefinition of "..." on every single line, of every variable, class, function, etc
When I compile my program I get an error message saying redefinition of "..." on every single line, of every variable, class, function, etc.
What am I doing wrong?
int incomingByte = 0;   // for incoming serial data

int byteCount = 0;

bool decision = false;

bool last_debounce = false;

bool test_running = false;

bool ready_freq_enable = false;

int cur_cavity_address = 0;

char serBuffer[256] = {0};

unsigned long previousMillis_enable = 0;
const long interval_online = 1000 / 100;

unsigned long previousMillis_debounce = 0;
const long interval_debounce = 50;

void setup() {
  // put your setup code here, to run once:
 /* pinMode(22, OUTPUT);//address bit 1
  pinMode(24, OUTPUT);//address bit 2
  pinMode(26, OUTPUT);//address bit 3

  pinMode(36, INPUT);

  pinMode(40, OUTPUT);
  pinMode(48, OUTPUT);
  pinMode(52, OUTPUT);*/

  pinMode(2, OUTPUT);//address bit 1
  pinMode(3, OUTPUT);//address bit 2
  pinMode(4, OUTPUT);//address bit 3

  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);

  pinMode(10, INPUT);

  Serial.begin(9600);
}

int seekChar(char c){
  for (int x = 0; x < 256; x++) {
    if (serBuffer[x] == c){
      return x;
    }
  }
  return -1;
}

void return_error(){
  Serial.println("ERROR!");
}

void loop() {
  if (Serial.available() > 0) {
          // read the incoming byte:
         int incomingByte = Serial.read();
          serBuffer[byteCount] = incomingByte;
          byteCount++;

          if (serBuffer[strlen(serBuffer)-1] == '\r'){
            serBuffer[strlen(serBuffer)-1] = 0; //remove the last carriage return

            int charIdx = seekChar(' ');
            char value[32] = {0};
            byteCount = 0;
            Serial.flush();

            if (charIdx != -1){
              memcpy(value, serBuffer + charIdx + 1, sizeof(value));
              memset(serBuffer + charIdx, 0, sizeof(serBuffer) - charIdx);
            }

            if (strcmp(serBuffer, "run") == 0){
              if (ready_freq_enable == true){
                test_running = strcmp(value, "true") == 0;
                if (test_running){
                  decision = 0;
                }
              } else {
                return_error();
              }

            } else if (strcmp(serBuffer, "reset") == 0){
              cur_cavity_address = 0;
              decision = false;
            } else if (strcmp(serBuffer, "decision") == 0){
              decision = strcmp(value, "true") == 0;
            } else if (strcmp(serBuffer, "enable") == 0){
              ready_freq_enable = strcmp(value, "true") == 0;

            } else if (strcmp(serBuffer, "address") == 0){
              if (abs(atoi(value)) > 8){
                return_error();
              }
              cur_cavity_address = abs(atoi(value));
            }

            memset(serBuffer, 0, sizeof(serBuffer));
            memset(value, 0, sizeof(value));

          }
  }

  test_running &= ready_freq_enable;
  update_io();
  check_status();
}

void check_status(){
  unsigned long currentMillis = millis();
  bool new_debounce =  digitalRead(10);
  if (new_debounce != last_debounce){

    if (currentMillis - previousMillis_debounce >= interval_debounce) {

    // save the last time you blinked the LED
      previousMillis_debounce = currentMillis;

      Serial.print( new_debounce );
      last_debounce = new_debounce;
    }

  } else {
    previousMillis_debounce = currentMillis;
  }
}

void update_io(){
  //digitalWrite(48, !digitalRead(48) );

  digitalWrite(7, test_running);

  digitalWrite(3, (cur_cavity_address & 0b001) != 0);
  digitalWrite(2, (cur_cavity_address & 0b010) != 0);
  digitalWrite(4, (cur_cavity_address & 0b100) != 0);

  unsigned long currentMillis = millis();
  //Serial.println(ready_freq_enable);
  if (currentMillis - previousMillis_enable >= interval_online) {
    // save the last time you blinked the LED
    previousMillis_enable = currentMillis;
    digitalWrite(5, !digitalRead(5) & ready_freq_enable);
    if (ready_freq_enable == false){
      cur_cavity_address = 0;
    }
  }

  digitalWrite(6, decision & ready_freq_enable);
}

Do you have more than one .ino file in the same folder?

Include some of the actual error messages in your question.

There doesn't appear to be anything wrong with the code you have posted, so its a problem with the build environment.  What environment are you building with?

Apparently I had a duplicate ino file on my same folder. Must of happened accidentally when I was creating a copy as backup. Thanks Chris!


text:
Serial.parseFloat() reads 0 despite me entering different value
I'm trying to make a robot that asks the user for the longitude and the altitude form the user and then using the data the GPS collects to go to the wanted location, however when I use Serial.parseFloat() to get the location from the user, i get the right value for the latitude and the longitude returns zero for some reason
here's the code i wrote
#include "Adafruit_FONA.h"

// standard pins for the shield, adjust as necessary
#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
#define PIN13 13
#define IN1 6      //IN1
#define IN2 7        //IN2
#define ENA 5          //ENA
#define ENB 10        //ENB
#define IN3 8          //IN3
#define IN4 9          //IN4
#define trigger1 A3      //Trigger
#define echo1 A2        //Echo
#define trigger2 A4
#define echo2 A5
#define trigger3 A0
#define echo3 A1

// We default to using software serial. If you want to use hardware serial
// (because softserial isnt supported) comment out the following three lines
// and uncomment the HardwareSerial line
#include <SoftwareSerial.h>
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;
int counter;
char serialData;
int duration;
float distance1, distance2, distance3;
float latitudeDestination, longitudeDestination;

// Hardware serial is also possible!
//  HardwareSerial *fonaSerial = &Serial1;
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
// Have a FONA 3G? use this object type instead
//Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST);

void getLatitude(){
    Serial.println("Enter the latitude destination :");
    while (Serial.available() == 0){}
    latitudeDestination = Serial.parseFloat();
}

void getLongitude()
{
    Serial.println("Enter the longitude destination :");
    while (Serial.available() == 0){}
    longitudeDestination = Serial.parseFloat();
}

void securityPassed()
{
    Serial.println("You need to pass security first");
    while (Serial.available() ==0){}
    serialData = Serial.read();
    if (serialData == '1')
    {
        Serial.println("Passed") ;
    }
    else {}
}

void setup() {
    pinMode(PIN13, INPUT);
    pinMode(trigger1, OUTPUT);
    pinMode(echo1, INPUT);
    pinMode(trigger2, OUTPUT);
    pinMode(echo2, INPUT);
    pinMode(trigger3, OUTPUT);
    pinMode(echo3, INPUT);
    pinMode(IN1 , OUTPUT);
    pinMode(IN2, OUTPUT);
    pinMode(IN3, OUTPUT);
    pinMode(IN4, OUTPUT);
    pinMode(ENA, OUTPUT);
    pinMode(ENB, OUTPUT);

    digitalWrite(ENA , HIGH);
    digitalWrite(ENB, HIGH);

    Serial.begin(9600);

    getLatitude();
    getLongitude();
    securityPassed();

    Serial.println(F("Adafruit FONA 808 & 3G GPS demo"));
    Serial.println(F("Initializing FONA... (May take a few seconds)"));
    fonaSerial->begin(4800);
    if (! fona.begin(*fonaSerial)) {
        Serial.println(F("Couldn't find FONA"));
        while (1);
    }
    Serial.println(F("FONA is OK"));
    // Try to enable GPRS
    Serial.println(F("Enabling GPS..."));
    fona.enableGPS(true);
}

void loop() {
    delay(2000);

    float latitude, longitude, speed_kph, heading, speed_mph, altitude;
    float latitudeDistance = latitudeDestination - latitude ;
    float longitudeDistance = longitudeDestination - longitude;

    // if you ask for an altitude reading, getGPS will return false if there isn't a 3D fix
    boolean gps_success = fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude);
    if (gps_success) {
      Serial.print("GPS lat:");
      Serial.println(latitude, 6);
      Serial.print("GPS long:");
      Serial.println(longitude, 6);
      Serial.print("GPS speed KPH:");
      Serial.println(speed_kph);
      Serial.print("GPS speed MPH:");
      speed_mph = speed_kph * 0.621371192;
      Serial.println(speed_mph);
      Serial.print("GPS heading:");
      Serial.println(heading);
      Serial.print("GPS altitude:");
      Serial.println(altitude);
      Serial.print("Latitude Distance: ");
      Serial.println(latitudeDistance);
      Serial.print("Longitude Distance: ");
      Serial.println(longitudeDistance);

      if ( latitudeDistance < 0.00001 && latitudeDistance > -0.00001)
      {

        if ( longitudeDistance < 0.00001 && longitudeDistance > -0.00001)
        {
          Serial.print("Arrived");
          stopm();
        }
        else
        {
          if (!counter == 1 && longitudeDistance > 0 )
          {
            moveRight();
            Serial.println("Turning Right");
            counter =1;
          }
          else if ( !counter == 1 && longitudeDistance < 0 )
          {
            moveLeft();
            Serial.println("Turning Left");
            counter=1;

          }
          moveForward();
        }
      }
      else
      {
        moveForward();
        Serial.print("Going To Destination");
      }
    }
    else {
      Serial.println("Waiting for FONA GPS 3D fix...");
    }
}

Can you demonstrate the problem with a simpler program?

Craig, I really wish I could make it simpler but I think the problem is caused by the GPS, so I just want people to take an look at the whole code to figure out where I went wrong

but the problem simply is that the function void getLatitude() works very well while the function void getLongitude() which is very similar to it doesn't work so well, when i enter the longitude destination in the serial monitor it gives the variable longitudeDestination a valure of zero no matter what value i enter

Are you sure you can't make something simpler with the problem? Can you make a simpler version that works to read the lat/long?

unfortunately not as the code is intended to receive the coordinates from the user and receive a signal from the raspberry pi that the user passed the face-recognition system and start navigating to it, all that in one Arduino code

Craig, this method working fine when i used it by its self, but when adding it to this code to work along with GPS it doesn't show the same efficiency, and there are not any easier ways to read lat/long than this one as far as i know

You are setting the lat/long Distance variables before reading the lat/long from the GPS.

What exactly are you sending to it? How does your location string look like?

@gre_gor it looks something like this 31.215486. just a normal float. I just would like to note that the first function getLatitude() works perfectly unlike the other one getLongitude

It is certainly possible that a person typing (or an automated system feeding data in packets over a spotty link) might fail to provide a valid number in the (default 1 second) time before parseFloat() times out.
However, given this is the second value to be read, there's a more complex possibility.
It's likely that the sequence actually sent might be something like
123.45\r\n
In this case 123.45 and the first non-value character \r will be consumed by the first parseFloat().
But that leaves a remaining \n in the serial buffer, so the serialAvailable() check is satisfied immediately and the next parseFloat() begins before the user has even started typing.  Unless they're very quick to respond, it may time out before they even begin.
If the user is supposed to use a terminal program that sends a carriage return and/or newline, you should probably change input processing to either consume until the end of the line before processing.
Or you can make your code flexible by being sure to consume any trailing line end characters (after checking for them with Serial.peek()) before you decide that the user has begun entering a new value and starting your next parseFloat() call.
You could also make your own more sophisticated parseFloat() using a different algorithm.

the two values should be send at once from Serial Monitor, separated by some non-digit character. parseFloat ignores non-digit initial characters.

@Juraj parseFloat ignores and consumes leading non-digit characters and one trailing one.  But if there are two, that second will trip the asker's serial data check, and cause the second parsing timeout to begin immediately.  The values in question are entered in response to distinct prompts so no, they wouldn't be sent "at once" unless someone decided to ignore the prompts and type them in immediate succession, or pipe in data from a script.  Changing the program to request all values on the same line could sort of work, if the terminal is in line mode or the user is careful not to pause.

Chris, exactly what I meant. Session Monitor sends the line at once


text:
Why does I2C On Nano Fail with LiquidCrystal_I2C library unless Nano runs at 8Mhz?
I have an Arduino Nano (running by default at 16Mhz).
I am connecting a 20x4 LCD screen via I2C (using A4 for SDA and A5 for SCL).
Here's the very simple code (which was previously only showing black blocks on the screen -- but now seems to be showing odd chars).

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 20, 4);

void setup() {
 lcd.begin();

  lcd.setCursor(2,0);
  lcd.print("test this");
}

void loop() {
  lcd.setCursor(5,2);
  lcd.print("Hello, world!");
}

ATmega328P DIP Circuit
I've been using this same LCD screen in another circuit which uses a raw ATMega382P (DIP) and it works 100% fine.
I put the LCD back into the circuit with the DIP, tested it and it works fine.
Then I remembered, that ATMega328P DIP runs at 8Mhz.
Run At 8Mhz
So that gave me the idea of running my Nano at 8Mhz just to see if it would work.
I altered the previous program just to set the CPU speed.  Here's the entire code again and a snapshot of it working.
#include <LiquidCrystal_I2C.h>
#include <avr/power.h>
LiquidCrystal_I2C lcd(0x3F, 20, 4);

void setup() {
   clock_prescale_set(clock_div_2);  // Sets to 8Mhz
 lcd.begin();

  lcd.setCursor(2,0);
  lcd.print("test this");
}

void loop() {
  lcd.setCursor(5,2);
  lcd.print("Hello, world!");
}

Questions
I've never changed anything on that LCD.
Is there something I'm missing?
I thought the SCL line (which is driven by the CPU) set the speed anyways??? -- -- and the LCD was just a slave.
Do you know of any reasons why this would behave this way?
Is there something I can change to run it at 16Mhz?

Can you print the value of the macro F_CPU on the serial monitor (or LCD)? Maybe the code (Wire.h) has compile-time checks for the clock speed and adjusts TWBRn wrong? (http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf chapter 26.5.2)

As soon as I read your comment it flipped a switch on in my brain and I remembered what I have done. I feel a bit foolish.  I altered my boards.txt so it has this line : nano.build.f_cpu=8000000L  which is setting it to build for 8Mhz.  I was doing that because I use Arduino IDE to build HEX files for my ATmega328P DIP and then I use AVR Dude to flash them to my chip.  I'm running ATmega328P DIPs on internal 8Mhz.  Thanks very much, I wouldn't have remembered that I had altered that.

Wow, that was a quite a shot into the dark but I hit something :D. Doesn't the Arduino IDE have specific board variants for 8MHz and 16MHz variants which you could use? Anyways, I guess you can write your own answer to the question and accept it.


text:
USB Mouse Passthrough
I am currently doing research for a project of mine. My goal is simple: I want to pass input from a physical mouse, to a microcomputer to process the input and modify, and send the input in the form of USB HID to a PC.

Mouse ---> Microcomputer (input modified) ---> PC

The Microcomputer preferably should be able to both send data to the PC (in the form of USB HID inputs as a mouse) and receive data from the PC.
I found the arduino Leonardo can act as a USB slave and emulate mouse movement, half of what I want. I need some microcomputer with capabilities to act both as a USB host and as a USB slave. I don't have experience with microcomputers, and I don't know how to find something with this feature.

Do you want to be able to change settings in the mouse from the computer? Can you explain what you want to modify? The mouse speed? Could it be possible to do this on the computer with a special driver? Which operating system?

I want the middleman computer to be able to modify the input to the main PC based on data from the main PC. A simple file pipe or something like that is enough for what I need. I assume it's possible with a USB controller in slave mode, because I've seen software based RGB keyboard controls, etc. However, in this case I don't need to access the mouse.

What do you want to modify? The mouse speed? Buttons? Auto-repeat?

I want to move a physical mouse, modify the movement in my microcomputer (e.g. multiply coordinates by two), then send it to the PC (the microcomputer will act as a virtual HID).

I'm not sure if that will work. A mouse does not know coordinates. If it is possible then it can be done on a linux computer as well without Arduino. I agree with the answer by @gdsports , attach a usb host shield.

Even in an incremental mode, the increments reported could be multiplied.

The cleanest solution to this problem would be to use an MCU with dual USB interfaces, one capable of being a USB host.   There are a few such parts in the STM32F4 lineup, and likely other brands as well, but not immediately clear if there are any with existing Arduino support.  Hardware wise, I believe you can do it with an inexpensive STM32F446 "Nucleo" board, though the pins of the USB interface are only available on headers, which you would need to wire to USB connectors.
A USB host shield is a possibility, but it's a bit "tacky" as a solution since it involves hanging a fairly sophisticated controller off a more primitive MCU, making an "upside down" architecture, and more expensive than an all-in-one solution, but it could be where you'll find the most existing code to support your effort.
One of the simplest things you could actually do would be to use a ps/2 mouse instead of a USB one, and interface that by bit-banging its simple serial interface.  Then you could use a board like a Leonardo or one of the Teensy series which has a customizable USB device interface, to present to the host computer as a USB mouse.

I was thinking about using a pi as USB host, then passing coordinates over GPIO to an arduino slave. But I feel like there will be input delay.

I like the nucleo as an option, I'm just worried that it may be too complex for me to understand, and I don't think I have the proper tools to solder on a header for usb (I have never purchased a small computer like this before).

It will indeed be challenging integrating the firmware - while a lot more capable, the examples also are far less turn-key than Arduino code.   In terms of attaching a USB port, what I did was to get a cheap USB extension cable, cut it in half, and crimp female header pins to it to plug into the board expansion headers (though watch out, the color code in cheap USB cables is usually completely wrong!).  These are all skills worth learning, but each takes time.  If this is the first time, you probably want to go with the host shield or the ps/2 mouse where you can stay purely Arduino.

thanks for the heads up. I found a nice little board while browsing adafruit, the Trinket M0 that i fcan couple with a USB host controller. https://github.com/gdsports/usb-metamorph/blob/master/README.md I found this github repo that has a lot of info about USB and stuff. I'm not even sure what the repo is about, I just skimmed over it, but the trinket m0 with USB host shield looks promising.

Hmm, while that combination might work, I worry that could bring the risk of the worst of both worlds; the atypical,only quasi-Arduino M0 platform, and the indirectness of the host shield.

The nucleo seems like my best bet. How do I research this further? What should I look for to determine if the computer has the functionality to work as a device and a host? It's not clear to me what I'm looking for in datasheets, etc. Thank you.

The hardware has the functionality, the issue is more that you'll need to do a lot of non-trivial software work, best case would be having to smoosh together two full example projects, figure out the semantics of handoff between them, wrangle a compiler more directly, etc.  Definitely worth the effort if making a product, less clear for a one-off and likely not if unfamiliar with such tasks.
Whatever you choose, start by getting each of hosting the mouse and emulating a mouse working independently.

Okay, thanks. It seems like I will need to actually order the device and tinker with it for a bit. I'm just wondering in general how I can tell which computer has what USB functionality. How did you figure out that Nucleo has this functionality? Was it through the SoC datasheet or something else? I'll probably be ordering a leonardo or something with the same SoC, just to get started with device emulation (i.e. slave device acting as USB HID).

So I found this: http://www.st.com/en/microcontrollers/stm32f446.html?querycriteria=productId=LN1875 We can see that there are two entries under USB, "USB OTG FS and USB OTG FS/HS", so I guess that says that there are two usb controllers capable of operating in OTG mode. Is this correct?

I know that I have already asked a lot, but how would i differentiate between USB ports and a USB controller? If I understand it is true that one host can have many ports, and multiple ports don't necessarily mean multiple controllers.

I hadn't recalled both being host capable, but that may be the case.  A given USB function can only support one connection, multiplexing is only possible by inserting hubs, which is not a complication you'd likely want here.

Plug a USB Host Shield into the Leonardo.
USB mouse --- USB Host Shield --- Leonardo --- PC

USB Host Shield Library
Circuits@Home Project
/*
 * USB Mouse pass through. Works at HID report level. HID report is not decoded.
 * Tested on Leonardo with Arduino USB host shield, IDE 1.8.5, and Logitech Marble
 * trackball/mouse. This is a proof of concept so is not guaranteed to work with
 * all USB mice/trackballs.
 */
// USB host mouse from USB Host Shield Library. Install using Library Manager
#include <hidboot.h>

// USB device mouse library included with Arduino IDE 1.8.5
#include <Mouse.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>

class MouseRptParser : public MouseReportParser
{
protected:
    void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
};

void MouseRptParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
{
  Serial.print("MouseRptParser::Parse");
  // Show USB HID mouse report
  for (uint8_t i = 0; i < len ; i++) {
    Serial.print(' '); Serial.print(buf[i], HEX);
  }
  Serial.println();

  // On error - return
  if (buf[2] == 1)
    return;

  if (len > 2) {
    uint8_t mouseRpt[4];
    mouseRpt[0] = buf[0];
    mouseRpt[1] = buf[1];
    mouseRpt[2] = buf[2];
    mouseRpt[3] = 0;
    HID().SendReport(1,mouseRpt,sizeof(mouseRpt));
  }
}

USB     Usb;
HIDBoot<USB_HID_PROTOCOL_MOUSE>    HidMouse(&Usb);

MouseRptParser Prs;

void setup()
{
  Serial.begin( 115200 );
#if !defined(__MIPSEL__)
  while (!Serial) delay(1); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  Serial.println("Start");

  if (Usb.Init() == -1) {
    Serial.println("USB host shield did not start.");
  }
  delay( 200 );

  HidMouse.SetReportParser(0, &Prs);

  Mouse.begin();
}

void loop()
{
  Usb.Task();
}


text:
Schematic for the adafruit motor shield v2.3
I am trying to locate a schematic for the Adafruit motor shield v2.3. It has many ports and currently I have found little to no explanation of what is on the board. I located this picture which highlights the motor ports, servo ports, and Arduino Pins. But what about everything else?
What are the pin holes above and below the Arduino pins? Are they secondary positions for the pins? What is the PWMs 0,1,14,15? How is the big empty board in the center setup?

Everything can be found out by reading the schematic which, incidentally, is the first hit on Google when you search for "Adafruit motor shield 2.3 schematic":

What are the pin holes above and below the Arduino pins? Are they secondary positions for the pins?

Yes. They're just there to make it easy to solder wires and jumpers to.

What is the PWMs 0,1,14,15?

They are connected to PWM pins 0, 1, 14 and 15 of the PCA9685.

How is the big empty board in the center setup?

It's just holes. Known as a "matrix prototyping board" for you to solder your own components and things into. Nothing there is connected to anything at all, it's up to you to make the connections with solder and wires.
As you can see from the schematic the only Arduino pins used are SDA/SCL (A4 and A5) and two PWM pins D9 and D10. Everything else comes from the on-board I2C PWM chip.

Thanks for clearing it up. I found this schematic earlier but it didn't go into detail like you mentioned in your post.


text:
Arduino RFID with motor and limit switches
Thanks for looking into my Arduino code.
I'm building an automated sliding draw, and I'm trying to activate the motor with a RFID scanner. The scanner waits for the token, and once it detects a token the motor turns and waits for a limit switch to be detected and stops the motor, then it does the same thing when it detects another RFID token but instead the motor travels in the opposite direction and waits for the opposite limit switch to be hit.
I have 2 sets of code. One is just the RFID scanner code which works fine, but it only switches a relay on and off. The other code is for the motor with 2 limit switches with a activation button. That code works too, and the draw opens and closes when you press a button, but it doesn't work with a RFID scanner. So my goal is to implement the RFID scanner code into the automated draw code in order to have a motor that turns and reverses with a RFID token and stops with a limit switch. I'm using an Arduino UNO board, 2 limit switches, a L298N H Bridge motor driver, and a MFRC522 RFID scanner.
Here is a schematic picture:

Here is the code for the automated draw using 3 buttons (2 limit switch, 1 activation button) and the DC motor:
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 4;     // the number of the pushbutton pin
const int buttonPin3 = 1;     // the number of the pushbutton pin
const int buttonPin2 = 2;     // the number of the pushbutton pin
const int motorPin =  5;      // the number of the LED pin
const int motorPin2 =  6;      // the number of the LED pin

// variables will change:
boolean buttonState = 0;         // variable for reading the pushbutton status
boolean buttonState2 = 0;         // variable for reading the pushbutton status
boolean buttonState3 = 0;   // variable for reading the pushbutton status

int drawPosition = 2;  // Tells progam what position the draw is in

/**
 *  setup inputs for switches and outs for motor pins
 *  serial begin to read the switches to test for errors
 */
void setup() {
    // initialize the pin as an inputs:
    pinMode(motorPin, OUTPUT);
    pinMode(motorPin2, OUTPUT);
    // initialize the pushbutton pin as an input:
    pinMode(buttonPin, INPUT);
    pinMode(buttonPin2, INPUT);
    pinMode(buttonPin3, INPUT);
    Serial.begin(9600);
}

/**
 * this function turns motor foward
 */
void drawForward() {
     // turn motor foward:
     digitalWrite(motorPin, LOW);
     digitalWrite(motorPin2, HIGH);
}

/**
 * this function turns motor backwards
 */
void drawBackward() {
     // turn motor in other direction:
     digitalWrite(motorPin, HIGH);
     digitalWrite(motorPin2, LOW);
}

/**
 * Stop the motor form moving
 */
void stopDrawFromMoving() {
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, LOW);

}

/**
 *
 */
void loop() {
   // read the state of the pushbutton value:
     buttonState = digitalRead(buttonPin);
     buttonState2 = digitalRead(buttonPin2);
   buttonState3 = digitalRead(buttonPin3);

   // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
   if (buttonState == HIGH) {
      drawPosition = 2;
      Serial.println(F("Front button state is high draw is open"));
      stopDrawFromMoving();
   }else if (buttonState2 == HIGH) {
      drawPosition = 1;
      stopDrawFromMoving();
  }

  if (buttonState3 == HIGH) {
    if( drawPosition  == 1 ){
      drawBackward();
      delay(100);
      drawPosition = 2;
      delay(100);
    }else if (drawPosition == 2 ) {
      delay(100);
      drawForward();
      delay(100);
      drawPosition = 1;
    }

  }
}

And that code you just read works fine, but it only activates the motor with a push button, but I'm trying to use RFID scanners.
Here is the code where I attempted to put the RFID code and the automated draw code together:
#include <EEPROM.h>     // We are going to read and write PICC's UIDs from/to EEPROM
#include <SPI.h>        // RC522 Module uses SPI protocol
#include <MFRC522.h>  // Library for Mifare RC522 Devices

//setting up inputs for limit switches and outputs for H Bridge motor driver
const int buttonPin = 4;     // the number of the pushbutton pin
const int buttonPin2 = 2;     // the number of the pushbutton pin
const int motorPin =  6;      // the number of the motors H Bridge (L298N) pin
const int motorPin2 =  5;      // the number of the motors H Bridge (L298N) pin

// variables for the state of the limit switches
boolean buttonState = 0;
boolean buttonState2 = 0;
int drawPosition = 2;  // Tells progam what position the draw is in

//this is the function to be called inside the loop. it makes the motor turn foward
void drawForward() {
  // turn H Bridge motor driver on in the foward polarity
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, HIGH);
}
// and this function turns the motor backwards
void drawBackward() {
  // turn H Bridge on with the REVERSED polarity
  digitalWrite(motorPin, HIGH);
  digitalWrite(motorPin2, LOW);
}
//This function is called when the motor needs to STOP moving
void stopDrawFromMoving() {
  //turn H Bridge motor driver OFF by turning both pins to LOW
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, LOW);
}

// Just stuff for the RFID to work
boolean match = false;          // initialize card match to false
boolean programMode = false;  // initialize programming mode to false
int successRead;    // Variable integer to keep if we have Successful Read from Reader
byte storedCard[4];   // Stores an ID read from EEPROM
byte readCard[4];   // Stores scanned ID read from RFID Module
byte masterCard[4];   // Stores master card's ID read from EEPROM
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.

///////////////////////////////////////// Setup ///////////////////////////////////
void setup() {
  // Setting up the digital read for limit switches
  buttonState = digitalRead(buttonPin);
  buttonState2 = digitalRead(buttonPin2);

  //Protocol Configuration for RIFD scanner
  Serial.begin(9600);  // Initialize serial communications with PC
  SPI.begin();           // MFRC522 Hardware uses SPI protocol
  mfrc522.PCD_Init();    // Initialize MFRC522 Hardware
  // This sets the RFID range to Maximum
  mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);
  Serial.println(F("BlueCore Tech Acces Control"));   // For debugging purposes

  // Check if master card defined, if not let user choose a master card
  if (EEPROM.read(1) != 143) {
    Serial.println(F("No Master Card Set"));
    Serial.println(F("Scan A RFID Card to Set as Master Card"));
    do {
      successRead = getID();            // sets successRead to 1 when we get read from reader otherwise 0
    }
    while (!successRead);                  // Program will not go further while you not get a successful read
    for ( int j = 0; j < 4; j++ ) {        // Loop 4 times
      EEPROM.write( 2 + j, readCard[j] );  // Write scanned PICC's UID to EEPROM, start from address 3
    }
    EEPROM.write(1, 143);                  // Write to EEPROM we defined Master Card.
    Serial.println(F("Master Card Set"));
  }
  Serial.println(F("-------------------"));
  Serial.println(F("Master Card's UID = "));
  for ( int i = 0; i < 4; i++ ) {          // Read Master Card's UID from EEPROM
    masterCard[i] = EEPROM.read(2 + i);    // Write it to masterCard
    Serial.print(masterCard[i], HEX);
  }
  Serial.println("");
  Serial.println(F("-------------------"));
  Serial.println(F("Everything Ready"));
  Serial.println(F("Waiting for Keys or cards to be scanned"));
  cycleLeds();    // Everything ready lets give user some feedback by cycling leds
}
///////////////////////////////////////// Main Loop ///////////////////////////////////
void loop () {

//this first chunk of "if" is always setting the variable from iether "1" or "2" depending on what limit switch is closed, this allows the program to REMEMBER what the position of the draw is.
  if (buttonState == HIGH) {   //if the back limit switch is closed, the draw is in the closed (or backward) position
    drawPosition = 2;    //sets the variable to "2" meaning the draw is in the closed position
    Serial.println(F("Front button state is high so draw is open"));
    stopDrawFromMoving();  //this also stopes the motor form moving foward any further
  } else if (buttonState2 == HIGH) { // same principle applies here but its just reversed:
    drawPosition = 1;
    Serial.println(F("Back button state is high draw is open"));
    stopDrawFromMoving();
  }

// THERE IS A ERROR HERE I CANNOT FIX ////////////////////////////////////////////////////////////////////////////THERE IS A ERROR HERE I CANNOT FIX/////////////////////////////////////////THERE IS A ERROR HERE I CANNOT FIX///////////////////////////////////////
//   'getID' was not declared in this scope exit status 1      this happens anywhere inside the loop where there is a mention of the 'getID' function. I though this only happens if you calling a function but it doesnt exist, but it clearly does exist becuase its at the bottom
  do {
    successRead = getID();  // sets successRead to 1 when we get read from reader otherwise 0
    if (programMode) {
    }
    else {
      normalModeOn();     // Normal mode, blue Power LED is on, all others are off
    }
  }
  while (!successRead);   //the program will not go further while you not get a successful read
  if (programMode) {
    if ( isMaster(readCard) ) { //If master card scanned again exit program mode
      Serial.println(F("Master Card Scanned"));
      Serial.println(F("Exiting Programming Mode"));
      Serial.println(F("-----------------------------"));
      programMode = false;
      return;
    }
    else {
      if ( findID(readCard) ) { // If scanned card is known delete it
        Serial.println(F("I know this key, removing..."));
        deleteID(readCard);
        Serial.println("-----------------------------");
      }
      else {                    // If scanned card is not known add it
        Serial.println(F("I do not know this key, adding..."));
        writeID(readCard);
        Serial.println(F("-----------------------------"));
      }
    }
  }
  else {
    if ( isMaster(readCard) ) {   // If scanned card's ID matches Master Card's ID enter program mode
      programMode = true;
      Serial.println(F("Hello Master - Entered Programming Mode"));
      int count = EEPROM.read(0);   // Read the first Byte of EEPROM that
      Serial.print(F("I have "));     // stores the number of ID's in EEPROM
      Serial.print(count);
      Serial.print(F(" record(s) in DATABASE"));
      Serial.println("");
      Serial.println(F("Scan a Card or key to ADD or REMOVE"));
      Serial.println(F("-----------------------------"));
    }
    else {
      if ( findID(readCard) ) {  // If not, see if the card is in the EEPROM
        Serial.println(F("Welcome, Acces Granted"));
        //this is another part from the other code that im trying to implement into the RFID code
        if ( drawPosition  == 1 ) { //if the variale is saying the draw is currently in the FOWARD position
          drawBackward();  //then return it to the BACKWARD position
          delay(100);
          drawPosition = 2;  //then make the variable a "2" so the code remembers what the position of the draw is for next time the RFID scanner is activated
          delay(100);
        } else if (drawPosition == 2 ) {  //same principle under here but its just reversed for when the draw is found in the opposite position and needs to return to the opposite position
          delay(100);
          drawForward();
          delay(100);
          drawPosition = 1;
        }
      }
      else {   // If the token is unknown, show that the ID was not valid and dont do anything else
        Serial.println(F("Acces Denied!"));
      }
    }

  }
  ///////////////////////////////////////// Get PICC's UID ///////////////////////////////////
  int getID() {
    // Getting ready for Reading PICCs
    if ( ! mfrc522.PICC_IsNewCardPresent()) { //If a new PICC placed to RFID reader continue
      return 0;
    }
    if ( ! mfrc522.PICC_ReadCardSerial()) {   //Since a PICC placed get Serial and continue
      return 0;
    }
    // There are Mifare PICCs which have 4 byte or 7 byte UID care if you use 7 byte PICC
    // I think we should assume every PICC as they have 4 byte UID
    // Until we support 7 byte PICCs
    Serial.println(F("Scanned KEY's UID:"));
    for (int i = 0; i < 4; i++) {  //
      readCard[i] = mfrc522.uid.uidByte[i];
      Serial.print(readCard[i], HEX);
    }
    Serial.println("");
    mfrc522.PICC_HaltA(); // Stop reading
    return 1;
  }
  ///////////////////////////////////////// Show reader details ///////////////////////////////////
  void ShowReaderDetails() {
    // Get the MFRC522 software version
    byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
    Serial.print(F("MFRC522 Version: 0x"));
    Serial.print(v, HEX);
    if (v == 0x91)
      Serial.print(F(" = v1.0"));
    else if (v == 0x11)
      Serial.print(F(" = BlueCore Tech. RFID Acces v2.0"));
    else
      Serial.print(F(" (unknown)"));
    Serial.println("");
    // When 0x00 or 0xFF is returned, communication probably failed
    if ((v == 0x00) || (v == 0xFF)) {
      Serial.println(F("WARNING: Communication failure, is the RFID-MFRC522 properly connected?"));
      while (true); // do not go further
    }
  }
  //////////////////////////////////////// Read an ID from EEPROM //////////////////////////////
  void readID( int number ) {
    int start = (number * 4 ) + 2;    // Figure out starting position
    for ( int i = 0; i < 4; i++ ) {     // Loop 4 times to get the 4 Bytes
      storedCard[i] = EEPROM.read(start + i);   // Assign values read from EEPROM to array
    }
  }
  ///////////////////////////////////////// Add ID to EEPROM   ///////////////////////////////////
  void writeID( byte a[] ) {
    if ( !findID( a ) ) {     // Before we write to the EEPROM, check to see if we have seen this card before!
      int num = EEPROM.read(0);     // Get the numer of used spaces, position 0 stores the number of ID cards
      int start = ( num * 4 ) + 6;  // Figure out where the next slot starts
      num++;                // Increment the counter by one
      EEPROM.write( 0, num );     // Write the new count to the counter
      for ( int j = 0; j < 4; j++ ) {   // Loop 4 times
        EEPROM.write( start + j, a[j] );  // Write the array values to EEPROM in the right position
      }
      successWrite();
      Serial.println(F("Succesfully added ID record to DATABASE"));
    }
    else {
      failedWrite();
      Serial.println(F("Failed! There is something wrong with ID or bad DATABASE"));
    }
  }
  ///////////////////////////////////////// Remove ID from EEPROM   ///////////////////////////////////
  void deleteID( byte a[] ) {
    if ( !findID( a ) ) {     // Before we delete from the EEPROM, check to see if we have this card!
      failedWrite();      // If not
      Serial.println(F("Failed! There is something wrong with ID or bad DATABASE"));
    }
    else {
      int num = EEPROM.read(0);   // Get the numer of used spaces, position 0 stores the number of ID cards
      int slot;       // Figure out the slot number of the card
      int start;      // = ( num * 4 ) + 6; // Figure out where the next slot starts
      int looping;    // The number of times the loop repeats
      int j;
      int count = EEPROM.read(0); // Read the first Byte of EEPROM that stores number of cards
      slot = findIDSLOT( a );   // Figure out the slot number of the card to delete
      start = (slot * 4) + 2;
      looping = ((num - slot) * 4);
      num--;      // Decrement the counter by one
      EEPROM.write( 0, num );   // Write the new count to the counter
      for ( j = 0; j < looping; j++ ) {         // Loop the card shift times
        EEPROM.write( start + j, EEPROM.read(start + 4 + j));   // Shift the array values to 4 places earlier in the EEPROM
      }
      for ( int k = 0; k < 4; k++ ) {         // Shifting loop
        EEPROM.write( start + j + k, 0);
      }
      successDelete();
      Serial.println(F("Succesfully removed ID record from DATABASE"));
    }
  }
  ///////////////////////////////////////// Check Bytes   ///////////////////////////////////
  boolean checkTwo ( byte a[], byte b[] ) {
    if ( a[0] != NULL )       // Make sure there is something in the array first
      match = true;       // Assume they match at first
    for ( int k = 0; k < 4; k++ ) {   // Loop 4 times
      if ( a[k] != b[k] )     // IF a != b then set match = false, one fails, all fail
        match = false;
    }
    if ( match ) {      // Check to see if if match is still true
      return true;      // Return true
    }
    else  {
      return false;       // Return false
    }
  }
  ///////////////////////////////////////// Find Slot   ///////////////////////////////////
  int findIDSLOT( byte find[] ) {
    int count = EEPROM.read(0);       // Read the first Byte of EEPROM that
    for ( int i = 1; i <= count; i++ ) {    // Loop once for each EEPROM entry
      readID(i);                // Read an ID from EEPROM, it is stored in storedCard[4]
      if ( checkTwo( find, storedCard ) ) {   // Check to see if the storedCard read from EEPROM
        // is the same as the find[] ID card passed
        return i;         // The slot number of the card
        break;          // Stop looking we found it
      }
    }
  }
  ///////////////////////////////////////// Find ID From EEPROM   ///////////////////////////////////
  boolean findID( byte find[] ) {
    int count = EEPROM.read(0);     // Read the first Byte of EEPROM that
    for ( int i = 1; i <= count; i++ ) {    // Loop once for each EEPROM entry
      readID(i);          // Read an ID from EEPROM, it is stored in storedCard[4]
      if ( checkTwo( find, storedCard ) ) {   // Check to see if the storedCard read from EEPROM
        return true;
        break;  // Stop looking we found it
      }
      else {    // If not, return false
      }
    }
    return false;
  }
  ///////////////////////////////////////// Write Success to EEPROM   ///////////////////////////////////
  void successWrite() {
    Serial.println(F("Write to EEPROM is Succsusful"));
  }
  ///////////////////////////////////////// Write Failed to EEPROM   ///////////////////////////////////
  void failedWrite() {
    Serial.println(F("Failed to write to EEPROM"));
  }
  ///////////////////////////////////////// Success Remove UID From EEPROM  ///////////////////////////////////
  void successDelete() {
    Serial.println(F("Removed from EEPROM"));
  }
  ////////////////////// Check readCard IF it is masterCard   ///////////////////////////////////
  // Check to see if the ID passed is the master programing card
  boolean isMaster( byte test[] ) {
    if ( checkTwo( test, masterCard ) )
      return true;
    else
      return false;
  }

So there's 2 main errors in the second code (the code implementing RFID with my limit switch logic and motor functions.)
The first one was quite obvious in the code when I said "ERROR HERE" and the error is a "exit status 1 getID was not declared in this scope." Not sure why this happens, I cant make sense of it.
Once that's fixed I can look at the main issue, and that's actually making it work. I have tested the code before I was getting that exit status error and the logic wasn't working. There is probably a better way of putting these to bits of code together but I'm fairly new to programing and I cant figure it out.
Thanks so much for your help  ( :

The getid issue has been fixed, i simply moved all the functions to the top of the code so the compiler reads them before it gets to the loop code. But the code still isn't working in practice. The tokens are not read at all, but the master card is. The code is trying to turn the motor and do all that code once it detects a token that is known. Any help would be great.

C++ and C only reads function declarations and globals from top to bottom, it will not look ahead to see if any others were defined.
You can put a declaration of the functions you want to use above where you want to use it.
//...
int getID();
///////////////////////////////////////// Main Loop ///////////////////////////////////
void loop () {
//...

Usually the Arduino IDE will attempt to generate declarations automatically.

thanks, ill try to put them all on top and let you know how it goes


text:
How do I get LEDs to turn on according to a continuous Python input?
I'm trying to make a tuner. 3 LEDs are connected to the Arduino board, each one corresponding to one situation (too high, low or correct).
Python handles the detecting of a note according to the mic input, and determines which led should be turned on, but as it's a live tuner, Python sends the information pretty fast.
I've figured out how to turn a led on one at a time and keep it on as long as the input doesn't change, but it only works at a low speed when I do it manually, with a Python program like this :
code=1
while code!=0:
    code=input("Code?")
    ser.write(code.encode('utf-8'))

If I try it with a Python code such as :
code= '5'
while 1:
ser.write(code.encode('utf-8'))

then the LEDs just stay off.
Here is my Arduino Code :
int hauteur = 0;

void setup() {
    pinMode (2, OUTPUT); //red pin
    pinMode (6, OUTPUT); //green pin
    pinMode (5, OUTPUT); //yellow pin
    Serial.begin(9600);
}

void loop() {
    if(Serial.available ()) {
        hauteur = Serial.parseInt();

        while (hauteur==2) {
            (digitalWrite(2,HIGH));
            if (Serial.available ()) { hauteur=Serial.parseInt(); }
        }
        digitalWrite(2,LOW);

        while (hauteur==5){
            (digitalWrite(5,HIGH));
            if (Serial.available ()) { hauteur=Serial.parseInt(); }
        }
        digitalWrite(5,LOW);

        while (hauteur==6){
            (digitalWrite(6,HIGH));
            if (Serial.available ()) { hauteur=Serial.parseInt(); }
        }
        digitalWrite(6,LOW);

        Serial.flush();
    }
}

If 2, 5 or 6 are received with enough time in between them, then the board does what it's supposed to do and turns on the according LED. How can I reduce that necessary lapse of time to get a real time change of lights like a live tuner?

Try to not send only the number, but also a trailing non-digit character as a delimiter (like "\n" the newline character)

what for is the Serial.flush()? you don't output anything on Serial in loop()

make two variables. current pin and next pin. read value in next pin and do nothing if next pin is same as current pin. if they are different set next pin high, current pin low and set current pin to next pin value.

your arduino code is very badly formatted, and therefore hard to read .... please correct the indentation ......... your second python snippet is also badly indented and it will not work as expected

You don't need to parseInt for one digit. Use Serial.read().
  hauteur = Serial.read() - 48; // 48 is ascii code of '0'

or better send bytes from python, not digit characters


text:
String class summation disappears the right operand
I intend to create a function to jsify sensors' content and save it on a SD-card or send through a http client. Except for the Serial.println's, the function is transcripted below.
String jsonificar(vector<vector<String>> sujeito){
  String json_txt = String(""), chave, valor;
  String chave_str, valor_str;

  json_txt+=String("{");
  for(unsigned int i = 0; i<sujeito.size(); i++){
    if(sujeito[i].size() != 2){
        Serial.println("Cada conteudo deve conter 2 textos!");
    }
    else{
        chave = sujeito[i][0];
        valor = sujeito[i][1];
        Serial.println(chave);
        Serial.println(valor);
        Serial.println(json_txt);
        json_txt += "\\\"";
        Serial.println(json_txt);
        json_txt += chave;
        Serial.println(json_txt);
        json_txt += "\\\"";
        Serial.println(json_txt);
        json_txt += ":";
        Serial.println(json_txt);
        json_txt += "\\\"";
        Serial.println(json_txt);
        json_txt += valor;
        Serial.println(json_txt);
        json_txt += "\\\"";
        Serial.println(json_txt);

        if(i != sujeito.size() - 1){
          json_txt += String(",");
        }
    }
  }

  json_txt+="}";
  Serial.println(json_txt);

  return json_txt;
}

The output on serial follows:
Output:

Chave1
Valor1
{
{\"
{\"Chave1
{\"Chave1\"
{\"Chave1\":
{\"Chave1\":\"
{\"Chave1\":\"Valor1
{\"Chave1\":\"Valor1\"
Chave2
Valor2
{\"Chave1\":\"Valor1\",
{\"Chave1\":\"Valor1\",\"
{\"Chave1\":\"Valor1\",\"    <===
{\"Chave1\":\"Valor1\",\"\"
{\"Chave1\":\"Valor1\",\"\": <===
{\"Chave1\":\"Valor1\",\"\": <===
{\"Chave1\":\"Valor1\",\"\": <===
{\"Chave1\":\"Valor1\",\"\": <===
{\"Chave1\":\"Valor1\",\"\":}

The arrows show the spots where the logs are different from expected: the keys and values provided are "Chave1", "Valor1", "Chave2", "Valor2". So, the key-value should be "Chave2":"Valor2". Would you have a grasp of this behaviour? I look forward for the answer!

How did you get std::vector into Arduino? It doesn't compile for me.

The same way one would use in default C++ appplication: using namespace std;   You have  answered your own question unpurposely ;P

The Arduino core implementation for AVR does not have these C++ STL types. Are you using an additional library like https://github.com/mike-matera/ArduinoSTL ?

Yes, I use ArduinoSTL. I also use PlatformIO as IDE and it says vector comes from namespace std.

You must be using this above library, no doubt. It does not work without it. I compiled this code and it ran without an error. Have a look at: https://pastebin.com/LPTYDje5

Note that you are constructing strings which uses dynamic memory allocation. What MCU are you on? Arduino Uno? You can see that my minimal test sketch works, so if it doesn't in your case, you ran out of memory. What exact sketch are you using?

`#include <Arduino.h>
#include <unity.h>
#include "../src/utils.h"
vector vetor_auxiliar1, vetor_auxiliar2;
vector<vector> vetor_mestre;
`

`void test_jsonificar(){
vetor_auxiliar1.push_back(String("Chave1"));
vetor_auxiliar1.push_back(String("Valor1"));
vetor_mestre.push_back(vetor_auxiliar1);
vetor_auxiliar2.push_back(String("Chave2"));
vetor_auxiliar2.push_back(String("Valor2"));
vetor_mestre.push_back(vetor_auxiliar2);

String resultado, esperado = String("{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2\"}");
resultado = jsonificar(vetor_mestre);

TEST_ASSERT_EQUAL(1, esperado.compareTo(resultado));

}
`

`void setup() {
Serial.begin(9600);
UNITY_BEGIN();
}
void loop() {
RUN_TEST(test_jsonificar);
UNITY_END(); // stop unit testing
}`

Okay you should have edited your question with that code but when I run that (wihtout the unity testing framework) I get the behaviour that it crashes after the third iteration (when put into a loop). I would just use the https://github.com/bblanchon/ArduinoJson library to construct these JSON strings in a more memory-efficient way than concatinating Strings which uses loads of heap (https://pastebin.com/h2eE3sgc)

Ok, I will do so. Thank you for the consulting.

Your "disappearing string" has the following cause: Out-of-Memory.
You are constructing lots of String objects in your code and are concatinating to one. That uses memory on the heap for each String (and realloc() when the String memory must be expanded).
Consider the following test sketch which includes your code but also adds a memory leak by 150 bytes in each iteration:
#include <Arduino.h>
#include <ArduinoSTL.h>
using namespace std;

extern unsigned int __heap_start;
extern void *__brkval;

/*
 * The free list structure as maintained by the
 * avr-libc memory allocation routines.
 */
struct __freelist {
    size_t sz;
    struct __freelist *nx;
};

/* The head of the free list structure */
extern struct __freelist *__flp;

/* Calculates the size of the free list */
int freeListSize() {
    struct __freelist* current;
    int total = 0;
    for (current = __flp; current; current = current->nx) {
        total += 2; /* Add two bytes for the memory block's header  */
        total += (int) current->sz;
    }
    return total;
}

int freeMemory() {
    int free_memory;
    if ((int) __brkval == 0) {
        free_memory = ((int) &free_memory) - ((int) &__heap_start);
    } else {
        free_memory = ((int) &free_memory) - ((int) __brkval);
        free_memory += freeListSize();
    }
    return free_memory;
}

String jsonificar(vector<vector<String>> sujeito) {
    String json_txt = String(""), chave, valor;
    String chave_str, valor_str;

    json_txt += String("{");
    for (unsigned int i = 0; i < sujeito.size(); i++) {
        if (sujeito[i].size() != 2) {
            Serial.println("Cada conteudo deve conter 2 textos!");
        } else {
            chave = sujeito[i][0];
            valor = sujeito[i][1];
            Serial.println(chave);
            Serial.println(valor);
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += chave;
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += ":";
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += valor;
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);

            if (i != sujeito.size() - 1) {
                json_txt += String(",");
            }
        }
    }

    json_txt += "}";
    Serial.println(json_txt);

    return json_txt;
}

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

String myStr = "";

void loop(void) {

    Serial.print(F("Free Memory:"));
    Serial.println(freeMemory());

    //force a memory leak by allocating appending to a global String
    myStr +=
            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

    vector<vector<String>> v =
            { { "Chave1", "Valor1" }, { "Chave2", "Valor2" }, };

    jsonificar(v);
    delay(1000);
}

From the output we can see the exact point where we have enough memory and the result is correct, and where we don't have enough memory and the string just "disappears" because there was not enough memory to allocate it:
Free Memory:911
Chave1
Valor1
{
{\"
{\"Chave1
{\"Chave1\"
{\"Chave1\":
{\"Chave1\":\"
{\"Chave1\":\"Valor1
{\"Chave1\":\"Valor1\"
Chave2
Valor2
{\"Chave1\":\"Valor1\",
{\"Chave1\":\"Valor1\",\"
{\"Chave1\":\"Valor1\",\"Chave2
{\"Chave1\":\"Valor1\",\"Chave2\"
{\"Chave1\":\"Valor1\",\"Chave2\":
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2
{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2\"}
Free Memory:761
Chave1
Valor1
{
{\"
{\"Chave1
{\"Chave1\"
{\"Chave1\":
{\"Chave1\":\"
{\"Chave1\":\"Valor1
{\"Chave1\":\"Valor1\"
Chave2
Valor2
{\"Chave1\":\"Valor1\",
{\"Chave1\":\"Valor1\",\"
{\"Chave1\":\"Valor1\",\"Chave2
{\"Chave1\":\"Valor1\",\"Chave2\"
{\"Chave1\":\"Valor1\",\"Chave2\":
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"


text:
ESP8266 communication issue
I have an issue communicating with ESP8266 via Arduino Uno's serial ports.
I can connect to it using
python -m serial.tools.miniterm /dev/ttyUSB0 115200
command but when trying to send an AT command, it looks like this:
�tC�

ERROR
�v[�
ERROR
at

OK

So, sometimes I'm able to properly send a command, but usually what I type turns to gibberish. I've tried other baud values, but only 115200 works.
I'm powering Arduino via USB from my laptop. I've seen some mentions that this behavior may be caused by low voltage but unfortunately, I'm currently unable to verify it whether that's a case here.
My schematic looks like this:

I'm new to this, so if there is any crucial information I've missed, then please let me know and I'll do my best to provide it.

Where are the voltage dividers from Arduino TX to ESP RX to shift from 5V to 3.3V? Are you sure the module is not on its default 9600 baud? Why is the ESP's EN not pulled up? Does adding a big capacitor between 3.3V and GND help?

Regarding voltage dividers: I was unaware it was needed. I've been more or less following this instruction: http://www.instructables.com/id/Arduino-motion-detector-PIR-that-writes-to-SQL-via/
Regarding the 9600 baud: Pretty sure - when I try to connect at 9600 it's all gibberish.
ESP EN: Will look into it
Capacitor: Will look into it

Appendix: With EN (Enable) I meant CH_PD (chip powerdown) -- but you already had it conencted to 3V3, so that's ok. Most probably it's because of the voltage shifting or the power supply is too bad.

3.3 V pin of Uno can't supply the necessary current for the esp8266.

115200 is the default baud rate of AT firmware

@Juraj I'll try to get some sort of external supply running tomorrow and report back

check the wires and connections. try connect the ground directly, not over breadboard

@MaximilianGerhardt It seems that the issue was with TX 5V voltage. I've bought some resistors, added a voltage divider and it works fine. Will answer my own question with updated schematic soon

The issue, as Maximilian Gergardt suggested in comments, was with Arduino's TX/RX sending 5V signal. Adding voltage dividers on RX line solved the issue. Refer to diagram below for details:


text:
How can I upload .hex files to a Pro Micro using Linux?
I have a hand-wired keyboard that uses a Pro Micro board, with an ATmega32u4 chip. I can't seem to flash firmware on it. The commands I've been trying are variations of:
avrdude -p m32U4 -P /dev/ttyACM0 -c avr109 -U flash:w:atreus62.hex

The errors I've been getting begin:
Writing | #######avrdude: error: programmer did not respond to command: set addr
####avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: write block
 ***failed;
 ***failed;
 ***failed;
 ***failed;

And end:
#avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: set addr
#avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: set addr
# | 100% 0.16s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0x0d != 0x0c
avrdude: verification error; content mismatch
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: error: programmer did not respond to command: exit bootloader

I'm on Arch Linux. Any ideas?

Enable verbose mode, program it once with the IDE, and copy the command line it uses.

What is the IDE?

And what do you mean by "program it"? Could you just tell me what the avrdude command is? I don't have any IDE installed.

Also verbose modes -v, -vv, -vvv, and -vvvv don't really seem to affect anything.

You are asking a question on the Arduino site, presumably you are familiar with the Arduino tools?  If not, give that a try first to validate your hardware and tools setup (before you try to do things the hard way.  Use the avrdude and configuration file for it that ships with a modern Arduino IDE version, and let the IDE drive it the first time, with verbose mode selected in the dropdown menu, so you see the suitable command.

I have no idea what the Arduino IDE is all about, but I installed it, and can't really make heads or tails of it. How can I open a hex file with it? If I could get the IDE to program the board, that'd be fine, too, but I have no idea what's going on in this program.

Also the IDE doesn't seem to have my board listed (pro micro).

@Jon, how did you create the hex file? ... it is odd that you would not know what an IDE is.

Using QMK. I know what an IDE is, just not what the Arduino IDE is supposed to do with .hex files, or how it's supposed to work.

There's two stages to uploading a hex file to a USB-based Arduino - and you're only doing the second stage.
The first stage is to reset the board into the bootloader so it can accept the instructions from the second stage.  The IDE normally does that manually for you when you hit the UPLOAD button.
The way these boards are reset is to first open the CDC/ACM port and set the baud rate to 1200, then close the port again. That triggers the code to reset the board into the bootloader.
You can probably do it using the stty tool in Linux:
$ stty -F /dev/ttyACM0 speed 1200
$ stty -F /dev/ttyACM0 speed 115200
$ avrdude -p m32U4 -P /dev/ttyACM0 -c avr109 -U flash:w:atreus62.hex

The second stty may not actually be needed, but it's good to reset the baud rate to a normal value ready for uploading. I don't have a board to hand right now to test it though.

Those commands don't seem to help, sadly. They both return 9600, if that's at all helpful. I'm still getting "programmer did not respond" errors.

The return value is the value it was before changing it. The second should return 1200 not 9600.  You can try using stty -F /dev/ttyACM0 ospeed 1200 ispeed 1200 instead.

That doesn't seem to help either, I'm afraid.

Have you had it working in the IDE at all?

I'm at a loss for how to upload .hex files to a chip using the IDE. (And furthermore the IDE is almost totally useless to me, since the UI isn't HiDPI-friendly.)

You don't upload hex files with the IDE. You write code, compile it, and upload that. Try the Blink example.

@Jon The point of the IDE and the reason we're all harping on it is that success in using the IDE's automation to upload trivial example code you aren't interested in shows you the commands you can then use to upload your custom hex file.  It lets you benefit from the work someone else put into figuring out how to do this, rather than having to figure it out again from scratch.  There's more wrong than right with the Arduino IDE when it comes to actual software development, but what it is good at is getting trivial code into a chip without spending a day reading documentation.

Also it confirms that your board is actually working and able to accept code. Some cheap chinese clones come without a bootloader.

If I can't upload hex files with the IDE, though, how can I use it? The codebase that generates my hex files is fairly complex, and scattered in a bunch of files across QMK. There's a real network of includes, env vars, and makefile instructions that I, as a non-C programmer, can't make sense of. Trying to put this all together in a way that the IDE will understand seems incredibly complicated. So I think everyone's advice to use the IDE is well-intentioned, but it won't help me just get this already-compiled hex file onto my board, which should be a simple task.

We're not telling you to use the IDE to complete your task. We are telling you to use the IDE to test that the board and everything is functional. Once that is confirmed we can then move on to more low-level things.

@Majenko you just saved my day, thank you! Couldn't get QMK to flash to my pro micro using any of the normal tooling, but setting ospeed and ispeed explicitly caused it to magically work. For the record I'm on OSX.

I had the same issue, and it was caused by udev, I found the answer here
It's some obscure bug
Tweaking udev rules solved the problem for me, now all is good, here is the procedure: https://learn.adafruit.com/adafruit-arduino-ide-setup/linux-setup#udev-rules

Had the same issue, and this fixed it for me! (mostly - I still had to use the stty commands from Majenko's answer, and run the upload a couple of times in order to get it working... but it worked!) It's a bit difficult to find this answer...


text:
Arduino OTA port not updating in Arduino IDE
The OTA (from the ArduinoOTA library) on my ESP8266 does not show up in the programming ports on the Arduino IDE unless I restart the IDE.   Even when I plug in a usb cable and the ports list updates to show that device, it does not show the network port without a restart.   Does anyone know why this would happen or how to solve it?
I downloaded the newest version of the IDE and this is still the case.

Is there any way to make the IDE actively check for a re-established mDns connection?

I have the same problem, ports appear on IDE restart and then except one (which also seems to be random) all disappear after some time.

I found an workaround for Windows:

disable IPv6 from Network Configuration
disable/enable network interface
restart Arduino IDE

You should see your OTA device in port list, in Arduino IDE.

Do you have to do these steps every time the OTA device turns on or does this cause the IDE to actively monitor for network OTA ports?

I just did it on the Windows machine with Arduine IDE. For example on Mac I don't have this problem.

For some reason you have to close and reopen the Arduino IDE for it to discover all available OTA ports.   Not sure why this is -- if anyone knows I would be glad to learn.
EDIT: keeping this answer just for comments -- it's not a real answer.

Which version of Arduino IDE? Which Operating System? Mine eventually discovers a a device that is flashed with OTA support added - usually takes less than a minute

1.8.4 OSX -- is there maybe a refresh ports function somewhere in the IDE?

How long do you wait? Is there a later version of the ide available for Mac

I downloaded the most recent version of the IDE and this is still a problem.

I have this problem on Windows 10. I am running Arduino 1.8.5 but this problem has been on previous versions. From what I understand it is a Windows issue. But some people have what appears to be the same problem because it get assigned to IP6 rather than IP4. I'm not really familiar with the details.

I have the exact problem on various flavours of Linux with last Arduino IDE and rebooting the router seems to be the only thing I've found that can make the IP address port appear.


text:
How to make my servo slow down in it´s movement
I want to make my servo react on the data that my light sensor tells him by the amount of light that it is catching. I want the servo to go fast to the left when there is shadow/darkness and then I want it to go slowly back to the right when the light is back.
This is the code I´m now using for my 180 degrees servo.
I also want this to work on my 360 degrees servo but because I am a beginner, I can´t figure it out...
#include <Servo.h>

Servo s;

void setup() {
  // put your setup code here, to run once:
  //pinMode(9,OUTPUT);
  pinMode(A0, INPUT);
  Serial.begin(9600);
  s.attach(9);
}

void loop() {
   float l = analogRead(A0);
   Serial.print(l);
   Serial.print(" ");
   int v = map(l,0,1024,0,179);
   s.write(v);
   Serial.println(v);

}

Don't post code as a picture. Copy and paste it into your question and use correct formatting there (mark the code and press Control + K to format it as block code). 2. Don't post just images of your circuit. We are not really able to see much on these. Instead draw a schematic. You can use the internal schematics editor of this site, when you edit your question. Or, if you don't understand schematics at this point in your learning, use something easier like Fritzing. 3. Describe better, why you are not able to use a 360° servo with your code. What is happening, if you try it?

I don't really understand, what your exact target is, but you have to watch out when using a 360° servo. Some of them are actually continuous rotation servos, where you don't set the angle with the Servo.write() function, but the rotation speed (so a value of 90 would mean no movement)

your problem has nothing to do with the light sensor .... you can remove all the code that has anything to do with the sensor ...... develop the code to control the motor first ..... if you cannot get the motor to run slowly, then it is pointless to go on without changing your goal

I added the code, pictures from my circuit in the right way now.
Hope that it's better to understand and help from now.

The servo's rotation speed is controlled by its internal circuitry. Once you send it a new target position, it drives at it's maximum speed toward that position and decelerates as it approaches.
The best you can do to slow it down is to change its target stepwise, until you reach the target position, instead of setting the final target all at once. If you move it in several large steps, the motion will be jerky; if you send smaller steps at shorter intervals (so the total travel time will be same), the motion will get smoother.
If your application needs the smoothest motion possible, send it many tiny steps rapidly, again, observing your required total travel time. You should be able keep the servo constantly at (or closer to) it's approach speed.


text:
How to avoid calling multiple times Wire.begin() in libraries?
it's all in the title ; I'm developping a library and use *TwoWire pointers in this library ; but I am using an external library that calls Wire.begin(). I've seen something about TWCR register in arduino but I don't know what it is exaclty.
Thanks in advance :)

What you are interested in is this bit of the Wire library:
TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);

The important bit is the TWEN bit - TwoWire ENable.
If that bit is set in the TWCR register than Wire.begin() has been called already and you don't need to call it again:
if (TWCR & _BV(TWEN) == 0) {
    Wire.begin();
}

However, it really doesn't matter if you call it multiple times.

other thing is if you do setFrequency(400000L) and then some other library calls Wire.begin()

Just to precise, it was to avoid such problems https://github.com/esp8266/Arduino/issues/2607 I don't know if it concerns me but I'll see with the prototype

@Storca Note that that's for a completely different architecture, so the "fix" I detail above has no relevance to it. The proper place for it to be fixed would be in the Wire library. We do it properly chipKIT: https://github.com/chipKIT32/chipKIT-core/blob/master/pic32/libraries/Wire/Wire.cpp#L122 - only allow begin to run the first time it's called.


text:
Can I track 70 pressure sensors from Arduino Mega?
I am a beginner at Arduino which I just received in the mail. My understanding is my Arduino Mega has 54 digital inputs and 16 analog inputs making for 70 inputs all together. I would like to track pressure sensors which are configured to detect simply open or closed. Given I can use my analog inputs as digital inputs can I have 70 pressure sensors? My project differs from others in that I dont need to track a gradation. In regards to the mega wiring what can I do to achieve this? Will I need a separate breadboard for each pressure sensor?

It depends on what your pressure sensors are.

I am building my pressure sensors from velostat and copper tape. How about for arguments sake we say I am using something out of the box that is either simply open or closed. I can adapt the sensor to meet my needs. Hypothetically can I connect all the sensors to digital inputs?

Yes. The sensors are just buttons.

Thanks for the commentary. In my literature i see a complex wiring scheme for a button. Can you tell me the wiring scheme?

IO pin to button. Button to GND. Turn on internal pullup. Nothing can be simpler.

In my literature i see a complex wiring scheme for a button. ... please share the literature if you can

how are the sensors arranged? .... what is the distance between the sensors? ... are they in any kind of groups? .... you could use a matrix keypad arrangement of 8x10, for example. ... then you would only require 7 connections to the arduino

also be aware, that you would need some I/O pins to "present" whatever you get from those sensors. And that probably 2 of that 70 I/O pins would be connected to your computer, while programming/debugging your code (you can output the results there as well, but you may want to send the results out in other way, say I2C (so more 2 I/O pins) to manipulate something to beep or blink or so, when some sensors are pressed.). Should I need to read exactly 70 inputs (or even more) for just 0/1, I would use some shift-registers for all inputs and poll them with just 3 pins, having rest free for outputs