body:
I want to build a line follower car, but I dont have Infrared sensors, so want to run the car, without sensors as a test

I have Motor Driver on top of Arduino UNO R3, all connections as expected, but all wheels are not spinning. I have no idea on which one is Motor1, 2,...

Code: https://create.arduino.cc/projecthub/adamsstephen/controlling-an-l9100-motor-driver-board-using-arduino-cc5618#toc-step-1--placing-electronics-0

    int Motor[8] ; // Array for all Motor Output pins, one more than required

    void setup() {
      Motor[1] = 4; // Set output numbers for ports
      Motor[2] = 5;
      Motor[3] = 6;
      Motor[4] = 7;
      Motor[5] = 8;
      Motor[6] = 9; // Set up Port for LED on Head of Arm.
      Motor[7] = 10; // Forward / Reverse selection for ALL motors
      // Switch connected to GND and A0, to locally turn off motors while testing.
      pinMode(Motor[1], OUTPUT); // Open Port to operate Motor on Pincers Forward = In Reverse = Out
      pinMode(Motor[2], OUTPUT); // Open Port to operate Motor Up= High  Reverse = Down
      pinMode(Motor[3], OUTPUT); // Open Port to operate Motor Forward = Forward Reverse = Backward
      pinMode(Motor[4], OUTPUT); // Open Port to operate Motor Wrist Forward = Up Reverse = Down
      pinMode(Motor[5], OUTPUT); // Open Port to operate Motor base Rotate Forward = Right Reverse = Left
      pinMode(Motor[6], OUTPUT); // Open Port to operate LED on head of Arm HIGH = ON LOW = OFF
      pinMode(Motor[7], OUTPUT); // Open Port for Forward / Reverse selection for ALL motors
    }
    void loop() {
        digitalWrite(Motor[6], LOW); // Turn off LED.
        if (analogRead(A0)< 1){ // switch ON
        digitalWrite(Motor[1], HIGH); // Turn on Motor 1. HIGH turns it on! Pincers
        digitalWrite(Motor[7], LOW); // HIGH is Forward, Reverse is OFF.
       Serial.println(analogRead(A0));
    }
        if (analogRead(A0) > 200  ){    // switch OFF
        digitalWrite(Motor[1], LOW); // Turn on Motor 1. HIGH turns it on!
        digitalWrite(Motor[7], LOW); // HIGH is Forward, Reverse is OFF.
       Serial.println(analogRead(A0));
    }
        delay(200); // debounce the switch action
    }

I commented the whole loop(), still some wheels are spinning. how is that possible? How can I know - which one is Motor1 ,...M4 and the corresponding Arduino pin numbers.
I want to spin all 4 wheels/ dc motors

title: Arduino - line follower car

Answers: 0


body:
I have been experimenting with pwm dimming using TIP120 on various high powered LED's, and have noticed a marked drop in the top level brightness compared to original connection without the tip 120 in line.
For instance a 70w panel connected with heavier gauge cable (not using jumper cables) no longer reaches full brightness with pwm set too full.
im using tasmota on a nodemc8266.
Is there something inherent the hardware set up causing the loss that I am missing or is there a software limitation with PWM?
curious

thanks

title: Losing top brightness when using tip120 and PWM with 70w LED panel

Answers: 1

body: Replace the TIP120 with a Low Rds N-channel MOSFET. Look at AOD508 or AOD514 for example, very low Rds, so it will develop very little voltage drop as the current increases.


body:
I'm trying to implement a Mobile Network (only) for the ESP32 using Arduino IDE. So to be able to connect to website up/download files etc. I need to be able to handle various HTTP PUT/GET/POST requests. However, the available libraries seem to always rely on additional WiFi related libraries. I don't want to have to load those as well, as they are quire bloated and not needed for my use scenario.

What options do I have for minimalist HTTP request libraries that does not rely on WiFi or BT or ETH?

title: Is there a simple HTTP(S) library that doesn't rely on WiFi?

Answers: 1

body:
The TinyGSM library implements Arduino networking Client base class over GSM modem's AT commands. The library is available in Library Manager.
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/St4IT.png


body:
I am trying to create an if statement that only runs once, the very first time the void loop is started and switches to another code after that. But the following only executes stepper1a(). Any help would be great. Thx !

<!-- language-all: lang-c++ -->

    int var;
    int var2;
    bool executed = false;

    const int M1dirpin = 4; //Stepper Dir Pin
    const int M1steppin = 5; //Stepper Step Pin

    void setup() {

    pinMode(A2,INPUT);
    pinMode(M1dirpin,OUTPUT);
    pinMode(M1steppin,OUTPUT);
    Serial.begin(9600);

    }

    void stepper1() {
      int j;
        delayMicroseconds(10);
        digitalWrite(M1dirpin,HIGH);
      for(j=0;j<=200;j++){
        digitalWrite(M1steppin,LOW);
        delayMicroseconds(10);
        digitalWrite(M1steppin,HIGH);
        delay(2);
      }
    }

    void stepper1a() {
      int j;
        delayMicroseconds(10);
        digitalWrite(M1dirpin,HIGH);
      for(j=0;j<=1600;j++){
        digitalWrite(M1steppin,LOW);
        delayMicroseconds(10);
        digitalWrite(M1steppin,HIGH);
        delay(2);
      }
    }

    void loop() {

    if (executed == false) {
    var = analogRead(A2);
    delay(10);
    if (var > 500) {
      stepper1a();
      delay(2000);
      executed = true;
      Serial.println("turned 1600");
      Serial.println(executed);
      }
    else if (executed == true) {
     var2 = analogRead(A2);
    delay(10);
    if (var > 500) {
      stepper1();
      delay(2000);
      Serial.println("turned 200");
    }
    }
    }
    }

Updated void loop:

    void loop() {

        static bool yes_we_did_the_one_time_job = false;

        if (yes_we_did_the_one_time_job) {
            var = analogRead(A2);
            delay(10);
            if (var > 500) {
                stepper2();
                delay(2000);
                Serial.println("turned 1600");
            }
        }
        else {
            var2 = analogRead(A2);
            delay(10);
            if (var > 500) {
                stepper1();
                delay(2000);
                Serial.println("turned 200");
                yes_we_did_the_one_time_job = true;
            }
        }
    }
This works now, thx !!!:

    void loop() {
      static bool yeswedid = false;

      if(yeswedid) {
        if(analogRead(A2) > 500) {
        stepper1();
        stepper2();
        }
      }
      else {
        if(analogRead(A2) > 500) {
        stepper1();
        yeswedid = true;
      }

      }
    }

title: Execute code only once

Answers: 2

body:
Generic solution:

```c++
void loop() {
    static bool yes_we_did_the_one_time_job = false;
    if (yes_we_did_the_one_time_job) {
        do_the_other_jobs();
    } else {
        do_the_one_time_job();
        yes_we_did_the_one_time_job = true;
    }
}
```

body:
If you have any code you want to run only once at the beggining of your program you can use the `setup()` method. It can actually do much more than just setting up pins and default values.

The code of main function of Arduino ([main.cpp][1]) looks like this:

    int main(void)
    {
     //(...) I cut some stuff from here

     setup();

     for (;;) {
      loop();
      if (serialEventRun) serialEventRun();
     }

     return 0;
    }

As you can see `setup()` is just a method and it can do almost exactly the same things as `loop()`.

The `setup()` method can actually contain a `for(;;)` loop that will stop the program from running the `loop()` method. From inside it you can check the sensor value and `break` from it when condition is met.

    void setup()
    {
      for (;;)
      {
        var = analogRead(A2);
        delay(10);
        if (var > 500) {
          stepper1();
          delay(2000);
          Serial.println("turned 200");
          break;
        }
      }
    }

in this case the `loop()` is very simple:

    void loop()
    {
      var = analogRead(A2);
      delay(10);
      if (var > 500)
      {
        stepper2();
        delay(2000);
        Serial.println("turned 1600");
      }
    }

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/main.cpp


body:
I am trying to use two "infrared obstacle avoidance modules" to work with the following sketch.  From all my research, I believe, a case statement is my best option because, (I understand) the sketch will not continue until the case is satisfied, however, I'm getting a weird outcome. When using two sensors with sketch below, the leds blink in an alternating pattern without any near the ir sensors.

If I use only one module the led will light until the sensor sees something, then the led turns off for the programmed delay then turns back on.

The outcome I'm looking for is eventually three modules, that will randomly light, when one lights it waits until something breaks the beam, then another will light and wait...
Does anyone have any ideas how to make this work?

    int ledselect;
    int led1 = 2;
    int led2 = 3;
    int ir1 = 4;
    int ir2 = 5;
    int s1 = A0;
    int s2 = A1;

    void setup() {
      Serial.begin(9600);
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(ir1, OUTPUT);
      pinMode(ir2, OUTPUT);
      pinMode(s1, INPUT);
      pinMode(s2, INPUT);

    }
    void loop() {
      ledselect = random(2);
      switch (ledselect) {

        case 0:
          digitalWrite(led1, HIGH);
          digitalWrite(ir1, HIGH);
          delay(50);
          while (analogRead(s1) >= 100)
          {
            delay(50);
            digitalWrite(led1, LOW);
            digitalWrite(ir1, LOW);
          }
          break;

        case 1:
          digitalWrite(led2, HIGH);
          digitalWrite(ir2, HIGH);
          delay(50);
          while (analogRead(s2) >= 100)
          {
            delay(50);
            digitalWrite(led2, LOW);
            digitalWrite(ir2, LOW);
          }
          break;
      }
    }

title: Using case statement with IR emitter reciever

Answers: 1

body:
What happens is:

1. A random number is selected
2. A light goes on
3. It goes off when nothing is near (assuming a low value of an analog sensor means nothing near?)
4. The same light or another light goes on (depending on the random led)
5. Continue with 3.

Some reasons why this might fail:

- Check the value (should it be higher or lower than 100?)
- Maybe the sensor is not so accurate and sometimes give 0 or max values which are incorrect. To change this, read multiple times the sensor and take the average, or remove the lowest and highest few (to remove spikes) and take the average.

**UPDATE**

The body of the `case` statements are almost equal, make it a function called from both `case` statements:

Your code will look like:

    void loop() {
      ledselect = random(2);
      switch (ledselect) {
        case 0:
          process(led1, ir1, s1);
          break;

        case 1:
          process(led2, ir2, s2);
          break;
      }
    }

    void process(int led, int sw, int ir)
    {
      digitalWrite(led, HIGH);
      digitalWrite(ir, HIGH);
      delay(50);
      while (analogRead(sw) >= 100)
      {
        delay(50);
        digitalWrite(led, LOW);
        digitalWrite(ir, LOW);
      }
    }

If you use the ternary operator ( x ? y : z, meaning if x than y else z), than your `loop` function will be:

    void loop() {
      ledselect = random(2);
      process(ledselect == 0 ? led1 : led2,
              ledselect == 0 ?  ir1 :  ir2,
              ledselect == 0 ?   s1 :   s2);
    }

An even more elegant way, is to use an array for the parts (not sure what better name can be), instead of all variables naming 0 and 1, put them in arrays, and you get the following code below. If you make more parts, you just have the change the beginning of the code.

    int ledselect;

    const int NrOfParts = 2;

    int leds     [NrOfParts] = {  2 , 3 };
    int irs      [NrOfParts] = {  4,  5 };
    int switches [NrOfParts] = { A0, A1 };

    void setup() {
      Serial.begin(9600);
      for (int part = 0; part < NrOfParts; part++)
      {
        pinMode(leds    [part], OUTPUT);
        pinMode(irs     [part], OUTPUT);
        pinMode(switches[part],  INPUT);
      }
    }

    void loop()
    {
      ledselect = random(2);
      process(leds[ledselect], irs[ledselect], switches[ledselect]);
    }

    void process(int led, int sw, int ir)
    {
      digitalWrite(led, HIGH);
      digitalWrite(ir, HIGH);
      delay(50);
      while (analogRead(sw) >= 100)
      {
        delay(50);
        digitalWrite(led, LOW);
        digitalWrite(ir, LOW);
      }
    }

**Update 2**

An even better way is to create a structure (so you keep all information of one 'part' together).

This solution uses the & (dereference) operator, meaning it is like a variable pointing to a part.

    int ledselect;

    const int NrOfParts = 2;

    struct Part
    {
      int led;
      int ir;
      int sw;
    };

    Part _parts[NrOfParts] =
    {
      { 2, 4, A0 },
      { 3, 5, A1 }
    };

    void setup() {
      Serial.begin(9600);
      for (int partNumber = 0; partNumber < NrOfParts; partNumber++)
      {
        Part& part = _parts[partNumber];
        pinMode(part.led, OUTPUT);
        pinMode(part.ir , OUTPUT);
        pinMode(part.sw ,  INPUT);
      }
    }

    void loop()
    {
      process(_parts[random(2)]);
    }

    void process(Part& part)
    {
      digitalWrite(part.led, HIGH);
      digitalWrite(part.ir, HIGH);
      delay(50);
      while (analogRead(part.sw) >= 100)
      {
        delay(50);
        digitalWrite(part.led, LOW);
        digitalWrite(part.ir, LOW);
      }
    }


body:
I have a problem using a servo and a GPS board at the same time on an Arduino Uno.

For the servo, I use the following code:
<!-- language-all: lang-cpp -->
```
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}
void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}
```

For the GPS module, I follow the guidance on [this webpage describing the NEO-6M GPS Module](https://randomnerdtutorials.com/guide-to-neo-6m-gps-module-with-arduino/)

```
#include <SoftwareSerial.h>

// The serial connection to the GPS module
SoftwareSerial ss(4, 3);

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

void loop(){
  while (ss.available() > 0){
    // get the byte data from the GPS
    byte gpsData = ss.read();
    Serial.write(gpsData);
  }
}
```

I combine these two code blocks into one *.ino file (combining the declarations, placing all the setup portions in the ```void setup(){...}``` function and the rest in the ```void loop(){...}``` part).

Here is the problem:
Each block by itself runs fine. The "GPS block" returns GPS messages and the "Servo block" runs smoothly through its position sweep. However, when this code is combined the servo starts to act erratically and "jerks" back and forth.
After some testing, it appears that starting the serial connection (```ss.begin(9600);```) changes the behavior of the servo control pin (here 9) and it looses its pulse width modulating (PWM) capability. The servo then starts to "jerk" to random positions.

Does anybody have insight into this phenomenon? Is there a way to operate the servo and the GPS module together?

Here is a functional code block that sweeps through the servo positions smoothly, by commenting out the line ```//ss.begin(GPSBaud);``` and replicates the erratic behavior by uncommenting the same line ```ss.begin(GPSBaud);```.

```
#include <Servo.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

static const int RXPin = 4, TXPin = 3;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(GPSBaud);
  //ss.begin(GPSBaud);
}

void loop() {
  for (pos = 20; pos <= 160; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 160; pos >= 20; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

```

title: Trouble operating Servo and GPS at the same time

Answers: 0


body:
I like to collect all possible interrupt and relay them to an alternative handler interrupt table what the user can set.

In order to do this i have to:
   1) collect all/any interrup request
   2) identify where is the interruption came from
   3) relay the call to another table the user pointed.

If you familiar with interrupts you know if you registers a single function to all interrupt handler there's no way to idenfity the source of the interrupt.
But registering unique interrupt handler that carries the information of the source and calls another function to dispatch call, for each interrupt is a code space wasting. Eg.: the atmega328 has 24 interrupt handlers. Each of the is compiled with the avr-gcc consumes 76 bytes.

----

But i have and idea how it is possible to register one handler function and identify the source:

    00000000 <__vectors>:
       0: 0c 94 34 00  jmp 0x68 ; 0x68 <__ctors_end>
       4: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
       8: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>
       c: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__bad_interrupt>

If i define an interrupt handler (even if it can fit the 4 byte space) a jmp instruction is placed. If it can be replaced to eg.: call 0xa2 (which can fit in 4 bytes), is can be used to identify the interrupt source address.

Because `call` stores the return address, the function started at 0xa2 can read back that address and therefor idenfity the caller. Then add an extra `pop` (pop the stack address accumulated by the `call` at the interrup table) and `reti` (to return as like from an interrupt handler) after the function body.

If this can work theorically, to achieve this only one question remains:

How can i replace the `jmp` instructions to `call` in interrupt table?

title: Atmega collecting and relaying interrupt calls

Answers: 2

body:
The interrupt vector table is provided by [the C runtime][crt]. It is
not _normally_ intended to be overridden by user code. You can, however,
do it, if you replace the whole C run time by your own, and compile your
sketch with the `-nostartfiles` option.

I have played this game once I was trying to accurately assess interrupt
latencies. See the details in [this answer][answer] (the answer is long,
but you can go right to the last section).

[crt]: http://svn.savannah.nongnu.org/viewvc/*checkout*/avr-libc/trunk/avr-libc/crt1/gcrt1.S
[answer]: https://arduino.stackexchange.com/a/8926

body:
The answer i've accepted is the proper answer for the problem i asked.
However replacing the C runtime requires to attach and maintain a lot of crt.S files oiginally related to the GCC. To avoid this i "slept several times over this prolem" and came out another solution.

After compiling the host application that have to redirect the interrupt calls
([script source][1]). I wrote a utility that rewrites every interrupt jumps at the beginning of the ihex ([source][2]) with an offset to the target application.

Ok this solution doesn't collect and identify and relay the incoming interrupts, just relay them. As far as there's no target application, nothing enables these interrupts and cause fault. This solution also doesn't use extra code space.

  [1]: https://github.com/danko-david/uartbus/blob/master/source/uc/bootloader/compile_and_upload.sh
  [2]: https://github.com/danko-david/uartbus/blob/master/source/java/uartbus/src/main/java/eu/javaexperience/electronic/IhexCli.java


body:
I uploaded regular pass through code for Serial and SoftwareSerial to communicate with my AT command based module.

Writing to SoftwareSerial seems to be working but reading not.
As I write "AT", the module returns me "-5" which should be "OK".

As I write "asdad" the module returns something similar ot "invalid syntax" but very messy.
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>
    SoftwareSerial ss(rx, tx);

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

    void loop() {
      while (Serial.available()) ss.write(Serial.read());
      while (ss.available()) Serial.write(ss.read());
    }

title: Why the SoftwareSerial is not working properly on Arduino Pro Mini 3v3?

Answers: 2

body:
You may get better results if you do not nest the read and write function calls as you did.  That is, read everything then write everything.

The reason for this is that [softwareserial.read()][1] returns 1 character.  If you immediately turn around and pass that character to [softwareserial.write()][2] you will devote the resources of the processor to sending that character.  In the meantime if another character is sent to the processor the processor will not see it or will only see part of it.

That said, you will likely get better results if you use a better embedded processor with dedicated serial port hardware for each port your project requires. Such as the [Mega 2560][3] processor on the [Arduino Mega][4].

Moving away from a cheap processor to one with enough hardware is a valid solution. Because, with another hardware serial port, the processor is only needed to read & write a character to & from the hardware using one command for each of these operations, not waste time reading & waiting each bit of a charater.  A hardware serial port or [UART][5] can cut the effort of receiving & sending a character by the processor by more than an order of magnitude.

  [1]: https://www.arduino.cc/en/Reference/SoftwareSerialRead
  [2]: https://www.arduino.cc/en/Reference/SoftwareSerialWrite
  [3]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf
  [4]: https://store.arduino.cc/usa/mega-2560-r3
  [5]: https://en.wikipedia.org/wiki/Universal_asynchronous_receiver-transmitter

body:
With SoftwareSerial 9600 baud is about the maximum rate you can reliably run at when using a 5V 16MHz Arduino. You are using an 8MHz one at 3.3V, so you can expect that speed cap to be halved.

Don't use SoftwareSerial. Ever. Full stop. There is no call to ever use it. If you don't have enough real UART ports on your board then you are using the wrong board. Don't just use a board because it's the one that everyone uses. Look at what you want to do and then pick a suitable board that fits your needs. There are many many 3.3V boards available with multiple (or even one single spare) UARTs - for example the Fubarino Mini, the Teensy 3.x, Any number of ESP32 based boards - all with a similar footprint to the Pro Mini, and with a huge amount more power to boot.


body:
I have two NodeMCU which have to send data to a server (also a NodeMCU). I want to acheive speed of atleast 10Hz because the sensor sends it at that rate. I have  tried websockets and couldn't get transfer rate of more than 1Hz and the data was being put in the buffer.

Any ideas how could I can acheive speed of 10Hz via WiFi?

Thanks for any help.

title: How to acheive fast and reliable communication between NodeMCUs?

Answers: 1

body:
WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.

If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read from the WiFiClient object on the other side.

client socket

    if (client.connect(serverIP, PORT)) {
      client.print("request\n");
      String response = client.readStringUntil('\n');
      Serial.println(response);
      client.stop();
    }

server side

    WiFiClient client = server.available();
    if (client && client.connected()) {
      String request = client.readStringUntil('\n');
      Serial.println(request);
      client.print("response\n");
      client.stop();
    }


body:
I'm new to Arduino and electronics in general. I'm trying to connect the Capacitive moisture sensor v1.2 to my arduino and get values in the serial plotter.
I connected the VCC to 5V, GRD to ground and AOUT to A0. However, I keep only getting values of 1, 2 or 3, while they are supposed to be in the hundreds. What could be a cause of such a problem. I'm using the chinese Wavgat board, but I have previously connected the moisture and humidity sensors and they displayed values normally.

Here's the code I used:

```
int val;
void setup() {
  Serial.begin(9600);
}

void loop() {
  val = analogRead(A0);
  Serial.println(val);
  delay(200);
}

title: Capacitive Moisture sensor only shows values 1 and 2

Answers: 0


body:
I have a ESP8266 on a Wemos D1 mini board. Simple "Rainbow with FastLED" animation. Shouldn't do much but the board gets so hot I can't touch it and it drains a 2500mAh battery in less than an hour.

Any idea what I'm doing wrong? Especially as a comparable micropython implementation just doesn't get that hot and the same battery keeps for about 5 hrs...

Here's the code
<!-- language-all: lang-cpp -->

    #define FASTLED_ALLOW_INTERRUPTS 0
    #include "FastLED.h"
    #include <EEPROM.h>

    // How many leds in your strip?
    #define NUM_LEDS 60
    #define DATA_PIN 13
    #define CLOCK_PIN 14
    #define COLOR_ORDER RGB
    int starthue = 0;
    int incrementer = 255/NUM_LEDS;
    CRGB leds[NUM_LEDS*2];
    int address = 0;
    int max_modes = 4;
    int colormode;

    void setup() {
      Serial.begin(9600);
      // put your setup code here, to run once:
      FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS*2);
        EEPROM.begin(512);
      colormode = EEPROM.read(address);
      Serial.println(colormode);
      int new_mode = (colormode == max_modes) ? 1 : ++colormode;
      Serial.println(new_mode);
      new_mode = (colormode == 0) ? 1: new_mode;
      Serial.println(new_mode);
      EEPROM.write(address, new_mode);
      EEPROM.commit();
      EEPROM.end();
    }

    void rainbow_mid(int howfast) {
      while (true) {
        fill_rainbow(leds, NUM_LEDS, starthue, incrementer);
        for (int i =0; i< NUM_LEDS; i++) {
          leds[NUM_LEDS-i-1] = leds[i];
          leds[NUM_LEDS*2-i-1] = leds[i];
        }
        FastLED.show();
        delay(howfast);
        starthue++;
      }
    }

    void rainbow(int howfast) {
      while (true) {
        fill_rainbow(leds, NUM_LEDS, starthue, incrementer);
        //addGlitter(80);
        for (int i =0; i< NUM_LEDS; i++) {
          //leds[NUM_LEDS-i-1] = leds[i];
          leds[NUM_LEDS*2-i-1] = leds[i];
        }
        FastLED.show();
        delay(howfast);
        starthue++;
      }

    }

    void loop() {
      switch(colormode) {
        case 1: rainbow_mid(10); break;
        case 2: rainbow_mid(50); break;
        case 3: rainbow(10); break;
        case 4: rainbow(50); break;
      }

    }

title: Insane heat development with ESP8266

Answers: 1

body:
the heat is from the supply lines of board.

it's not the chip itself, as if it gets hot like that the chip should be destroyed.
it seems you have connected 60 LEDs strip to the board and you provide it's supply from the board's supply line. so the lines get hot, and the board gets hot too.
so the heat is not from the chip. its from power supply tracks on the PCB.

use another power source for the LED strip.


body:
I'm working on a group project to involving the creation of an in-house library using the Arduino IDE. As the Arduino IDE uses C++, the library must be a class. One of the classfields is an array of numbers. We would like it if we could specify the array length during object construction, as there are pros and cons to low and high array lengths. Is it possible to specify or change the array length during object construction?

Unfortunately, the Arduino IDE doesn't allow the usage of C++ vectors, so that's out of the question.

title: How to Specify Array Length during Object Construction within Arduino IDE?

Answers: 3

body:
Some example solutions can be found in [this stackexchange question/answer][1].  The accepted answer used this code:

    private int size;

    private String words[];

    public WordStore(int n){
         words =new String[n];
    }

  [1]: https://stackoverflow.com/questions/20425361/set-array-length-to-value-passed-to-constructor

body:
As suggested in [st2000’s
answer](https://arduino.stackexchange.com/a/66916/7508), you could use
dynamic allocation but, if you do that, do not forget to free the
allocated memory in the destructor. Otherwise you have a nasty memory
leak and your program will not live long:

```c++
class MyClass {
public:
    MyClass(size_t length) : arrayLength(length) {
        theArrayOfNumbers = new int[arrayLength];
    }
    ~MyClass() {
        delete[] theArrayOfNumbers;
    }
private:
    const size_t arrayLength;
    int *theArrayOfNumbers;
};
```

One issue with this approach is that dynamic allocation is no very
friendly to the limited amount of memory you have in a microcontroller.

A safer option would be to use a template class instead. This way the
array is statically allocated:

```c++
template <size_t arrayLength>
class MyTemplateClass {
    int theArrayOfNumbers[arrayLength];
};
```

One caveat with this approach is that the users of the library may not
be comfortable with the syntax for instantiating a template. You will
have to provide clear examples in the documentation. Another issue is
that the array size will have to be a compile-time constant.

body:
Another way is for the caller to provide the memory as a pointer to enough bytes for 'N' objects (cast, if necessary, as a pointer to the required type), and the number, 'N' of such objects. This gives the caller the choice of whether to allocate statically or dynamically.

It looks like you want an array of ints. So you'd allocate an array (statically, in my example, but you could choose whichever best fits your application):

    int memArray[N];
    // ...
    myClass(N, memArray&);

I avoid allocating memory from the heap, but someone else might have a different preference or a situation that requires it; this technique lets the library work for either.


body:
I have programmed a small software to control an LED strip using an esp. I've written a web app which sends a request to the esp which then applies the color. So far everything works, but I've got a weird problem:

When I'm running the software on the NodeMCU, everything is fast and snappy, the web app takes 500ms at max to load. When I'm running the software from an ESP-12f [(schematic)](https://raw.githubusercontent.com/c-klinger/esp8266-arduino-wifirgb/master/schematics/wifirgb_schematics.png), it takes way longer to load, about 5 seconds. Sometimes it doesn't even load at all.

Another thing that's weird: I've got two ESP-12f, one of those won't even load very often.

I also have the feeling that the "normal" esps run hotter than the nodemcu, but that could be because they are close to the voltage regulator which gets hot

```c++
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ArduinoOTA.h>
#include <colorWheel.h>
#include <web_iro_js.h>

#define RED_LED 14
#define GREEN_LED 12
#define BLUE_LED 5

#define BUILTIN_LED 2

const char* ssid = "---";
const char* password = "---";

IPAddress ip(192,168,2,111);
IPAddress gateway(192,168,2,1);
IPAddress subnet(255,255,255,0);
ESP8266WebServer server(80);

int brightness_red      = 0;
int brightness_green    = 0;
int brightness_blue     = 0;

int presets[4][3]       = {{255,119,46},{46,0,39},{0,115,23},{0,0,0}};

boolean blinking        = false;
boolean fading          = false;
boolean jumping         = false;

int blinkDelay[]        = {50, 145, 240, 335, 430, 525, 620, 715, 810, 905};
int speedPosition       = 4;

int fadeOrder[]       = {RED_LED, GREEN_LED, BLUE_LED};
int lastFade          = 0;    //0~2, refers to fadeOrder[]
int thisFade          = 1;    //0~2, refers to fadeOrder[]
int fadeSpeed[]       = {1, 1, 1, 2, 3, 4, 5, 5, 7, 9};

boolean blinkHelper = false;

void handleRequest();
void handleGet();
void setupOTA();
void connectToWiFi();
void turnOff();
void turnOn();
void applyColor();
void applyPreset();
void blink();
void fade();
void jump();

void setup() {
    Serial.begin(115200);
    delay(10);

    analogWriteRange(255);

    pinMode(BUILTIN_LED, OUTPUT);
    digitalWrite(BUILTIN_LED, LOW);

    pinMode(RED_LED, OUTPUT);
    pinMode(GREEN_LED, OUTPUT);
    pinMode(BLUE_LED, OUTPUT);

    analogWrite(RED_LED, 0);
    analogWrite(GREEN_LED, 0);
    analogWrite(BLUE_LED, 0);

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

    WiFi.begin(ssid, password);
    WiFi.config(ip, gateway, subnet);

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

    setupOTA();

    server.on("/request", handleRequest);
    server.on("/get", handleGet);

    server.on("/", HTTP_GET, []() {
        server.send(200, "text/html", GUI);
    });

    server.on("/iro.min.js", HTTP_GET, []() {
        server.send_P(200, "application/javascript", IRO_JS);
    });

    server.begin();

    Serial.println("Setup done");
    pinMode(BUILTIN_LED, OUTPUT);
    digitalWrite(BUILTIN_LED, HIGH);
}

void loop() {
    if (WiFi.status() != WL_CONNECTED) {
        //Serial.println("no connection");
        connectToWiFi();
    }
    ArduinoOTA.handle();
    server.handleClient();

    if (blinking) {
        blink();
    }

    if (fading) {
        fade();
    }

    if (jumping) {
        jump();
    }

    if (blinking || fading || jumping) {
        delay(blinkDelay[speedPosition]);
    } else {
        delay(20);
    }
}

void handleRequest() {
    if (!server.hasArg("mode")) {
        Serial.println("no mode specified");
        server.send(400, "text/plain", "no mode specified");
        return;
    }

    String request = server.arg("mode");

    if (request.equals("color")) {
        fading = false;
        jumping = false;
        applyColor();

    } else if (request.equals("preset")) {
        fading = false;
        jumping = false;
        applyPreset();

    } else if (request.equals("blink")) {
        if (blinking) {
            blinking = false;
        } else {
            turnOff();
            fading = false;
            jumping = false;
            blinking = true;
        }
        server.send(200, "text/plain", "applied blinking");
    } else if (request.equals("fade")) {
        if (fading) {
            fading = false;
        } else {
            turnOff();
            blinking = false;
            jumping = false;
            fading = true;
        }
        server.send(200, "text/plain", "applied fading");
    } else if (request.equals("jump")) {
        if (jumping) {
            jumping = false;
        } else {
            turnOff();
            blinking = false;
            fading = false;
            jumping = true;
        }
        server.send(200, "text/plain", "applied jumping");
    } else if (request.equals("speed")) {
        if (!server.hasArg("newSpeed")) {
            server.send(400, "text/plain", "no speed specified");
            return;
        }
        int speed = server.arg("newSpeed").toInt();
        speedPosition = 9 - speed;
        server.send(200, "text/plain", "applied speed");
    } else {
        server.send(400, "text/plain", "argument not found");
    }
}

void handleGet() {
    if (!server.hasArg("arg")) {
        Serial.println("no argument specified");
        server.send(400, "text/plain", "no argument specified");
        return;
    }
    String request = server.arg("arg");
    String answer = "";

    if (request.equals("current")) {
        answer += (String(brightness_red));
        answer += (";" + String(brightness_green));
        answer += (";" + String(brightness_blue));
        answer += (";" + String(speedPosition));

    } else if (request.equals("presets")) {
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 3; j++) {
                answer += String(presets[i][j]);
                answer += ";";
            }
        }
    } else {
        server.send(400, "text/plain", "argument not found");
    }
    server.send(200, "text/plain", answer);
}

void setupOTA() {
    ArduinoOTA.setHostname("ESP8266");
    ArduinoOTA.setPassword("password");

    ArduinoOTA.onStart([]() {
        Serial.println("Start");
    });
    ArduinoOTA.onEnd([]() {
        Serial.println("\nEnd");
    });
    ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
        Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
    });
    ArduinoOTA.onError([](ota_error_t error) {
        Serial.printf("Error[%u]: ", error);
        if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
        else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
        else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
        else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
        else if (error == OTA_END_ERROR) Serial.println("End Failed");
    });
    ArduinoOTA.begin();
}

void connectToWiFi() {
  Serial.println("WiFi connection lost, reconnecting");
  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet);

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

void applyColor() {
    Serial.println("applying new color ");
    brightness_red = 0;
    if (server.hasArg("red")) {
        brightness_red = server.arg("red").toInt();
    }

    brightness_green = 0;
    if (server.hasArg("green")) {
        brightness_green = server.arg("green").toInt();
    }

    brightness_blue = 0;
    if (server.hasArg("blue")) {
        brightness_blue = server.arg("blue").toInt();
    }

    turnOn();
    server.send(200, "text/plain", "applied new color");
}

void applyPreset() {
    if (!server.hasArg("index")) {
        Serial.println("no index specified");
        server.send(400, "text/plain", "no index specified");
        return;
    }

    int index = server.arg("index").toInt();

    if (server.hasArg("save")) {
        Serial.println("saving preset");
        presets[index][0] = brightness_red;
        presets[index][1] = brightness_green;
        presets[index][2] = brightness_blue;
        server.send(200, "text/plain", "preset saved");
    } else {
        Serial.println("applying preset");
        brightness_red = presets[index][0];
        brightness_green = presets[index][1];
        brightness_blue = presets[index][2];

        turnOn();
        server.send(200, "text/plain", "preset applied");
    }
}

title: Same software on single ESP-12f slower than on NodeMCU

Answers: 0


body:
<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/jZGKs.png)

<!-- End schematic -->

In above schematic;

1. what value should R1 have? is it even needed?
2. do we need that pull down resistor(R2)? if yes, 10K is enough or we need higher value like 100K resistor there?

[IRLZ44N DATASHEET][1]

  [1]: https://www.infineon.com/dgdl/irlz44npbf.pdf?fileId=5546d462533600a40153567217c32725

title: How to connect IRLZ44N to Arduino?

Answers: 1

body:
1. It's better with resistor so output driver isn't stressed to its maximum limits. Gate has its capacitance so it's better to limit charge/discharge current for such weak source

2. As the gate is basically capacitor, it has really big input impedance. Without pull down resistor it'll be catching all kinds of EMI (electro-magnetic interferences). So 10k is fine. The 100k might be less unreliable if the mcu output is not active (boot/reset)


body:
I create applications for a computer that is to be used to control the robot arm. I wanted to make the first attempt to run the application not on the motor, but on the diode and check if it will change its brightness depending on the position of the slider. I wrote an application in Qt that sends thongs to Arduino, and Arduino I read and converts to int. The problem is that although the slider is set to 0, the Arduino does not show it, often the figures do not agree too often (often too small), also when I suddenly move the number slider all the time count towards the front instead of back.

Arduino code:

    String br;

    void setup()
    {
      Serial.begin(9600);
      pinMode(9, OUTPUT);
    }

    void loop()
    {
       while (Serial.available()>0)
     {
        br = Serial.readString();
        analogWrite(9, br.toInt());
        Serial.println(br.toInt());
     }
    }

Qt code:

    void MainWindow::on_horizontalSliderGrip_sliderMoved(int position)
    {
       this->sendMessageToDevice(QString::number(position) + "n");
       qDebug() << "Grip: " << QString::number(position);
    }

    void MainWindow::sendMessageToDevice(QString message)
    {
       if(this->device->isOpen() && this->device->isWritable())
       {
           //this->addToLogs("Sending information to the device " + message);
           this->device->write(message.toStdString().c_str());
       }
       else
       {
           this->addToLogs("I can not send a message. The port is not open!");
       }
    }

  [![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/OLlyu.png

title: From Strings to int problem

Answers: 1

body:
As Majenko wrote in his comment, your problem lies with `Serial.readString()`. It is generally not a good way to handle Serial data. It reads data from the Serial interface, until the timeout (default 1s) occurs. So it will try to read until 1 second after your last change of the slider and return the whole data as one string. `String.toInt()` will then start to read the string from the first character and convert them to an integer, until it reads a non-digit character (meaning the `n`, that you send). It stops there and returns the already converted value.

This means, that out of all the data, that was send to the Arduino, only the first value will be used. The rest get's thrown away.

Better you should use a non-blocking code, that handles the messages (numbers in your case) correctly. This is done by reading the incoming serial data byte by byte, adding them into a buffer, until a special delimiter character get's received. Then the message get's processed as a whole. After that, the next message can be read and processed. This way you don't miss any of the send values.

The special delimiter character is arbitrary; you can use any character, that does not occur in the valid data. So using the character `n` is ok here. But mostly the newline character `\n` is used, so that you can also send messages with alphanumeric characters. Most likely you already meant to use `\n`.

As an example of this serial code, you can take the `readline()` function from [Majenko's blog post][1]:

    char buf[80];

    int readline(int readch, char *buffer, int len) {
        static int pos = 0;
        int rpos;

        if (readch > 0) {
            switch (readch) {
                case '\r': // Ignore CR
                    break;
                case '\n': // Return on new-line
                    rpos = pos;
                    pos = 0;  // Reset position index ready for next time
                    return rpos;
                default:
                    if (pos < len-1) {
                        buffer[pos++] = readch;
                        buffer[pos] = 0;
                    }
            }
        }
        return 0;
    }

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

    void loop() {
        if (readline(Serial.read(), buf, 80) > 0) {
            Serial.print("You entered: >");
            Serial.print(buf);
            Serial.println("<");
        }
    }

You can convert the character buffer to an int with `atoi()` in the if statement in `void loop()` and use it for ´analogWrite()`.

  [1]: https://majenko.co.uk/blog/reading-serial-arduino


body:
I've been building an add on to my garage door opener that will allow it to be opened from the outside with a valid RFID token or from inside using push buttons.

This works as expected when first plugged in, but then after a few hours, the RFID component stops responding to swipes. The push buttons continue to allow the door to be opened, closed or halted during an action.

I'm not sure if this is  an electrical hardware issue or a code based bug, but any help is appreciated.

[![Hardware Sketch][1]][1]

    #include <AddicoreRFID.h>
    #include <SPI.h>

    #define  uchar unsigned char
    #define uint  unsigned int

    uchar fifobytes;
    uchar fifoValue;

    AddicoreRFID myRFID; // create AddicoreRFID object to control the RFID module

    // ------------
    // Open / Close Garage Door
    // ------------

    /*-------------

    Every program based on Wiring (programming language used by Arduino, and Particle devices) has two essential parts:
    setup - runs once at the beginning of your program
    loop - runs continuously over and over

    -------------*/

    // First, we're going to make some variables.
    // This is our "shorthand" that we'll use throughout the program:

    int re1 = 8                                                                                ; // Relay IN1 Blue
    int re2 = 7; // Relay IN2 Purple
    int re3 = 6; // Relay IN3 Orange
    int re4 = 5; // Relay IN4 Yellow
    int btn1 = 3;
    int btn2 = 4;
    int btn3 = 2;

    int OpenButtonState = 0;
    int CloseButtonState = 0;
    int StopButtonState = 0;

    int doorstate = 0; // 0 = "Closed", 1 = "Open"

    //--Pins for RFID

    const int chipSelectPin = 10;
    const int NRSTPD = 9;

    //Maximum length of the array
    #define MAX_LEN 16

    //End of RFID Pin Config

    void setup() {

      Serial.begin(9600);      // open the serial port at 9600 bps:
    //setup the pins to output voltage
      pinMode(re1, OUTPUT);
      pinMode(re2, OUTPUT);
      pinMode(re3, OUTPUT);
      pinMode(re4, OUTPUT);
      pinMode(btn1, INPUT);
      pinMode(btn2, INPUT);
      pinMode(btn3, INPUT);

       // start the SPI library:
      SPI.begin();

      pinMode(chipSelectPin,OUTPUT);              // Set digital pin 10 as OUTPUT to connect it to the RFID /ENABLE pin
        digitalWrite(chipSelectPin, LOW);         // Activate the RFID reader
      pinMode(NRSTPD,OUTPUT);                     // Set digital pin 9 , Not Reset and Power-down
        digitalWrite(NRSTPD, HIGH);

      myRFID.AddicoreRFID_Init();

    //setup web call functions

    //Particle.function("netopen", R1ON);
    //Particle.function("netclose", R2ON);
    //Particle.function("netstop", R3ON);

      digitalWrite(re1, HIGH); //turn off relay
      digitalWrite(re2, HIGH); //turn off relay
      digitalWrite(re3, HIGH); //turn off relay
      digitalWrite(re4, HIGH); //turn off relay

    }

    // This routine gets repeated over and over, as quickly as possible and as many times as possible, after the setup function is called.
    // Note: Code that blocks for too long (like more than 5 seconds), can make weird things happen (like dropping the network connection).  The built-in delay function shown below safely interleaves required background activity, so arbitrarily long delays can safely be done if you need them.

    void loop() {

    //Loop for RFID ----------------------------------------------------------------------

    uchar i, tmp, checksum1;
      uchar status;
            uchar str[MAX_LEN];
            uchar RC_size;
            uchar blockAddr;  //Selection operation block address 0 to 63
            String mynum = "";

            str[1] = 0x4400;
      //Find tags, return tag type
      status = myRFID.AddicoreRFID_Request(PICC_REQIDL, str);
      if (status == MI_OK)
      {
              Serial.println("RFID tag detected");
                     }

      //Anti-collision, return tag serial number 4 bytes
      status = myRFID.AddicoreRFID_Anticoll(str);
      if (status == MI_OK)
      {
              checksum1 = str[0] ^ str[1] ^ str[2] ^ str[3];
              Serial.print("The tag's number is:\t");
              Serial.print(str[0]);
                Serial.print(" , ");
              Serial.print(str[1]);
                Serial.print(" , ");
              Serial.print(str[2]);
                Serial.print(" , ");
              Serial.println(str[3]);

    //check if valid card combination
                if((str[0] == 333) && (str[1] == 444) && (str[2] == 555) && (str[3] == 666) )                   //You can change this to the first byte of your tag by finding the card's ID through the Serial Monitor
                {
                    Serial.println("\nKey fob identifed - Josh\n");

                    if(doorstate == 1) {
                      //door is already open so close
                        // Close Garage Door
                        R2ON(""); //turn on relay
                        doorstate = 0;
                        Serial.print("Relay 2 on") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        R2OFF(); //turn off relay
                        Serial.print("Relay 2 off") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                          Serial.print("Close State Button HIGH - Finished Closing Garage Door")    ;
                        Serial.println("");

                    } else {
                      //door is closed so open

                        //Open Garage Door
                        R1ON(""); //turn on relay
                        doorstate = 1;
                        Serial.print("Relay 1 on") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        R1OFF(); //turn off relay
                        Serial.print("Relay 1 off") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        Serial.print("Open State Button HIGH - Finished Opening Garage Door")    ;
                        Serial.println("");
                    }

                } else if((str[0] == 111) && (str[1] == 2222) && (str[2] == 333) && (str[3] == 444) ) {             //You can change this to the first byte of your tag by finding the card's ID through the Serial Monitor
                    Serial.println("\nCar Charge Card Identified - Josh\n");

                    if(doorstate == 1) {
                      //door is already open so close
                        // Close Garage Door
                        R2ON(""); //turn on relay
                        doorstate = 0;
                        Serial.print("Relay 2 on") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        R2OFF(); //turn off relay
                        Serial.print("Relay 2 off") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                          Serial.print("Close State Button HIGH - Finished Closing Garage Door")    ;
                        Serial.println("");

                    } else {
                      //door is closed so open

                        //Open Garage Door
                        R1ON(""); //turn on relay
                        doorstate = 1;
                        Serial.print("Relay 1 on") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        R1OFF(); //turn off relay
                        Serial.print("Relay 1 off") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        Serial.print("Open State Button HIGH - Finished Opening Garage Door")    ;
                        Serial.println("");
                    }
                } else if((str[0] == 000) && (str[1] == 11) && (str[2] == 22) && (str[3] == 333) ) {             //You can change this to the first byte of your tag by finding the card's ID through the Serial Monitor
                    Serial.println("\nCar Garage Card Identified - Charlotte\n");

                    if(doorstate == 1) {
                      //door is already open so close
                        // Close Garage Door
                        R2ON(""); //turn on relay
                        doorstate = 0;
                        Serial.print("Relay 2 on") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        R2OFF(); //turn off relay
                        Serial.print("Relay 2 off") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                          Serial.print("Close State Button HIGH - Finished Closing Garage Door")    ;
                        Serial.println("");

                    } else {
                      //door is closed so open

                        //Open Garage Door
                        R1ON(""); //turn on relay
                        doorstate = 1;
                        Serial.print("Relay 1 on") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        R1OFF(); //turn off relay
                        Serial.print("Relay 1 off") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        Serial.print("Open State Button HIGH - Finished Opening Garage Door")    ;
                        Serial.println("");
                    }
                }
                Serial.println();
                delay(1000);
      }

            myRFID.AddicoreRFID_Halt();      //Command tag into hibernation

       //End Loop For RFID  ----------------------------------------------------------------------

    OpenButtonState = digitalRead(btn1);
    CloseButtonState = digitalRead(btn2);
    StopButtonState = digitalRead(btn3);

    if (OpenButtonState == HIGH) {

      Serial.print("Open State Button HIGH - Opening Garage Door")  ;
      Serial.println("");
        //Open Garage Door
      R1ON(""); //turn on relay
      doorstate = 1;
      Serial.print("Relay 1 on") ;
      Serial.println("");
      delay(1000); // wait 1 second
      R1OFF(); //turn off relay
      Serial.print("Relay 1 off") ;
      Serial.println("");
      delay(1000); // wait 1 second
      Serial.print("Open State Button HIGH - Finished Opening Garage Door")    ;
      Serial.println("");
      }

    if (CloseButtonState == HIGH) {

      Serial.print("Close State Button HIGH - Closing Garage Door") ;
      Serial.println("");
        // Close Garage Door
      R2ON(""); //turn on relay
      doorstate = 0;
      Serial.print("Relay 2 on") ;
      Serial.println("");
      delay(1000); // wait 1 second
      R2OFF(); //turn off relay
      Serial.print("Relay 2 off") ;
      Serial.println("");
      delay(1000); // wait 1 second
        Serial.print("Close State Button HIGH - Finished Closing Garage Door")    ;
      Serial.println("");

      }

    if (StopButtonState == HIGH) {

     Serial.print("Stop State Button HIGH - Stopping Garage Door")  ;
     Serial.println("");
     // Stop
      R3ON(""); //turn on relay
      doorstate = 1;
      Serial.print("Relay 3 on") ;
      Serial.println("");
      delay(1000); // wait 1 second
      R3OFF(); //turn off relay
      Serial.print("Relay 3 off") ;
      Serial.println("");
      delay(1000); // wait 1 second
          Serial.print("Stop State Button HIGH - Finished Stopping Garage Door")    ;
      Serial.println("");

      }

      // And repeat!
    }

    int R1ON(String command) {

        digitalWrite(re1, LOW); //turn on relay
        //Particle.publish("Relay 1 on - Door Open");
        delay(1000); // wait 1 second
        digitalWrite(re1, HIGH); //turn off relay
        //Particle.publish("Relay 1 off");
    }

    void R1OFF() {
      digitalWrite(re1, HIGH); //turn off relay
        //delay(1000); // wait 1 second
    }

    int R2ON(String command) {

        digitalWrite(re2, LOW); //turn on relay
        //Particle.publish("Relay 2 on - Door Closing");
        delay(1000); // wait 1 second
        digitalWrite(re2, HIGH); //turn off relay
        //Particle.publish("Relay 2 off");
    }

    void R2OFF() {

        digitalWrite(re2, HIGH); //turn on relay
        //delay(1000); // wait 1 second
    }

    int R3ON(String command) {

        digitalWrite(re3, LOW); //turn on relay
        //Particle.publish("Relay 3 on - Door Stopped");
        delay(1000); // wait 1 second
        digitalWrite(re3, HIGH); //turn off relay
        //Particle.publish("Relay 3 off");
    }

    void R3OFF() {

        digitalWrite(re3, HIGH); //turn on relay
        //delay(1000); // wait 1 second
    }

    void R4ON() {

        digitalWrite(re4, LOW); //turn on relay
        //delay(1000); // wait 1 second
    }

    void R4OFF() {

        digitalWrite(re4, HIGH); //turn on relay
        //delay(1000); // wait 1 second
    }

Updated Code 7/7/19 @20:53

    #include <AddicoreRFID.h>
    #include <SPI.h>

    //#define  unsigned char unsigned char
    #define uint  unsigned int

    unsigned char fifobytes;
    unsigned char fifoValue;

    AddicoreRFID myRFID; // create AddicoreRFID object to control the RFID module

    // ------------
    // Open / Close Garage Door
    // ------------

    /*-------------

    Every program based on Wiring (programming language used by Arduino, and Particle devices) has two essential parts:
    setup - runs once at the beginning of your program
    loop - runs continuously over and over

    -------------*/

    // First, we're going to make some variables.
    // This is our "shorthand" that we'll use throughout the program:

    int re1 = 8                                                                                ; // Relay IN1 Blue
    int re2 = 7; // Relay IN2 Purple
    int re3 = 6; // Relay IN3 Orange
    int re4 = 5; // Relay IN4 Yellow
    int btn1 = 3;
    int btn2 = 4;
    int btn3 = 2;

    int OpenButtonState = 0;
    int CloseButtonState = 0;
    int StopButtonState = 0;

    int doorstate = 0; // 0 = "Closed", 1 = "Open"

    //--Pins for RFID

    const int chipSelectPin = 10;
    const int NRSTPD = 9;

    //Maximum length of the array
    #define MAX_LEN 16

    //End of RFID Pin Config

    void setup() {

      Serial.begin(9600);      // open the serial port at 9600 bps:
    //setup the pins to output voltage
      pinMode(re1, OUTPUT);
      pinMode(re2, OUTPUT);
      pinMode(re3, OUTPUT);
      pinMode(re4, OUTPUT);
      pinMode(btn1, INPUT);
      pinMode(btn2, INPUT);
      pinMode(btn3, INPUT);

       // start the SPI library:
      SPI.begin();

      pinMode(chipSelectPin,OUTPUT);              // Set digital pin 10 as OUTPUT to connect it to the RFID /ENABLE pin
        digitalWrite(chipSelectPin, LOW);         // Activate the RFID reader
      pinMode(NRSTPD,OUTPUT);                     // Set digital pin 9 , Not Reset and Power-down
        digitalWrite(NRSTPD, HIGH);

      myRFID.AddicoreRFID_Init();

    //setup web call functions

    //Particle.function("netopen", R1ON);
    //Particle.function("netclose", R2ON);
    //Particle.function("netstop", R3ON);

      digitalWrite(re1, HIGH); //turn off relay
      digitalWrite(re2, HIGH); //turn off relay
      digitalWrite(re3, HIGH); //turn off relay
      digitalWrite(re4, HIGH); //turn off relay

    }

    // This routine gets repeated over and over, as quickly as possible and as many times as possible, after the setup function is called.
    // Note: Code that blocks for too long (like more than 5 seconds), can make weird things happen (like dropping the network connection).  The built-in delay function shown below safely interleaves required background activity, so arbitrarily long delays can safely be done if you need them.

    void loop() {

    //Loop for RFID ----------------------------------------------------------------------

    //unsigned char checksum1;
      unsigned char status;
            unsigned char str[MAX_LEN];
            //unsigned char RC_size;
            //unsigned char blockAddr;  //Selection operation block address 0 to 63
            //String mynum = "";

            str[1] = 0x4400;
      //Find tags, return tag type
      status = myRFID.AddicoreRFID_Request(PICC_REQIDL, str);
      if (status == MI_OK)
      {
              Serial.println("RFID tag detected");
                     }

      //Anti-collision, return tag serial number 4 bytes
      status = myRFID.AddicoreRFID_Anticoll(str);
      if (status == MI_OK)
      {
    //          checksum1 = str[0] ^ str[1] ^ str[2] ^ str[3];
              Serial.print("The tag's number is:\t");
              Serial.print(str[0]);
                Serial.print(" , ");
              Serial.print(str[1]);
                Serial.print(" , ");
              Serial.print(str[2]);
                Serial.print(" , ");
              Serial.println(str[3]);

    //check if valid card combination
                if((str[0] == 333) && (str[1] == 444) && (str[2] == 555) && (str[3] == 666) )                   //You can change this to the first byte of your tag by finding the card's ID through the Serial Monitor
                {
                    Serial.println("\nKey fob identifed - Josh\n");

                    if(doorstate == 1) {
                      //door is already open so close
                        // Close Garage Door
                        R2ON(); //turn on relay
                        doorstate = 0;
                        Serial.print("Relay 2 on") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        R2OFF(); //turn off relay
                        Serial.print("Relay 2 off") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                          Serial.print("Close State Button HIGH - Finished Closing Garage Door")    ;
                        Serial.println("");

                    } else {
                      //door is closed so open

                        //Open Garage Door
                        R1ON(); //turn on relay
                        doorstate = 1;
                        Serial.print("Relay 1 on") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        R1OFF(); //turn off relay
                        Serial.print("Relay 1 off") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        Serial.print("Open State Button HIGH - Finished Opening Garage Door")    ;
                        Serial.println("");
                    }

                } else if((str[0] == 222) && (str[1] == 333) && (str[2] == 444) && (str[3] == 555) ) {             //You can change this to the first byte of your tag by finding the card's ID through the Serial Monitor
                    Serial.println("\nCar Charge Card Identided - Josh\n");

                    if(doorstate == 1) {
                      //door is already open so close
                        // Close Garage Door
                        R2ON(); //turn on relay
                        doorstate = 0;
                        Serial.print("Relay 2 on") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        R2OFF(); //turn off relay
                        Serial.print("Relay 2 off") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                          Serial.print("Close State Button HIGH - Finished Closing Garage Door")    ;
                        Serial.println("");

                    } else {
                      //door is closed so open

                        //Open Garage Door
                        R1ON(); //turn on relay
                        doorstate = 1;
                        Serial.print("Relay 1 on") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        R1OFF(); //turn off relay
                        Serial.print("Relay 1 off") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        Serial.print("Open State Button HIGH - Finished Opening Garage Door")    ;
                        Serial.println("");
                    }
                } else if((str[0] == 111) && (str[1] == 222 && (str[2] == 333) && (str[3] == 444) ) {             //You can change this to the first byte of your tag by finding the card's ID through the Serial Monitor
                    Serial.println("\nCar Garage Card Identided - Charlotte\n");

                    if(doorstate == 1) {
                      //door is already open so close
                        // Close Garage Door
                        R2ON(); //turn on relay
                        doorstate = 0;
                        Serial.print("Relay 2 on") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        R2OFF(); //turn off relay
                        Serial.print("Relay 2 off") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                          Serial.print("Close State Button HIGH - Finished Closing Garage Door")    ;
                        Serial.println("");

                    } else {
                      //door is closed so open

                        //Open Garage Door
                        R1ON(); //turn on relay
                        doorstate = 1;
                        Serial.print("Relay 1 on") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        R1OFF(); //turn off relay
                        Serial.print("Relay 1 off") ;
                        Serial.println("");
                        delay(1000); // wait 1 second
                        Serial.print("Open State Button HIGH - Finished Opening Garage Door")    ;
                        Serial.println("");
                    }
                }
                Serial.println();
                delay(1000);
      }

            myRFID.AddicoreRFID_Halt();      //Command tag into hibernation

       //End Loop For RFID  ----------------------------------------------------------------------

    OpenButtonState = digitalRead(btn1);
    CloseButtonState = digitalRead(btn2);
    StopButtonState = digitalRead(btn3);

    if (OpenButtonState == HIGH) {

      Serial.print("Open State Button HIGH - Opening Garage Door")  ;
      Serial.println("");
        //Open Garage Door
      R1ON(); //turn on relay
      doorstate = 1;
      Serial.print("Relay 1 on") ;
      Serial.println("");
      delay(1000); // wait 1 second
      R1OFF(); //turn off relay
      Serial.print("Relay 1 off") ;
      Serial.println("");
      delay(1000); // wait 1 second
      Serial.print("Open State Button HIGH - Finished Opening Garage Door")    ;
      Serial.println("");
      }

    if (CloseButtonState == HIGH) {

      Serial.print("Close State Button HIGH - Closing Garage Door") ;
      Serial.println("");
        // Close Garage Door
      R2ON(); //turn on relay
      doorstate = 0;
      Serial.print("Relay 2 on") ;
      Serial.println("");
      delay(1000); // wait 1 second
      R2OFF(); //turn off relay
      Serial.print("Relay 2 off") ;
      Serial.println("");
      delay(1000); // wait 1 second
        Serial.print("Close State Button HIGH - Finished Closing Garage Door")    ;
      Serial.println("");

      }

    if (StopButtonState == HIGH) {

     Serial.print("Stop State Button HIGH - Stopping Garage Door")  ;
     Serial.println("");
     // Stop
      R3ON(); //turn on relay
      doorstate = 1;
      Serial.print("Relay 3 on") ;
      Serial.println("");
      delay(1000); // wait 1 second
      R3OFF(); //turn off relay
      Serial.print("Relay 3 off") ;
      Serial.println("");
      delay(1000); // wait 1 second
          Serial.print("Stop State Button HIGH - Finished Stopping Garage Door")    ;
      Serial.println("");

      }

      // And repeat!
    }

    void R1ON() {

        digitalWrite(re1, LOW); //turn on relay
        //Particle.publish("Relay 1 on - Door Open");
        delay(1000); // wait 1 second
        digitalWrite(re1, HIGH); //turn off relay
        //Particle.publish("Relay 1 off");

    }

    void R1OFF() {
      digitalWrite(re1, HIGH); //turn off relay
        //delay(1000); // wait 1 second

    }

    void R2ON() {

        digitalWrite(re2, LOW); //turn on relay
        //Particle.publish("Relay 2 on - Door Closing");
        delay(1000); // wait 1 second
        digitalWrite(re2, HIGH); //turn off relay
        //Particle.publish("Relay 2 off");

    }

    void R2OFF() {

        digitalWrite(re2, HIGH); //turn on relay
        //delay(1000); // wait 1 second

    }

    void R3ON() {

        digitalWrite(re3, LOW); //turn on relay
        //Particle.publish("Relay 3 on - Door Stopped");
        delay(1000); // wait 1 second
        digitalWrite(re3, HIGH); //turn off relay
        //Particle.publish("Relay 3 off");

    }

    void R3OFF() {

        digitalWrite(re3, HIGH); //turn on relay
        //delay(1000); // wait 1 second

    }

    void R4ON() {

        digitalWrite(re4, LOW); //turn on relay
        //delay(1000); // wait 1 second

    }

    void R4OFF() {

        digitalWrite(re4, HIGH); //turn on relay
        //delay(1000); // wait 1 second

    }

  [1]: https://i.stack.imgur.com/bZgqU.jpg

title: Garage Door Opener RFID failing after a period

Answers: 2

body:
In 50+ years of dealing with hardware/software issues, I've found that the culprit is almost never the hardware. So, your problem is most likely the software.

To start with, there are several major problems with your code:

 1. You are using an unsigned char type to represent integer values > 256; this will not work.  When I tried to compile your code, one of the many error messages was "StackOvrFl.ino: 107:8: warning: large integer implicitly truncated to unsigned type [-Woverflow]" on the line 'str[1] = 0x4400;' You need to declare 'str' as 'unsigned int str[MAX_LEN];'.
 2. It's really bad form to use 'nicknames' ('uchar') for types; If someone else needs to maintain or modify your code (or help you with it as in this case), they are going to trip over that and emit 4-letter words in your direction.
 3. Turn on compiler warnings and errors, and don't stop debugging until all such warnings/errors are cleared.  The compiler is your friend; let it help you.
 4. If you had turned on compiler warnings/errors, you would have found that the identifier 'MI_OK' was never declared, and so can have ANY VALUE when you check it.

The combination of the integer overflow and undeclared symbol problems will almost undoubtedly cause undefined behavior, but there may be other issues as well.  Clean up your code, pay attention to compiler warnings, and then see what happens.

Good luck!

Frank

body:
Consider removing the type [String][1] from the code including removing where String is used in passing formal values to some functions.  It appears to do nothing.  And if the compiler does not optimize it out, could actually be consuming what little RAM the embedded processor contains.

The type String loads in all kinds of help you may or may not need.  Generally String is a bad idea for embedded processors because Sting consumes a large amount of resources to support all of String's features. And sometimes those resources are not given back.  This is generally referred to as a [memory leak][2]. Briefly, this is when the RAM in an embedded processor is considered used by the program, but is not actually being used by the programmer.

  [1]: https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/
  [2]: https://en.wikipedia.org/wiki/Memory_leak


body:
I'm quite new to Arduino and am making my first proper project, an obstacle avoiding robot.

I'm using an Arduino Uno and a motor shield compatible with the Adafruit motor driver library. I'm trying to run the example code from here: https://learn.adafruit.com/adafruit-motor-shield/using-dc-motors, but with both motors running at once. This should run the motors forward for 1 sec, backward for 1 sec and then pause for 1 sec.

I'm getting inconsistent behaviour when I run the code. When I only connect 1 motor, it works fine. When the Arduino is connected to my laptop via USB, it works fine. However, when I use the 6V external power supply and both motors, they will only move in 1 direction and remain still during the second movement period. When I set them to move forward-backward-stationary, they only move forwards. When I set them to backward-forward-stationary, they only move backwards.

Any ideas what might be causing this / how I could fix it? Like I said, I'm pretty new to this so might be making a simple mistake.

Here's my setup:
[![4 AA batteries powering a motor shield, with 2 DC motors attached to motor ports 1 and 4.][1]][1]

I have 2 DC motors, one attached to port 1 and the other to port 4 on the motor shield. The power supply is 4 AA batteries (which I think is 6V?), which is also connected to the motor shield.

And here's my code:

    #include <AFMotor.h>

    AF_DCMotor leftMotor(1, MOTOR12_1KHZ);
    AF_DCMotor rightMotor(4, MOTOR12_1KHZ);

    void setup() {
      leftMotor.setSpeed(255);
      rightMotor.setSpeed(255);
    }

    void loop() {
      leftMotor.run(FORWARD);
      rightMotor.run(FORWARD);
      delay(1000);

      leftMotor.run(BACKWARD);
      rightMotor.run(BACKWARD);
      delay(1000);

      leftMotor.run(RELEASE);
      rightMotor.run(RELEASE);
      delay(1000);
    }

Any help is much appreciated!

  [1]: https://i.stack.imgur.com/azvtE.jpg

title: DC motors only run in one direction

Answers: 3

body:
Your code looks pretty straightforward, and the fact that everything works properly with the laptop-USB connector makes me suspect that your problem lies with the battery pack.

When you said "When the Arduino is connected to my laptop via USB, it works fine.", did you mean that the 4-cell battery pack is still connected to the motor shield as shown, but the Arduino is being powered from the laptop via USB?

I suspect that what is going on is that during the transition from one direction to the other, the battery voltage temporarily drops below the Arduino's low-voltage cutoff point and everything stops, EXCEPT, when the Arduino is connected to the laptop via USB, the USB connection continues to power the Arduino through the dropout period and everything works.

Since you are starting to work with electronics and Arduino, you might want to consider getting a basic DVM (Digital Volt-AmpMeter) and a basic lab power supply. These two items would allow you to easily troubleshoot this problem.  A common desktop PC power supply with 5, 12 and (sometimes) 24V DC output makes a good bench power supply and are widely available and cheap.

Hope this helps,

Frank

body:
Possible hardware solution:

Consider using 2 battery packs.  One connected to the Arduino and the other connected to the motor drive board.  Remember to connect the grounds of the 2 battery packs together.

Possible software solution:

Software is often over looked when solving what appears to be a hardware issue.  Consider introducing a short pause between motor direction changes.  It may be that the power required to reverse the direction of a motor exceeds the capacity of the battery pack.  Likely it will take less power to first stop the motor, pause then start the motor in the opposite direction.

body:
4 AA batteries is 6 volts, which is the right amount of voltage for 2 DC motors. Like all the other answers on this page, the problem most likely has to do with your battery pack, although I am not sure how that would affect your motors. I can't really tell from the picture, but the problem would have to be with the wiring from your battery pack. If you have wires that go from the battery pack, to the motors, you should check to make sure that those are properly wired, as that would be a problem.

I hope this information helps, and the rest of your projects with Arduino go very smoothly!

-Simon


body:
i will be designing a robot with multiple stepper motor. is it advisable to use millis instead of delay here or not?
right now im testing if Millis() would work but still having a hard time programming this.

title: Stepper Motor Code. Delay or Millis

Answers: 1

body:
Arduino function delay() which pauses the program for an amount of milliseconds specified as parameter.

millis(), on the other hand, is a function that returns the amount of milliseconds that have passed since program start.

Just like delay() has a microsecond-version called delayMicroseconds(), millis() has micros(). If you need better resolution, micros() may be the way to go.

However, be aware that micros() will overflow after approximately 70 minutes, compared to millis()‘s 50 days. This means that the functions’ return values will start all over from zero.


body:
I have a DFRobots MPU6050 module wired to SCL/SDA/Pin 2 on a Mega 2560 board, using Jeff Rowberg's I2CDev/MPU6050_6Axis_MotionApps libraries.  I have 2.2K pullups on the MPU6050 module, tied to +5V, as shown in the following photo.

[![enter image description here][1]][1]

I used a modified version of the code from Jeff's example to retrieve heading values from the MPU6050, as shown below
<!-- language-all: lang-cpp -->

    bool GetIMUHeadingDeg() //08/28/18 chg to bool return
{

 //Purpose:  Encapsulate everything needed to acquire a yaw value
 //Inputs:
 // global_yawval = float variable defined at global scope
 // fifocount = uint8_t variable defined at global scope
 // packetsize = uint8_t variable defined at global scope
 // mpuIntStatus = uint8_t variable defined at global scope
 // whilecount = long variable defined at global scope
 // resetcount = int variable defined at global scope
 //Outputs:
 // global_yawval filled with latest yaw value from sensor
 // true = success, false = failure
 //Notes:
 // 08/13/18 now returns global_yawval to calling routine
 // 08/28/18 chg return to bool so can return success/failure

 // if programming failed, don't try to do anything
 //if (!dmpReady) return;
 //if (!dmpReady) false;

 bool result = false; //added 01/16/19 to supress warnings

 // wait for MPU interrupt or extra packet(s) available
 while (!mpuInterrupt && fifoCount < DMPpacketSize)
 {
  whilecount++;
  delay(10);
  delay(10);

  if (mpuInterrupt)
  {
   fifoCount = mpu.getFIFOCount();
   mySerial.printf("%ld\t%d\n", whilecount, fifoCount);
   whilecount = 0;
   break;
  }
 }

 // reset interrupt flag and get INT_STATUS byte
 mpuIntStatus = mpu.getIntStatus();
 mpuInterrupt = false;

 // get current FIFO count
 fifoCount = mpu.getFIFOCount();

 // check for overflow (this should never happen unless our code is too inefficient)
 if ((mpuIntStatus & 0x10) || fifoCount == 1024)//0x10 is mask for MPU6050_INTERRUPT_FIFO_OFLOW_BIT
 {
  // reset so we can continue cleanly
  mpu.resetFIFO();
  Serial.println(F("FIFO overflow!"));
  result = false; //added 01/16/19 to supress warnings

  // otherwise, check for DMP data ready interrupt (this should happen frequently)
 }
 else if (mpuIntStatus & 0x02)//0x02 is mask for MPU6050_INTERRUPT_DMP_INT_BIT
 {
  // wait for correct available data length, should be a VERY short wait
  while (fifoCount < DMPpacketSize)
  {
   fifoCount = mpu.getFIFOCount();
   //mySerial.printf("fifo count = %d\n", fifoCount);
  }

  //07/08/18 added to watch for non-modulo FIFO counts
  if (fifoCount == 0 || fifoCount % DMPpacketSize != 0)
  {
   mpu.resetFIFO();
   FIFO_resetcount++;
  }
  else
  {
   //07/07/18 modified to read all outstanding packets
   // read a packet from FIFO
   while (fifoCount >= DMPpacketSize)
   {
    //mySerial.printf("fifo count = %d\n", fifoCount);
    mpu.getFIFOBytes(fifoBuffer, DMPpacketSize);
    fifoCount -= DMPpacketSize;
   }

   // display Euler angles in degrees
   mpu.dmpGetQuaternion(&q, fifoBuffer);
   mpu.dmpGetGravity(&gravity, &q);
   mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

   global_yawval = ypr[0] * 180 / M_PI;
   result = true; //added 01/16/19 to supress warnings
  }

  ////DEBUG!!
  //  mySerial.printf("yawdeg = %4.2f\n", global_yawval);
  //  mySerial.printf("time = %ld\tyawdeg = %6.2f\n", millis(), global_yawval);
  ////DEBUG!!
 }

 return result; //added 01/16/19 to surpress warnings
}

I have noticed occasional bad data points in the computed Heading values retrieved from the MPU6050, as shown in the attached plot. Any ideas what I can do about this?  Is bad value detection/removal an expected issue when dealing with IMU products like the MPU6050?

[![enter image description here][2]][2]

As an experiment, I excluded all points for which the rotation rate was unrealistically high, resulting in the 'Adj Hdg' line (gray line) in the plot below.  This (mostly) works, except for one instance where there were two bad values in a row.

[![enter image description here][3]][3]
TIA,

Frank

  [1]: https://i.stack.imgur.com/Ux9wG.jpg
  [2]: https://i.stack.imgur.com/3hZSW.jpg
  [3]: https://i.stack.imgur.com/VxcpP.jpg

title: MPU6050/DMP Intermittent bad data output?

Answers: 1

body:
Looks like the major driver in the data 'noise' was the FIFO data rate, set via the MPU6050_DMP_FIFO_RATE_DIVISOR constant in MPU6050_6Axis_MotionApps20.h.  I changed the rate from 100Hz (0x01) to 20Hz (0x09) and got the following almost completely noiseless plot under the same conditions as before.  Note the vertical scale - only 6 deg total, and the one 'excursion' is only a 4 deg change. I also plotted the 3-point running average, which further reduces the excursion to less than 2 deg.

So, if you are looking for clean yaw (Heading) data from the MPU6050 DMP, consider changing the FIFO rate.

Frank

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/6Wg8V.jpg


body:
My Uno WiFi Rev2 outputs on the serial monitor after ~30 min "no socket available". Until that point everything works just fine, my requests run as expected. I use the .flush() and .stop() commands, as in several forums suggested. In the following my really messy code (sorry for that, but it's not optimized and only for testing some stuff):
<!-- language-all: lang-cpp -->

    #include <SPI.h>
    #include <WiFiNINA.h>

    //W-Lan Data
    int status = WL_IDLE_STATUS;
    char ssid[] = "**********";
    char pass[] = "**********";

    bool jsonBool;
    char jsonChar;
    int curlyBracket;
    String jsonCode;
    String json;

    IPAddress HueBridge(10, 0, 0, 30);

    WiFiClient WHTTP;

    void setup() {
      while (status != WL_CONNECTED) {
        status = WiFi.begin(ssid, pass);
        delay(500);
      }
    }

    void loop() {
      jsonProcessing();
      httpRequest();

      bar1();

      delay(55);
    }

    void httpRequest() {
      WHTTP.flush();
      WHTTP.stop();
      if(WHTTP.connect(HueBridge, 80)) {
        WHTTP.println("GET /api/*************/lights/ HTTP/1.1");
        WHTTP.println("Host: 10.0.0.30");
        WHTTP.println("Connection: close");
        WHTTP.println();
      }
    }

    void jsonProcessing() {
      while(WHTTP.connected()) {
        if(WHTTP.available()) {
          curlyBracket = 7;
          while(WHTTP.available()) {
            jsonChar = WHTTP.read();
            if((jsonChar == '{') && (curlyBracket == 7)) {
              jsonBool = true;
              curlyBracket = 0;
            }
            if(jsonChar == '}') {
              jsonBool = false;
              jsonCode = jsonCode + '}';
              curlyBracket++;
            }
            if(jsonBool) {
              jsonCode = jsonCode + jsonChar;
            }
          }
        }
        WHTTP.flush();
        WHTTP.stop();
      }
      jsonBool = false;

      //processing jsonCode variable

      jsonCode = "";
    }

    void bar1() {
      //calculating stuff
    }

If anything is unclear feel free to ask. This is not the whole code, just the WiFi relevant parts.

The main structure is copied from here [https://www.arduino.cc/en/Tutorial/WiFiNINAWiFiWebClientRepeating][1]
so it theoretically should work.

Thanks in advance.

  [1]: https://www.arduino.cc/en/Tutorial/WiFiNINAWiFiWebClientRepeating

title: Arduino Uno WiFi Rev2 "no socket available"

Answers: 0


body:
Picked up a YS-IRTM IR Transmitter/Receiver module to do some testing for a project. There's not a lot of details on it but eventually came across two very important sources:

Translated Module Datasheet: https://docplayer.net/101050357-Nec-infrared-codec-module-ver1-0-ys-irtm.html

Examples: https://forum.arduino.cc/index.php?topic=359707.msg2861077#msg2861077

I've been trying to get this working for a few days and so far haven't gotten anything. Need to reach out before I pull out whatever hair I have left.

BTW, new to this and may have easily missed something.

Wiring Diagram
```
Arduino Uno    YS-IRTM
5v          -> 5v
GND         -> GND
0 RX        -> TXD
1 TX        -> RXD
```

Code
```
int icb = 0;
SoftwareSerial ir_mod(0, 1);

void setup(){
  Serial.begin(115200);
  while(!Serial){}
  Serial.println("Setup IR Serial");
  ir_mod.begin(9600);
  while(!ir_mod){}
  Serial.println("IR Serial Ready");
}

void loop(){
  if(ir_mod.available() > 0){
    icb = ir_mod.read();
    Serial.print(" 0x");
    Serial.println(icb, HEX);
  }
}
```

Current Output
```
Setup IR Serial
IR Serial Ready
```

Nothing will happen if I try to interact with the Receiver with any IR Transmitter (like a TV/AC Remote) but if I disconnect and reconnect the power, I get " 0xFFFFFFFF". Then nothing.

title: Using the YS-IRTM with an Arduino Uno

Answers: 2

body: Default baud for module is 9600 unless you previous set it diffrent as per the datasheet A1 F3 ## 00 00 I believe

body: I am also new to this but if I am not mistaken, you seem to have connected the IR module to Arduino Hardware Serial while trying to communicate with the module via SoftwareSerial. Try using Arduino pins 2 and 3 for the SoftwareSerial instead of pins 0 and 1. Forgive me if I got it all wrong.


body: Is it possible to test a SPI connection by wiring the MISO directly to the MOSI pin?  I'm working on a low-level SPI implementation, and I want to check that the library is basically working.  It would be nice to be able to test the connection itself without additional hardware.

title: SPI: test by connecting MOSI to MISO

Answers: 2

body:
Usually the SPI Master clocks data out while the Slave clocks data back in. So if you were sending and receiving 8 bits per transaction you can clock out 8 bits and at the same time clock in 8 bits for a total of 8 clocks.  This is described in [this Wikipedia paragraph][1]. That said, often the first 8 clocks are used to transmit a command and an additional 8 clocks are used to retrieve the result.

If you looped MOSI to MISO you would clock in what you clocked out. You would complete the entire transaction in 8 clocks. At a low level I'm thinking this does not matter. But at a higher level the software would have to be re-written to accommodate this weirdness.

  [1]: https://en.wikipedia.org/wiki/Serial_Peripheral_Interface#Data_transmission

body:
Yes, you can - and it's something I often do when doing low-level electrical testing an SPI interfacce.  For every clock that you send out the data presented on MOSI will get reflected on MISO.  So if you were to (using the Arduino SPI library) do:

    uint8_t x = SPI.transfer(0x38);

then `x` should equal `0x38`.

I find this especially useful on systems with remappable pins to confirm that the pins are configured correctly in the board configuration for proper SPI operation.


body:
[![enter image description here][1]][1]

Hi I am using Arduino uno & ESP-01

ESP-01 is working well when I put firmware to ESP, for example, wifi spreading or AT command is okay.

but when I disconnect arduino from PC(disconnect USB connection)

ESP-01 suddenly do not work anything. no spread wifi, no AT command reaction..

so I always have to re-input the firmware to ESP again, for make it work again.

How can I make maintain ESP-01 's firmware?

picture is my connection status. thank you

  [1]: https://i.stack.imgur.com/2AbW5.jpg

title: ESP 01 lost its firmware when it disconnected

Answers: 1

body:
You have io 0 puled LOW so the esp-01 firmware starts in flashing mode and the firmware starts immediately after flashing (no reset).

Remove io 0 to ground connection and add a pull-up for io 0 over a 10kOhm resistor if you want the esp-01 to start normally.

Note: powering the esp-01 from the 3.3 V pin of Uno (150mA max) could be insufficient for esp8266 WiFi operations at top transmit power (according to specs it can draw to 170 mA).


body:
I have a 5V (5.3V) switching transformer that goes to a 7805 voltage regulator and powers Arduino, Arduino controls 4 relays using BJTs. those relays getting power directly from the same power source.

Arduino and it's modules + LCD uses ~40ma, each relay consumes 70ma. total current is around 350ma lets say 400ma.

The problem is 5V isn't enough to power Arduino, modules, sensors and relays. LCD gets very dim etc...

it works with 9V but 7805 gets really hot ~70 centigrade while having a heat sink on!

If i remove the 7805 and switching power burns or something bad happens then there's nothing in between to protect the Arduino!

What's the solution for this situation?
______________
**EDIT:** *for anyone who may have the same problem; I solved the problem with using a proper switching power salvaged from an old USB type-C charger and removed the 7805 voltage regulator, there's no heat anymore and it's working perfectly.*

title: Powering Arduino AND Relays

Answers: 1

body:
Linear regulators such as the 7805 operate by dissipating the additional voltage until their rated voltage remains.
This - as you noticed - requires a higher voltage  than the rated voltage.
Some variants, labeled as LDO for low drop-out, have reduced requirements for this, but normal 7805 usually require around 7 V to operate correctly.

The difference to the rated voltage is dissipated as heat as per `P = U * I`, with U being the voltage difference, and I the current pulled by your circuit.

You can use the switching power supply directly, or use a more advanced voltage regulator like the R-78E5.0 directly from 9 V, which has far lower losses.

Another option would be using the 5V from the switching transformer to drive the (less delicate) relays, and use the 7805 only for the MCU and display, but you would still want to use a heat sink in that case.


body:
I'm making a timer program which takes the Time Duration as input from the user by two button switches (one for 'up' and one for 'down'), and after pressing an another button switch ('start'), the timer starts. During countdown, an LED glows, and after the end of the countdown, it turns off.

The elapsed time is displayed on a 7 seg. display, as a minute count.

```c++
#define segA 2
#define segB 3
#define segC 4
#define segD 5
#define segE 6
#define segF 7
#define segG 8
#define pinsig 0

const int buttonPinUp = 12;
const int buttonPinDown = 10;
const int buttonPinStart = 9;

int COUNT=0;
int buttonStateUp = 0;
int buttonStateDown = 0;
int buttonStateStart = 0;
int flag;

void setup()
{
    for (int i = 2; i < 9; i++)
    {
        pinMode(i, OUTPUT);
    }
    pinMode(pinsig, OUTPUT);
    pinMode(buttonPinUp, INPUT);
    pinMode(buttonPinDown, INPUT);
    pinMode(buttonPinStart, INPUT);
}

void loop()
{
    buttonStateUp = digitalRead(buttonPinUp);
    if (buttonStateUp == HIGH)
    {
        COUNT++;
        delay(200);
    }
    buttonStateDown = digitalRead(buttonPinDown);
    if (buttonStateDown == HIGH)
    {
        COUNT--;
        delay(200);
    }
    buttonStateStart = digitalRead(buttonPinStart);
    if (buttonStateStart == HIGH)
    {
        flag = HIGH;
    }

    if (flag == HIGH)
    {
        if (COUNT > 0)
        {
            digitalWrite(pinsig, HIGH);
            COUNT--;
            delay(2000);
        }
        if (COUNT == 0)
        {
            flag = LOW;
            digitalWrite(pinsig, LOW);
        }
    }

    switch (COUNT)
    {
        case 0:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, HIGH);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, LOW);
            break;
        case 1:
            digitalWrite(segA, LOW);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, LOW);
            digitalWrite(segE, LOW);
            digitalWrite(segF, LOW);
            digitalWrite(segG, LOW);
            break;
        case 2:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, LOW);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, HIGH);
            digitalWrite(segF, LOW);
            digitalWrite(segG, HIGH);
            break;
        case 3:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, LOW);
            digitalWrite(segF, LOW);
            digitalWrite(segG, HIGH);
            break;
        case 4:
            digitalWrite(segA, LOW);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, LOW);
            digitalWrite(segE, LOW);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, HIGH);
            break;
        case 5:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, LOW);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, LOW);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, HIGH);
            break;
        case 6:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, LOW);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, HIGH);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, HIGH);
            break;
        case 7:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, LOW);
            digitalWrite(segE, LOW);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, LOW);
            break;
        case 8:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, HIGH);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, HIGH);
            break;
        case 9:
            digitalWrite(segA, HIGH);
            digitalWrite(segB, HIGH);
            digitalWrite(segC, HIGH);
            digitalWrite(segD, HIGH);
            digitalWrite(segE, LOW);
            digitalWrite(segF, HIGH);
            digitalWrite(segG, HIGH);
            break;
    }
}
```

But the program is not working as I expected.
I'm new in programming, so know a little basics. Can anyone help me in that ?

title: Having problem in coding Arduino Uno

Answers: 0