title: WifiManager and WiFi functionally

text:
# Question
Title: WifiManager and WiFi functionally
I’m considering using `wifiManager` mostly to have the ability not to hard code WiFi creditntials. But In my current code I use WiFi’s functions as `WiFi.setAutoReconnect(true)` and `WiFi.status() != WL_CONNECTED`

How can it be done using `WifiManager`?

# Answer
> 1 votes
You don't. WifiManager does all that for you. You don't need anything like that in your code. Just follow the examples and read the documentation.

But if you do want to then you just need to remember that WifiManager is merely a library that configures the WiFi for you. If you want to query or alter the WiFi settings you can - exactly as you are right now. The two aren't mutually exclusive.

# Answer
> 1 votes
Here's a working example that's on my Wemos D1 Mini. It stands up an AP until you provide credentials for your local LAN, then displays it's DHCP IP address on a 16x2 LCD and stands up a webserver. Once the credentials are stored it won't stand up the AP, it will just reconnect and do the main loop() of the sketch. To force the AP to restart you need to call the `ESP.reset();` method to flush the stored credentials and reboot the Wemos.

```
#include <LiquidCrystal_PCF8574.h>
#include <ESP8266WiFi.h>

#include <WiFiManager.h>
#include <ESP8266WebServer.h>
#include <Wire.h>

WiFiClient wemosCL;

ESP8266WebServer server(80);

const int led = LED_BUILTIN;

LiquidCrystal_PCF8574 lcd(0x38);

void handleRoot() {
  digitalWrite(led, 1);
  server.send(200, "text/html", "<html><head><title>ESP8266 Demo</title><style>body{background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088;}</style></head><body><h1>Hello from ESP8266!</h1><p>IP Addr: " +
          WiFi.localIP().toString() + "<p></body></html>");

  digitalWrite(led, 0);
}

void handleNotFound() {
  digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++) {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  digitalWrite(led, 0);
}

void setup(void) {
  Serial.begin(115200);
  WiFiManager wifiManager;
  wifiManager.autoConnect("Wemos", "configuration");
  pinMode(led, OUTPUT);
  digitalWrite(led, 0);

  lcd.begin(16, 2);
  lcd.setBacklight(255);
  lcd.print("I'm alive");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    lcd.setCursor(0, 0);
    lcd.print(".");
  }

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Status:Connected");
  lcd.setCursor(0, 1);
  lcd.print("IP:");
  lcd.print(WiFi.localIP());

  server.on("/", handleRoot);

  server.onNotFound(handleNotFound);

  server.begin();
}

void loop(void) {
  server.handleClient();
}

```

---
Tags: esp8266, wifi
---


# Question
Title: Creating and Arduino synthesizer without the tone library
I am thinking about trying to make an Arduino synthesizer using the true analog output on the Due. However I would like to be able to play multiple notes at the same time on a single buzzer. Is this possible and how would I do it?

# Answer
You just have to add the waveforms. For example, if you want to play pure tones (the simplest and most boring timbre), you generate a sine wave for each of them and add them together:

```
struct Note {
    float frequency;
    float phase;
    bool is_active;
} notes[MAX_NOTES];

void output_sample()
{
    static uint32_t previous_time;
    uint32_t now = micros();
    uint32_t elapsed_time = now - previous_time;
    previous_time = now;
    float output = 0;
    for (int i = 0; i < MAX_NOTES; i++) {
        Note *note = &notes[i];
        if (note->is_active) {
            output += cos(note->phase);
            note->phase += 2*M_PI*note->frequency*1e-6*elapsed_time;
            if (note->phase >= 2*M_PI) {
                note->phase -= 2*M_PI;
            }
        }
    }
    analogWrite(DAC_PIN, 2048 + round(output * (2047.0 / MAX_NOTES)));
}

```

The function `output_sample()` should be called as frequently as possible. You can change the `notes` array any time to add, remove or change notes.

There is some room for optimization here, like:

* storing `2*M_PI*note->frequency*1e-6` as the “frequency” in order to save some calculations
* using a wave table instead of the `cos()` function (I don't know how good is the Due at transcendental math)
* replacing `elapsed_time` by a constant if you can manage to output the samples at a fixed rate.

---

**Edit**: I wrote “You can change the `notes` array any time to add, remove or change notes.” Here is how to start or stop a note, i.e. to add or remove it from the list of active notes:

```
// Start a note. Returns an index to be used with stop_note(), or -1 if
// we couldn't start the note because we are already outputting the
// maximum number of simultaneous notes.
int start_note(float frequency)
{
    int i;  // index of the note in the notes[] array

    // Find a free slot in the array.
    for (i = 0; i < MAX_NOTES; i++)
        if (!notes[i].is_active) break;  // found

    // Couldn't find a free slot?
    if (i == MAX_NOTES) return -1;

    // Setup the note parameters.
    notes[i].frequency = frequency;
    notes[i].phase = 0;
    notes[i].is_active = true;
    return i;
}

// Stop the note with the given index.
void stop_note(int index)
{
    if (index >=0 && index < MAX_NOTES)
        notes[index].is_active = false;
}

```
> 1 votes

# Answer
Sound is nothing else than a multiple simple waves combined in to one. So, theoretically you can play as many sounds (tones) as you like on a single pin. If you want to go true analog than you probably want to use a sin wave to generate sound. However, in that case you can do the following: Either make a function that would be capable of generating a sin wave of your desired frequency. In case of true analog this would probably be done by calculating actual sin values and using the map() function mapping 0 - 1 to 0 - 1024 and writing to the pin. The frequency can be adjusted by changing the delay between each step of changing the voltage or DAC value. However, this will not allow for multiple frequencies. Alternatively for multiple frequencies to be played at the same time you would need to calculate the Fourier inversion of all the waves you want to play and send the results of that to the DAC.
> 0 votes

---
Tags: arduino-due, sound, digital-analog-conversion
---


# Question
Title: How to merge two GPS coordinates without losing decimals
I want to take the GPS coordinates like **42.1234** per **22.1234** and merge them as a string, with a separator character:

`42.1234 x 22.1234`

But using this code:

`gps_string = (String)gps.location.lat()+' x '+(String)gps.location.lng();`

I lose the last decimals and I get:

`42.12 x 22.12`

The only way I could see full coordinates is by specifying an extra parameter to println, like this:

`Serial.println(gps.location.lat(), 6);`

How can I create a string containing both two coordinates without losing decimals ? e.g `42.1234 x 22.1234`

# Answer
If you want 4 decimal places, you may try something like this:

```
gps_string = String(gps.location.lat(), 4)
           + " x "
           + String(gps.location.lng(), 4);

```
> 1 votes

---
Tags: arduino-uno, arduino-ide, gps, variables, convert
---


title: Serial.println Issue with Flame Sensor

text:
# Question
Title: Serial.println Issue with Flame Sensor
I'm really new to coding and Arduino so I would be eternally grateful for the help.

I'm trying to make a really basic flame sensor that beeps, lights up an LED and displays the distance from the sensor to the flame when activated. I keep getting a "'Serial' does not name a type" error message for the line that reads - Serial.println(analogRead(A0));

I’ve tried to figure it out from the information on this forum of similar questions to try to correct the issue but it seems like every time I fix one thing another 2 errors come up. I’ve been stuck on this one for a little while so I’m hoping I might be able to receive some kind of assistance from the Arduino community.

Below is the entire code - any help is appreciated, thanks :)

```
int Led = 4;
int Buzz = 7;
int Sensor = 11;
int Fire = HIGH;
void setup()
{ Serial.begin(9600);
pinMode(Buzz,OUTPUT);
pinMode(Sensor,INPUT);
pinMode(Led,OUTPUT);
}
void loop()
{
Fire = digitalRead(Sensor);
if(Fire == HIGH);
Serial.print("analog Read = ");
Serial.print(analogRead);
}
Serial.println("HELP! A FIRE!");
digitalWrite(Buzz,HIGH);
digitalWrite(Led,HIGH);
delay(200);
digitalWrite(Led,LOW);
delay(200);
Serial.println(analogRead(A0));
}
else
{
Serial.println("No fire detected");
digitalWrite(Buzz,LOW);
digitalWrite(Led,LOW);
}
delay(500);
}

```

# Answer
First things first; please INDENT YOUR CODE. The code you posted is a mess and I took at least double the time to fix that.

First, you have an extra closing curly bracket at line 17 and the `if (Fire == High);` should be changed to `if (Fire == High){`

Fixed code:

```
int Led = 4;
int Buzz = 7;
int Sensor = 11;
int Fire = HIGH;
void setup()
{
  Serial.begin(9600);
  pinMode(Buzz,OUTPUT);
  pinMode(Sensor,INPUT);
  pinMode(Led,OUTPUT);
}
void loop()
{
  Fire = digitalRead(Sensor);
  if(Fire == HIGH){
//Serial.print("analog Read = ");
//Serial.print(analogRead);
    Serial.println("HELP! A FIRE!");
    digitalWrite(Buzz,HIGH);
    digitalWrite(Led,HIGH);
    delay(200);
    digitalWrite(Led,LOW);
    delay(200);
    Serial.println(analogRead(A0));
 }
 else
 {
    Serial.println("No fire detected");
    digitalWrite(Buzz,LOW);
    digitalWrite(Led,LOW);
  }
  delay(500);
}

```
> 3 votes

---
Tags: arduino-uno, sensors, error
---


title: Program Arduino then Remove Atmega?

text:
# Question
Title: Program Arduino then Remove Atmega?
Can I program an Arduino and then remove the micro-controller from it and use it on a breadboard without reprogramming the micro-controller again?

My steps would be:

1. create my Arduino code.
2. I upload the compiled code to the board.
3. I remove the Ic and use it alone without the whole board.

Will the code be preserved on the microcontroller?

# Answer
Yes. The programming of the arduino microcontroller sets the values inside the FLASH. This is non volatile memory and as such won't be erased by taking out the IC.

Please note that this is assuming a DIP package IC as these can be removed without force, heat and stress. A TQFP, and SMT packages like that, IC might get damaged by moving them in such a way. This doesn't mean it has to be erased, it is still non volatile storage, but the moving process is much more dangerous for the chip.

I would recommend connecting the whole arduino or if you really need the whole chip: designing your own board/circuit which allows you to program the chip without moving it around as this is really tedious and not worth the effort. Also moving the chip around is a ESD hazard.

Also please note that you'll need to add a clock source for the chip to work (most of the time). Or you'll need to enable an internal PLL. It will in any case require more effort on your part to make sure that the MCU can work. Therefore using the whole arduino board is preferable.
> 3 votes

# Answer
Yes you can do it (as said by Tarick).

## Note about clock:

Be sure to program it correctly:

* Do not add a bootloader if you don't need one
* Do not use an external oscillator if you don't have one on your new board! This is important, since if you remove it you will not be able to start or programming it again!

So, before you remove the IC, set this on your Arduino (I assume it is an ATMega328):

* 8MHz internal (leave external only if you have an oscillator in the new board!)
* Bootloader: no

You will see that you do not have this options if you select a normal Arduino, since it already has an oscillator.

So you should use the board manager and add this: https://github.com/MCUdude/MiniCore
> 2 votes

# Answer
As code is stored in the flash memory, your code won't erase until some unexpected happens. But the question might comes in whether your code will work properly or not when you remove microcontroller from arduino board and connect with breadboard.

As you are planning to remove the microcontroller, I am guessing you are using Arduino Uno atmega328 DIP package.

You need to do two things for the proper function of the microcontroller in the breadboard. There are other solutions exist. I always prefer this one as easy.

1. connect 16MHz crystal with 22p(two) capacitor with the corresponding crystal pin(pin 9 &10). The crystal circuit is straightforward. Searching google might help.
2. Pull the Reset Pin with VCC using a 10k resistor.
> 1 votes

# Answer
Don't forget 0.1uF caps on the VCC and AVCC pins to Gnd. AVCC must also have power on it, either direct to the VCC pin, or thru a filter (small inductor)
> 0 votes

---
Tags: hardware, breadboard
---


# Question
Title: How can I make std::cout write to Serial?
I'm using an Arduino MKR WiFi 1010, a SAMD ARM Cortex M3 board. I rely on the standard library a lot, using things like `std::vector<>` and `std::string`. I also want to use `std::cout`. I've managed to do this on an UNO R3 using the ArduinoSTL library, but that library neither works nor is necessary on the MKR WiFi 1010, because it has all the standard library stuff built in to the platform.

However, on MKR WiFi 1010, I cannot get `std::cout` to produce any output. I'm guessing its not really hooked up to anything.

I want `std::cout` to write to `Serial` (which is aliased to `SerialUSB` which is of type `Serial_`).

Is there a way of making `std::cout` write to the `Serial` stream?

# Answer
The ARM gcc libraries offer a simple way to redirect standard outputs. It is enough to implement function `_write(int fd, char *ptr, int len)` and it will replace the default implementation used in library to direct the standard outputs to debugger semihosting. The function must be compiled as C to match.

```
#include <Arduino.h>
#undef max
#undef min
#include <stdio.h>
#include <iostream>

using namespace std;

extern "C" {
int _write(int fd, char *ptr, int len) {
  (void) fd;
  return Serial.write(ptr, len);
}
}

void setup() {

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

  Serial.println("START");

  printf("HERE WE ARE\r\n");

  cout << "TEST COUT\r\n";
  cerr << "TEST ERR\r\n";
}

void loop() {

}

```

the `#undefs` undefine the Arduino macros, which are in conflict with includes used in `<iostream>`
> 5 votes

---
Tags: serial, mkr1010, stl
---


# Question
Title: Converting human readable date to a unix timestamp
Can anyone provide a sample code that would convert a human readable date like `2019-10-27 22:10:35` to a unix timestamp like `1572214235`?

I found many topics about it, but they eider refer to out of date libraries, or they seem to address more complex time functions, I find it hard to extract this functionality from them.

# Answer
If you have a fixed format you can use `strtok()` to slice the string into individual segments, then convert those segments to integers. They can then be used with `TimeLib.h` with the `setTime()` function. You can then query TimeLib for the unix timestamp with `now()`.

**Edit:** using PaulStoffregen's TimeLib, this code sets current time and returns current unix timestamp.

```
#include <TimeLib.h>

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

  // hour, min, sec, day, month, year
  setTime(22, 30, 11, 29, 3, 2019);

  // 1553898611
  Serial.println(now());
}
void loop() {}

```

**Edit 2:** And to convert **any** given date to a unix timestamp (without setting current time):

```
#include "TimeLib.h"

tmElements_t my_time;  // time elements structure
time_t unix_timestamp; // a timestamp

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

  // convert a date and time into unix time, offset 1970
  my_time.Second = 0;
  my_time.Hour = 23;
  my_time.Minute = 0;
  my_time.Day = 25;
  my_time.Month = 3 - 1;      // months start from 0, so deduct 1
  my_time.Year = 2017 - 1970; // years since 1970, so deduct 1970

  unix_timestamp =  makeTime(my_time);
  Serial.println(unix_timestamp);
}

void loop() {}

```
> 1 votes

# Answer
After parsing the time into numbers, you can use the standard C time library `time.h`. More specifically, use the `mktime` function to convert a `struct tm` into a `time_t`, and use `difftime` to get the seconds since the start of the Unix expoch:

```
#include <time.h>

void loop() {
    struct tm ltm = {0};
    ltm.tm_year = 2019 - 1900;
    ltm.tm_mon  = 11 - 1;
    ltm.tm_mday = 5;

    int32_t epoch_seconds = difftime(mktime(&ltm), (time_t)0);
    Serial.print("Remember, remember, ");
    Serial.print(epoch_seconds);
}

```

Note that in `struct tm`, the year starts at 1900 and the month starts at 0.

EDIT: In avr-libc, `difftime` returns an `int32_t`, not a `double`.
> 2 votes

---
Tags: arduino-uno, timers, gps, time, convert
---


# Question
Title: Can I get some help with a metronome code on my arduino uno?
ok so I dont actually know anything about coding or electronics outside of being an electrician. This is something i've been working on for about a month. I may be asking something dumb but here it is.

also i dont know where to put my code so ill put it in the comments (sorry).

so basically I want a visual metronome. I want to plug a control box into the wall, plug a lamp into the control box to blink at a set interval. the box will have a rotary encoder and lcd display to control the beats per minute. to achieve this im gonna use a SSR and some transformers to achieve a variety of voltages for different led lights. but I want to affect a 120v cct to do it all. but I just want to get the code down before I build it so im trying to blink the onboard led on my arduino uno for now.

I have the code, which is 3 different sketches, frankensteined together. probably poorly. I added an arithmetic equation to facilitate the metronome timing but I cant transfer that value to the "interval" for the blinking light.

In my serial viewer, the equation works and it gives me the values I desire. I just cant get that into the interval.

the math equation is simple (60/bpm)1000 = intended interval

example: (60/120)1000 = 500 as the milli interval for the blinking light. 2 blinks per second.

```
enter code here

// rotary encoder -----------------

int val;
int encoder0PinA = 6;
int encoder0PinB = 7;
int encoder0Pos = 59;
int encoder0PinALast = LOW;
int n = LOW;

// lcd screen ---------------------

     // include the library code:
#include <LiquidCrystal.h>

     // initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// led blink ----------------------

     // the number of the LED pin
const int ledPin =  LED_BUILTIN;

     // ledState used to set the LED
int ledState = LOW;

     // will store last time LED was updated
unsigned long previousMillis = 0;

     // interval at which to blink (milliseconds) --    long interval = ;

// mathssss -----------------------

float a = (60 / encoder0Pos) * 1000;

// on to setup -------------------------------------------------------

void setup() {
      // put your setup code here, to run once:

// rotary encoder ---------------
 pinMode (encoder0PinA, INPUT);
  pinMode (encoder0PinB, INPUT);
  Serial.begin (9600);

  Serial.println ("hi");

// lcd screen -------------------
      // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
      // Print a message to the LCD.
  lcd.print("BeatsPerMinute");

// led blink -------------------
pinMode(ledPin, OUTPUT);

}

// on to loop --------------------------------------------------------
void loop() {
      // put your main code here, to run repeatedly:
      long interval = (60.00 / encoder0Pos) * 1000;

// rotary encoder --------------
  n = digitalRead(encoder0PinA);
  if ((encoder0PinALast == LOW) && (n == HIGH)) {
    if (digitalRead(encoder0PinB) == LOW) {
      encoder0Pos--;
    } else {
      encoder0Pos++;
    }

     // serial ----------------------------------------------------------------------
  Serial.println ("BPM");
  Serial.println (encoder0Pos);
  Serial.println ("interval");
  Serial.println (interval);
  Serial.println ("intended interval");
  Serial.println (60.00 / encoder0Pos * 1000, 8);
  Serial.println ("----------------");
     // serial done -----------------------------------------------------------------
  }
  encoder0PinALast = n;

  // lcd screen ----------------

       // set the cursor to column 0, line 1
       // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
       // print the number of seconds since reset:
  lcd.print(encoder0Pos);

  // led blink -----------------

    unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    digitalWrite(ledPin, ledState);

 // serial --------------------

 // done

  }

}

```

# Answer
As I wrote in my comment, you don't actually set the value of `interval` to the new value, when the encoder position changes. So the blinking interval does not change. You need to use the formula to set the new value to `interval`. Insert

```
interval = 60.00 / encoder0Pos * 1000;

```

before your `Serial.print()` statements. Also, you need to remove the `const` keyword at the definition of `interval`, or you won't be able to change it's value.

---

Judging from your comments, you misunderstand how variables work. A variable does not save a formula, just a value. `a` is defined at global scope in your code (outside of any function). That means, that the definition get's executed at the very start of the program. Since `encoder0Pos` has the value 59 at that time, the value `1016.95` get's assigned to the variable `a`. This value only ever changes, if you actively assign a new value to that variable (which you never do). The formula is only executed once during the assignment.
> 2 votes

---
Tags: arduino-uno, led, timing
---


# Question
Title: FastLED library: How can I adjust the brightness of a single pixel on an absolute scale?
I'm using the FastLED library to control a digital RGB LED strip.

While this library seems very comprehensive in capability and ease of use, I do not yet see a way to simply set the brightness value of a *individual* pixel on an *absolute scale*. In other words, I want to simply set the brightness of a pixel, without passing a hue or saturation, and without it effecting other pixels.

`FastLED.setBrightness()` scales down the brightness of all pixels.
`leds[i].fadeLightBy()` scales down an individual pixel, but if it's called again for the same pixel before updating the LEDs, then the pixel will be faded again from it's already-faded value.

Is there truly no built-in method for setting the brightness of individual pixels to a particular value?

# Answer
There is no dedicated function to adjust brightness.
You can (however) do this by using the HSV color model.

---

**Breaking HSV (Anachronism) into Parts:**

**H** (Hue) Controls the Color itself.
**S** (Saturation) of the Color.
**V** is called Lightness or Value.

**'V'** is what you want to control.
Just set the LEDs color to a HSV value and change it's V value.

```
leds[i] = HSV(color, saturation, brightness);

```

---

While 'Color' and Saturation' remain the same (to keep the same color), you can change the 'Brightness' directly on the third parameter.

Note that 'leds\[i\]' is still defined as 'CRGB', not as 'HSV'.
This assignment uses an implicit conversion, that is defined in the library.

You can see the 'HSV' usage example within the 'Cylon' example on the FastLED library.
There you will find the Hue value that gets changed; but it is the same principle as 'brightness'.

---

Now there is a problem to solve.
The FastLED library can convert 'HSV' Colors to 'RGB' Colors; but not the other way round.
So you cannot simply get the 'hue' and Saturation from an 'RGB' Color with this library.

**You have 2 Alternatives:**

**1.** You can just define an extra LEDs array with HSV colors and synchronize both arrays to contain the same data (everytime you want to change a color, you would set a 'HSV' color in the second array, convert that array to 'RGB' by using 'CRGB(hsv\_leds\[i\])' and save that in the first array, which get's used by the FastLED library).
This is relatively easy, but you effectively need double the memory for storing the color values.
This is not an issue, if you have enough memory or few enough LEDs to control.

**2.** You can write your own function to convert 'RGB' values to 'HSV'; then use it to access the 'hue' and 'Saturation' values for the targeted 'RGB' Color, create a new 'HSV' Color with it and the new 'Brightness' and use it to set the 'RGB' values for the FastLED library.
In this forum thread there is a brief discussion about that, though it leaves you with the implementation yourself.
I think there are suitable implementations, that can be found on the web.
A quick search gave me this code from github gist. I have not tested it, so I cannot say, if it really works correctly, but you should give it a try. I'm sure there are also other implementations.
> 3 votes

---
Tags: library, rgb-led, led-strip
---


# Question
Title: I am making a rubber band gun but i cant seem to get the button to work with my code to turn the servo?
```
#include <Servo.h>
const int buttonPin = 3;
int buttonState = 0;

Servo myservo;
void setup() {
    myservo.attach(2);
    pinMode(buttonPin, INPUT);
}

void loop() {
    buttonState = digitalRead(buttonPin);
    if (buttonState == HIGH){ myservo.write(90); }
    else { myservo.write(155); }
    delay(1000);
}

```

# Answer
Just put your button between pin3 and GND, and use the internal pullup resistor like this:

```
#include <Servo.h>
const int buttonPin = 3;
int buttonState = 0;

Servo myservo;
void setup()
{
    myservo.attach(2);
    pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
    buttonState = digitalRead(buttonPin);
    if(buttonState == LOW)
    {
      myservo.write(90);
    }
    else
    {
      myservo.write(155);
    }
    delay(1000);
}

```
> 1 votes

# Answer
There are two problems you should pay attention to when using the button:
> 0 votes

---
Tags: arduino-ide
---


title: 5v relay module and bulb holder

text:
# Question
Title: 5v relay module and bulb holder
Hello sir , so can i cut the switch from the picture and connect the wires to my relay module ? Im sorry because im still learning . Thank you !

# Answer
> 1 votes
A relay is nothing more than a switch - but instead of your finger controlling it, it's controlled by an electromagnet.

The relay can perform the exact same function as the switch on that cable. In the image you have posted you would use the right-hand two screw terminals (middle is "common", right is "normally open") to replace the switch.

# Answer
> 1 votes
You can refer to this to cut the switch

If you are a beginner, you can get started with Relay here

NOTE: It's dangerous and can cost your life. Please be careful when using Relay with 220 VAC

---
Tags: arduino-uno
---


# Question
Title: ESP12E motorshield analogWrite issue when powering DC motor
I am relatively new to adruino and this whole space. I am currently trying to power a DC motor using an ESP12E motor shield and an ESP8266 Module

Motor Shield - https://www.amazon.com/gp/product/B078CPZDW1/ref=ppx\_yo\_dt\_b\_search\_asin\_title?ie=UTF8&psc=1

ESP8266 - https://www.amazon.com/gp/product/B010O1G1ES/ref=ppx\_yo\_dt\_b\_search\_asin\_title?ie=UTF8&psc=1

DC Motor - https://www.amazon.com/gp/product/B07MTT7B88/ref=ppx\_yo\_dt\_b\_search\_asin\_title?ie=UTF8&psc=1

Here is my code

```
#define DIRA 0
#define PWMA 5
#define LED 2

void setup() {
  Serial.begin(9600);
  Serial.println();
  Serial.println("Starting...");

  Serial.println("Preparing motor...");
  pinMode(DIRA, OUTPUT);
  pinMode(PWMA, OUTPUT);
  analogWrite(PWMA,0);
  digitalWrite(DIRA,1);
  delay(5000);

  Serial.println("Starting motor...");
  analogWrite(PWMA,5);
  delay(5000);

}

void loop() {
}

```

Here is how I have wired it up

**Note: This setup is similar to what I have but not exactly, I have 4 AA batteries connected and only 2 motors**

I am expecting the motor to start once I upload this code but nothing is happening. If I change the analogWrite to digitalWrite, the motor runs but I want to be able to control the speed, rather than just having it run at one speed.

I have tested using analogWrite by changing the intensity of an LED and it was working, although the output pin was not the same as the one I use for the motor.

Would greatly appreciate any help as I have already gone through pages of google searches without any luck. I have been using this example as a reference, https://hackaday.io/project/8856-incubator-controller/log/29291-node-mcu-motor-shield.

# Answer
This answer is the summary of the comments of the question. The idea of the solution was originally mentioned by @Majenko.

You powered the shield with about 6 Volts. The statement `analogWrite(PWMA, 5);` gives you (5/1024) ~ 0.5% of this 6 Volts at the output pin PWMA. This 0.03V are not enough to drive the motor.

You should use at least 3 Volts to drive the motor (as of the specs). This can be achieved by using a duty cycle of the PWM signal of about 50%. `analogWrite(PWMA, 512);` should do the trick.
> 1 votes

---
Tags: esp8266, motor, nodemcu
---


# Question
Title: Creating an array, assigning a value to each indices, and assessing the array
I am trying to create an unassigned array of size 512 and then assigning a reading to each indices. I want to get the start time before and after the loop and only run it once. Then I want to know how to retrieve the readings and serialprint the values after the loop. So far this is what I have but I don't think it is running as I want it to. I was able to get the start time but I'm not sure if it is running afterwards. Any help is greatly appreciated. Thanks!

```
void setup() {
int Vs[512] = {};
int analogPin = A0; // turn pin A0 on
pinMode(9, INPUT);
Serial.begin(9600); // setup serial
analogWrite(9, pow(2, 7)); //LED power 0
int time = micros();
Serial.println(time);
}

void loop() {
int i;
for (int i = 0; i <= 511; i++); { //loop setup for 512
int c = analogRead(A0) * (5.000/1024.000);
int Vs[i] = {c};
Serial.println(Vs[i]);
}
int stoptime = micros();
Serial.println(stoptime);
}

void stop() {
while(1);
}

```

# Answer
> 1 votes
There are multiple issues with your program. The most obvious is that, if you define a variable multiple times, you end up with mutliple *different* variables that share the same name. For example:

```
void setup() {
    int Vs[512] = {};  // this Vs is local to setup()
}

void loop() {
    int i;  // this i is local to loop()
    for (int i = 0;  // this other i is visible within the for loop only
            i <= 511;
            i++)
        ;  // this is the body of the for loop
    {
        ...
        int Vs[i] = {c};  // this Vs is local to loop()
    }
}

```

Another issue I pointed out in the snippet above is that a semicolon by itself is an empty (i.e. do-nothing) statement. Thus you `for` loop is empty.

There is no point in defining a constant such as `analogPin = A0` if you don't use it.

The value returned by `micros()` is not an `int`, it's an `unsigned log`.

If you store a voltage in volts in an `int`, you get a very poor resolution of one volt. You could store in a `float`, but that would fill up the memory of your Arduino. I would rather store the raw readings, and convert to volts only for printing.

`Serial.println()` takes time, and you are doing this during the timed part of your code, which is probably unintended.

Here is a version of your program that may better reflect your intentions. It takes 512 analog readings, stores them in an array, then prints them and reports the time taken to do the readings. Then it waits for one second and repeats the whole thing again.

```
const uint8_t analogPin = A0;
const int readings_count = 512;
int Vs[readings_count];

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

void loop() {
    // Take a run of analog readings.
    unsigned long start_time = micros();
    for (int i = 0; i < readings_count; i++) {
        Vs[i] = analogRead(analogPin);
    }
    unsigned long stop_time = micros();

    // Print the readings.
    Serial.println("Voltage readings:");
    for (int i = 0; i < readings_count; i++) {
        Serial.println(5.0/1024 * Vs[i]);
    }
    Serial.print("Data recorded in ");
    Serial.print(stop_time - start_time);
    Serial.println(" µs");
    Serial.println();

    // Wait before the next run.
    delay(1000);
}

```

If you really want to run only one iteration of the process, then you can just replace `delay(1000);` by `exit(0);`. Alternatively, move the body of `loop()` to the end of `setup()`, and keep an empty `loop()`.

---
Tags: arduino-uno
---


# Question
Title: Sending more than BUFFER_LENGTH(32) bytes in slave answer I2C
I need to send 259 bytes as answer to I2C master read request. AFAIK there is a buffer limit of 32 bytes in Wire.h ~~and in HW (Arduino Nano)~~. Is there a way sending 259 byte answer, or I have to choose another HW?

The code is:

```
void serveInitCommunication() {
  Serial.println("serveInitCommunication()");
  static unsigned int counter = 0;
  auto answer = findInitAnswer(counter);

  uint8_t buffer[260]; //maximum size from dataLengths[] in comm_init_data.h
  memcpy_P(buffer, answer.dataPtrProgmem, answer.dataSize);

  Serial.print(" dataSize:");
  Serial.print(answer.dataSize);
  Serial.print(" data:");
  Serial.println(int(buffer[answer.dataSize - 1]));

  auto bytesToWrite = answer.dataSize;
  uint16_t bytesWritten{0};

  while (bytesToWrite > BUFFER_LENGTH) {
    Serial.println("Write part");
    Wire.write(buffer + bytesWritten, BUFFER_LENGTH);
    bytesToWrite -= BUFFER_LENGTH;
    bytesWritten += BUFFER_LENGTH;
  }
  Serial.print("Bytes written:");
  Serial.print(bytesWritten);
  Serial.print(" Bytes yet to write:");
  Serial.println(bytesToWrite);
  Wire.write(buffer + bytesWritten, bytesToWrite);

  counter++;
}

```

And called is it:

```
void requestHandler() {
  char buff[100];
  sprintf(buff, "requestHandler addr:0x%x counter:%d", readAddress, msgReadCounter);
  Serial.println(buff);

  if (readAddress == INIT_MSG_ADDRESS) {
    serveInitCommunication();
  }
}

```

I've tried moving the `serveInitCommunication()` into `void loop()` and setting a just a flag in `requestHandler()` but without success. Sending up to 32 bytes works fine. Tnx

update: `uint8_t twi_transmit(const uint8_t*, uint8_t);` so twi library self limit data to 255 bytes

update2: there is a hacker way doing it, by replacing the twi.c twi\_txBuffer and twi\_txBufferLength with buffer from the sketch

# Answer
The limitation is purely in software. The I2C hardware has a limit of one byte at a time, and the software creates a 32 byte buffer and feeds each byte from that in turn.

While it would be perfectly possible to increase that buffer size, you may find you have other problems when you get above 255 bytes, since lots of parameters and internal variables for the library are limited to 8 bit values.

It would also be considered very "hacky" since you can't easily upgrade the Wire library in future.

A better strategy would be to split your data into chunks and make multiple requests, each one saying "Give me chunk number ..." and then recombine them upon reception.
> 1 votes

---
Tags: arduino-nano, i2c, wire-library
---


title: External vs internal pullup

text:
# Question
Title: External vs internal pullup
There are two ways of pulling the pins in Arduino – using internal and external resistor. I wonder when I should use external resistor instead of INPUT\_PULLUP.

# Answer
> 3 votes
You can use either the internal or external resistor in normal application.

Each method has each own advantages:

**Internal resistor**

* Pros: flexible to change by changing the code
* Pros: Reduce PCB size
* Pros: Reduce cost (very small)
* Cons: It may make MCU hot

**External resistor**

* Pros: Reduce heat for MCU
* Cons: Not easy to replace when it is built-in PCB
* Cons: Increase PCB size

Besides, Pull-up and pull-down resistors are not only used for INPUT port but also for OUTPUT port. In the case of OUTPUT port. The external resistor has another advantage: flexibility in connecting devices with different I/O voltages. For example, in I2C hardware see I2C at the Hardware Level.

NOTE: As far as I know, at the writing time, Arduino library does NOT support INPUT\_PULLDOWN

# Answer
> 2 votes
"Cons: It may make MCU hot"
It will not. P=V^2/R, so 5\*5/20,000 = 1.25mW, that will not make the processor hot. Even turning all 80 in a Mega2560, and pulling them all low, will only dissipate 0.1W.

"NOTE: As far as I know, at the writing time, Arduino library does NOT support INPUT\_PULLDOWN" That is because Atmega328P, '1284, '2560, etc. family of devices do not have internal pulldown resistors. Only pullup. See Section 14 of their datasheets, "I/O Ports".

This pullup is generally insufficient for I2C pullup, the rising edge created by the 20K to 50K internal pullup is very slow. External 4.7K down to around 2.2K (depends on how many I2C devices are connected) are needed. And the I2C bus spec says they should be at the end of the bus, not the origin of bus (which is generally the processor).

If you have a long wire coming from a button or switch, that is generally a good time to use an external pullup to ensure good switching levels between high and low.

# Answer
> 1 votes
The "Arduino Language" (i.e. the `pinMode()` function) only knows INPUT\_PULLUP.

So you need external resistors for PULLDOWN resistors.

OUTPUT signals are not floating, so the term PULLUP/PULLDOWN resistor does not really apply there.

Besides, the value of an internal pullup resistor is not adjustable. If that value (20 .. 50k) is not appropriate (I²C needs something less than 10k) an external resistor is required.

---
Tags: pull-up
---


title: MCP4725 I2C address

text:
# Question
Title: MCP4725 I2C address
I want to use four of MCP4725 DAC module at the same time but it only has two I2C addresses which can be set via jumpers:

In page 10 of the datasheet it says:

> Device Address Selection pin. This pin can be tied to VSS or VDD, or can be actively driven by the digital logic levels. The logic state of this pin determines what the A0 bit of the I2C address bits should be.

Is there anyway to set more than two addresses for this module? or any hack via hardware/software...

# Answer
> 1 votes
There is a trick to this, and it involves considering one device "active" and all others "inactive".

You only ever work with one address, and that is the address of the "active" unit. All other units are on the secondary "inactive" address which you ignore.

The address pin of each unit is then connected to an IO pin, and can be considered a "chip select" pin.

The sequence, then, is:

* Set unit one's A0 low and all other units HIGH.
* Communicate on Address 0
* Set unit two's A0 LOW and all other units HIGH.
* Communicate on Address 0
* Etc for each unit

Since you never communicate on Address 1 the rest of the "inactive" units ignore all the communication.

---
Tags: i2c, dac
---


title: RS485 communication problem

text:
# Question
Title: RS485 communication problem
I'm trying to achieve RS485 communication between Arduino Mega and Arduino UNO as specified in following link:

https://www.engineersgarage.com/arduino/rs485-communication-between-arduino-mega-and-arduino-pro-mini

But now my problem is The master i.e. Arduino Mega doesn't print anything on Serial Monitor.

Please help me out to solve this issue, trying from week still no success.

---

Sir Peter Paul Kiefer,

Im attaching my circuit setup

Master Code/Mega code

```
void setup()
{
  //Using Serial1 Port
  Serial1.begin(9600);
  Serial.begin(9600);

  //DE/RE Controling pin of RS-485
  pinMode(8, OUTPUT);
}

void loop()
{
  char getdata='m';

  //DE/RE=HIGH Transmit Enabled M1
  digitalWrite(8,HIGH);

  //Write '9' and Fetch Data From Pro Mini
  Serial1.print('9');

  //DE/RE=LOW Receive Enabled M1
  digitalWrite(8,LOW);
  delay(1000);

  //If Serial Data is available
  if(Serial1.available())
  {
    while( Serial1.available() && getdata!='d' )
    {
      getdata=Serial1.read();
      Serial.print(getdata);
    }

    Serial.println("");
  }
}

```

Slave code

```
void setup()
{
  //Serial1.begin(9600);//Uncomment for Arduino Lenardo
  Serial.begin(9600);
  //while(!Serial1);//Uncomment for Arduino Lenardo

  //Led Connected
  pinMode(13, OUTPUT);

  //DE/RE Controling pin of RS-485
  pinMode(8, OUTPUT);
}

void loop()
{
  // put your main code here, to run repeatedly:
  char getdata='c';

  //Led OFF
  digitalWrite(13,LOW);
  //DE/RE=LOW Receive Enabled
  digitalWrite(8,LOW);

  if(Serial.available())
  {
    getdata=Serial.read();
  }

  if(getdata=='9')
  {
     //DE/RE=HIGH Transmit Enabled
     digitalWrite(8,HIGH);

     Serial.print("AcruxTek");
     Serial.print("Isld");
  }

  delay(2000);
  //Led ON
  digitalWrite(13,HIGH);
  delay(2000);
}

```

---

I connected gnd of RS485 converter to arduino gnd and also i did common gnd between circuits but still no output. I used same code nothing changed.. except one thing the example uses arduino pro mini but i used arduino uno as slave

# Answer
> 1 votes
I think there might be two issues in the engineering garage code. delay() function parameter in both codes is not matched. And another thing might cause problem is"Arduino Serial monitor hardware serial is already connected with another usb-serial converter ic which you are using for code uploading, so you cannot use this serial port for rs-485. So using software serial of Arduino pro-mini is a safe option. Finally you have to connect the software Serial pins with rs-485 converter. I have modified the code a little bit and attached the code herewith.

**Arduino Mega code**

```
void setup()
{
  Serial1.begin(9600);//Using Serial1 Port
  Serial.begin(9600);
  pinMode(8, OUTPUT);//DE/RE Controling pin of RS-485
}

void loop()
{
  digitalWrite(8,HIGH);//DE/RE=HIGH Transmit Enabled M1
  Serial1.print('9');//Write '9' and Fetch Data From Pro Mini

  int timeOut = 0;
  digitalWrite(8,LOW);//DE/RE=LOW Receive Enable
  while(!Serial1.available() && timeOut < 5000)
  {
    delay(1);
    timeOut++; // wait 5s to get response from slave
  }
  String response = Serial1.readString();
  Serial.println(response);
}

```

**Arduino Pro-Mini Code**

```
#include <SoftwareSerial.h>
#define RS485_RX 2
#define RS485_TX 3
SoftwareSerial mySerial(RS485_RX,RS485_TX);//Creating object

void setup()
{
  //Serial1.begin(9600);//Uncomment for Arduino Lenardo
  Serial.begin(9600);
  mySerial.begin(9600);
  //while(!Serial1);//Uncomment for Arduino Lenardo

  pinMode(13, OUTPUT);//Led Connected
  pinMode(8, OUTPUT);//DE/RE Controling pin of RS-485
}

void loop()
{
  digitalWrite(13,LOW);//Led OFF
  digitalWrite(8,LOW);//DE/RE=LOW Receive Enable

  while(!mySerial.available())
  {
    delay(1);
  }

  String res = mySerial.readString();
  if (res == "9")
  {
     digitalWrite(8,HIGH);//DE/RE=HIGH Transmit Enabled
     mySerial.print("AcruxTek");
     mySerial.print("Isld");
  }
  digitalWrite(13,HIGH);//Led OFF
}

```

# Answer
> 1 votes
It's not really clear from the picture, but it seems that, the two adapter have no common ground. i.e you have to connect the ground (GND) pin of one the adapter to the GND pin of the other one. But do *not* remove the connection between the GND pins and the arduino GND pins.

I also assume that the mega-adapter is powered with 3.3 V and the UNO-adapter is powered with 5 V (or 3.3V I can not see). This might cause a problem, because the MAX485 chip needs a 5V power supply.

EDIT:

Sorry by a second view a saw, the mega delivers 5 V. So possibly you only have to connect the GNDs of the adapters to solve your problem.

EDIT 2:

I guess the little yellow wire in front of of both adapters connects the DE pins of them. The DE pin of each adapter is also connected to the respective Arduino PIN 8. So it doesn't matter which Arduino is requesting to switch the adapter into the send mode. Both adapters are sending. As far as I know, the adapter only work in Half Duplex you mus define the direction of the data flow. If one adapter is in send mode the other must be in receive mode.

It might also be possible that the DE and RE PIN of each adapter is connected. But this seams strange to me also. With that I would say you setup up one adapter in both receive and send mode and the other in none of them.

EDIT 3:

By looking into the MAX485 Spec. I saw that RE is LOW active but labeled as RE (which I understood as HIGH active), so sorry the last paragraph of my EDIT 2 is nonsense. So, perhaps it's a matter of timing or (more likely) there is still something wrong with the wiring.

EDIT 4:

In the picture I see that you connect the hardware tx and rx pins to the adapter. But Software Serial needs its own pins. Pin0 and Pin1 are connected with the PC Serial Terminal over the built in USB to Serial adapter of the arduino UNO. That's the reason why you need the software serial solution on an arduino. You need a second serial interface and UNO has only one of them which is already used for the connection to the PC (Programming and serial monitor).

In the code I don't see the initialization of the software serial port. This is also necessary:

```
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

// set up a new serial object
SoftwareSerial mySerial (rxPin, txPin);

```

---
Tags: rs485
---


# Question
Title: Ramping up and down arduino motor due to ultrasonic sensor input
Im working on an arduino robot that needs to follower a leader robot infront of it. The leader robot can accelerate, decelerate , and stop and my robot needs to be able to follow the leader without crashing into it.

I have my two sensors working however Im having a harder time integrating the motors to ramp up or down. Currently only one wheel turns on at a time for the right and left commands. How can I appropriatly ramp up or down the wheel speed.

```
int SpRMotor = 5;  //speed Right Motor
int MotorA1 = 7; //Right Motor = +
int MotorA2 = 6; //Right Motor = -
int MotorB1 = 8; //Left Motor = -
int MotorB2 = 9; //Left Motor = +
int SpLMotor = 10;  //speed Left Motor

int TriggerPIN1 = 3;//right
int EchoPIN1 = 2;
int TriggerPIN2 = 12;//left
int EchoPIN2 = 11;

void setup(){
  pinMode(TriggerPIN1,OUTPUT);
  pinMode(EchoPIN1,INPUT);
  pinMode(TriggerPIN2,OUTPUT);
  pinMode(EchoPIN2,INPUT);

  pinMode(MotorB1, OUTPUT);
  pinMode(MotorB2, OUTPUT);
  pinMode(MotorA1, OUTPUT);
  pinMode(MotorA2, OUTPUT);
  pinMode(SpLMotor, OUTPUT);
  pinMode(SpRMotor, OUTPUT);

  analogWrite(SpRMotor, 170);
  analogWrite(SpLMotor, 170);
  Serial.begin(9600);
  }
void loop(){

  int limit;
  int sampledata1, sampledata2;
  sampledata1 = distance(TriggerPIN1, EchoPIN1);
  Serial.print("distance1: ");
  Serial.print(sampledata1);
  delay(100);
  sampledata2 = distance(TriggerPIN2, EchoPIN2);
  Serial.print(" distance2: ");
  Serial.println(sampledata2);
  delay(100);
  limit = 10;
  if((15> sampledata1 >= limit)&&(15> sampledata2 >= limit))
  {
    Serial.print("True");
    forward();
    delay(100);
  }
     if (sampledata2  >= 15 )
    {turnRight();}
  if (sampledata1  >= 15 )
    {turnLeft();}
  if ((limit > sampledata1)&&(limit> sampledata2 ))
  {
    Stop();
  }

}

void forward(){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, HIGH);
digitalWrite(MotorB1, HIGH);
digitalWrite(MotorB2, LOW);
}

void turnRight(){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, LOW);
digitalWrite(MotorB1, HIGH);
digitalWrite(MotorB2, LOW);
}

void turnLeft(){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, HIGH);
digitalWrite(MotorB1, LOW);
digitalWrite(MotorB2, LOW);
}

void Stop(){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, LOW);
digitalWrite(MotorB1, LOW);
digitalWrite(MotorB2, LOW);
}
int distance(int trig, int echo)
{ digitalWrite(trig,LOW);
  delayMicroseconds(2);
  digitalWrite(trig,HIGH);
  delayMicroseconds(10);
  digitalWrite(trig,LOW);
  long timedelay = pulseIn(echo,HIGH);
  int distance = 0.0343 * (timedelay/2);

  return distance;
}

```

# Answer
> 1 votes
The speed seams to be defined by a an analog write to `SpRMotor` and `SpLMotor`. You did that once (with value 170) in the setup. If you use variables for that (e.g. `speedValueL` and `speedValueR`) you can change their values as you need it and write it to the PWM channels on each forward, backward, left or right statement.

A short example:

```
int SpRMotor = 5;  //speed Right Motor
int MotorA1 = 7; //Right Motor = +
int MotorA2 = 6; //Right Motor = -
int MotorB1 = 8; //Left Motor = -
int MotorB2 = 9; //Left Motor = +
int SpLMotor = 10;  //speed Left Motor

int TriggerPIN1 = 3;//right
int EchoPIN1 = 2;
int TriggerPIN2 = 12;//left
int EchoPIN2 = 11;

int speedValueL = 0;
int speedValueR = 0;

void setup()
{
  pinMode(TriggerPIN1,OUTPUT);
  pinMode(EchoPIN1,INPUT);
  pinMode(TriggerPIN2,OUTPUT);
  pinMode(EchoPIN2,INPUT);

  pinMode(MotorB1, OUTPUT);
  pinMode(MotorB2, OUTPUT);
  pinMode(MotorA1, OUTPUT);
  pinMode(MotorA2, OUTPUT);
  pinMode(SpLMotor, OUTPUT);
  pinMode(SpRMotor, OUTPUT);

  analogWrite(SpRMotor, speedValueR);
  analogWrite(SpLMotor, speedValueL);

  Serial.begin(9600);
}

void loop()
{
  int limit;
  int sampledata1, sampledata2;
  sampledata1 = distance(TriggerPIN1, EchoPIN1);
  Serial.print("distance1: ");
  Serial.print(sampledata1);
  delay(100);
  sampledata2 = distance(TriggerPIN2, EchoPIN2);
  Serial.print(" distance2: ");
  Serial.println(sampledata2);
  delay(100);
  limit = 10;
  if( (15> sampledata1 >= limit) && (15> sampledata2 >= limit) )
  {
    Serial.print("True");
    // Just my guess - do what fits for you
    speedValueL = 170;
    speedValueR = 170;

    forward();
    delay(100);
  }

  if (sampledata2  >= 15 )
  {
    // Just my guess - do what fits for you
    speedValueL = 200;
    speedValueR = 0;

    turnRight();
  }

  if (sampledata1  >= 15 )
  {
    // Just my guess - do what fits for you
    speedValueL = 0;
    speedValueR = 200;

    turnLeft();
  }

  if ( ( limit > sampledata1 ) && ( limit> sampledata2 ) )
  {
    // Just my guess - do what fits for you
    speedValueL = 0;
    speedValueR = 0;

    Stop();
  }
}

void forward()
{
  analogWrite(SpRMotor, speedValueR);
  analogWrite(SpLMotor, speedValueL);

  digitalWrite(MotorA1, LOW);
  digitalWrite(MotorA2, HIGH);
  digitalWrite(MotorB1, HIGH);
  digitalWrite(MotorB2, LOW);
}

void turnRight()
{
  analogWrite(SpRMotor, speedValueR);
  analogWrite(SpLMotor, speedValueL);

  digitalWrite(MotorA1, LOW);
  digitalWrite(MotorA2, LOW);
  digitalWrite(MotorB1, HIGH);
  digitalWrite(MotorB2, LOW);
}

void turnLeft()
{
  analogWrite(SpRMotor, speedValueR);
  analogWrite(SpLMotor, speedValueL);

  digitalWrite(MotorA1, LOW);
  digitalWrite(MotorA2, HIGH);
  digitalWrite(MotorB1, LOW);
  digitalWrite(MotorB2, LOW);
}

void Stop()
{
  analogWrite(SpRMotor, speedValueR);
  analogWrite(SpLMotor, speedValueL);

  digitalWrite(MotorA1, LOW);
  digitalWrite(MotorA2, LOW);
  digitalWrite(MotorB1, LOW);
  digitalWrite(MotorB2, LOW);
}

int distance( int trig, int echo )
{
  digitalWrite( trig, LOW );
  delayMicroseconds( 2 );
  digitalWrite( trig, HIGH );
  delayMicroseconds( 10 );
  digitalWrite( trig, LOW );
  long timedelay = pulseIn( echo, HIGH );
  int distance = 0.0343 * ( timedelay / 2);

  return distance;
}

```

---
Tags: arduino-uno, c++
---


title: Use 5V SD-Adapter on 3.3V System

text:
# Question
Title: Use 5V SD-Adapter on 3.3V System
I want to use a Catalex Micro SD Card Adapter in Combination with my Arduino MKR GSM 1400. The problem is, that the Arduino uses 3.3V to operate but the SD Adapter needs 5V (or at least 4.5V) to operate properly. Can I just use the 5V output of my Arduino to power the adapter, or will a higher voltage destroy the arduino when using it over a longer period of time? And if so, how can I use my MKR GSM 1400 with a SD-module? Maybe by unsing a step up/down converter in my circuit or just switch to a module that uses 3.3V?

# Answer
I have seen in several Catalex schematics that show pin 13 of the 74ABT125 is connected directly to GND. This would be correct?
> 0 votes

# Answer
The SD card is a 3.3 V device. The 5 V module with SD card adapter steps down the voltage for powering the card and has logic level conversion for card's SPI pins.

If you want to connect SD card to a 3.3 V board it is better to use a simple breakout board without power and signal conversion.

I do not recommend you to connect a 5 V SPI device to MKR SPI pins without logic level conversion.

EDIT: smajli analyzed in his answer the logic level conversion chip used on the adapter you use. it doesn't output more than 3.3 V and you can use it powered from 5 V. but it is still a workaround.
> 1 votes

# Answer
Catalex Micro SD Card Adapter has built-in level converter in a form of 74LVC125A 3-state buffer. This buffer chip needs 1.65 to 3.6V voltage supply. The +5V from your Arduino is lowered to 3.3V by the adapter (as seen in the schematics, just change 74ABT125 to 74LVC125A).

Link to 74LVC125A
Link to Catalex Adapter schematic

To operate the adapter you would need a certain logic level. Your Arduino provides signals with 3.3V level. This fits perfectly to the adapter. The answer is yes, you can connect your Catalex SD card adapter with your Arduino.
Good luck
> 1 votes

# Answer
You can use the adapter because:

* the adapter uses an AMS1117 to generate 3.3V to supply the SD card and the level shifter
* the level shifter is a 74LVC125 which uses 3.3V and works with 3.3V (and accepts up to 5V as input level)

The adapter works for 3.3V and 5V systems as long as 5V power is available.
> 1 votes

---
Tags: power, sd-card, mkr1000, sd
---


title: Why is this code not working?

text:
# Question
Title: Why is this code not working?
So I am trying to use Port Manipulation to turn on LEDS but I need to use PORT Manipulations for specific reasons.

<pre><code>//22-29PORTA (0x01-0x80)
//30-37PORTC (0x80-0x01)
//38-45PORTD (0x80-0x01)

void setup(){
PORTA =  B0000000; //29--->22
PORTC =  B0000000; //37--->30
PORTD =  B0000000; //45--->38
}

void loop(){
 PORTA =  B1000100;
 PORTC =  B0101000;
 PORTD =  B0000010;
 delay(1000);

 PORTA =  B1010000;
 PORTC =  B0001010;
 PORTD =  B0100000;
 delay(1000);

 PORTA =  B0010100;
 PORTC =  B0100010;
 PORTD =  B0001000;
 delay(1000);

}```
Heres the code for Arduino Mega 2560
</code></pre>

# Answer
> 2 votes
You need to set the ports to output first, before you can use them.

To do that you use the DDRx (Data Direction) registers. Your code should look like:

```
//22-29PORTA (0x01-0x80)
//30-37PORTC (0x80-0x01)
//38-45PORTD (0x80-0x01)

void setup(){
    // Set the pins all to output
    DDRA = 0xFF;
    DDRC = 0xFF;
    DDRD = 0xFF;

    PORTA =  B0000000; //29--->22
    PORTC =  B0000000; //37--->30
    PORTD =  B0000000; //45--->38
}

void loop(){
    PORTA =  B1000100;
    PORTC =  B0101000;
    PORTD =  B0000010;
    delay(1000);

    PORTA =  B1010000;
    PORTC =  B0001010;
    PORTD =  B0100000;
    delay(1000);

    PORTA =  B0010100;
    PORTC =  B0100010;
    PORTD =  B0001000;
    delay(1000);
}

```

You can read more about direct port manipulation here.

---
Tags: arduino-mega
---


# Question
Title: Unused lines of code causing program to crash
I have a project which essentially involves WiFi, a web server, and an LED. I'm using the Inbuilt LED on my ESP8266 for testing at the moment. I am using the Arduino IDE for programming.

I had a problem where my code would crash after connecting to WiFi. By commenting out functions in my loop, I narrowed down the crash problem to my function that handles the LED. Here I ran into a problem, commenting out each block of code individually, and even a few at once, I wasn't able to prevent the crash. There must be more than one line causing the crash. Commenting out the entire function was the only thing that worked.

After hours of troubleshooting, I was left at the stage where I had the contents of all the if statements and loops and such commented out. Here is what left me utterly confused. Here is the if statement:

```
if(webSocketActive){
    Serial.println("websocket is active, setting brightness");
    analogWrite(LED_BUILTIN, 1024 - lightBrightnessAdjust);
} else {
    //other stuff with more if-statements that are empty
}

```

At this point, if I comment out the analogWrite line, the program works fine. But if I leave it like this, it crashes after connecting to WiFi. (I didn't post my entire program because it is over 1000 lines long).

The baffling part about all this is, webSocketActive is never set to true prior to this point in the code... The Serial.println() never does anything, meaning the ESP definitely doesn't execute the instructions inside the if statement. But, for some inexplicable reason, simply having the analogWrite() uncommented crashes the program, even if it never executes that line.

I've also had other issues where putting some sort of Serial.print() function in the loop to repeatedly run somehow doesn't make the code crash. Could someone let me know what is going on?

# Answer
> 0 votes
Turns out that the MDNS.begin() in setup and the MDNS.update() in the loop was, presumable, causing some sort of undefined behaviour, since the code didn't always crash. I commented out these two lines, and the code works fine now, minus the MDNS.

# Answer
> 0 votes
I think I might know the problem (maybe you've fixed it after two weeks) but your `analogWrite(Pin, Val)`might end up being out of range, remember that analogWrite only takes an int of 0 to 255 therefore if your `lightBrightnessAdjust` variable is lower than 769 then we will get an int above the accepted input range of analogWrite().

I know the code never actually runs but it still compiles and maybe Arduino doesn't like even a possible error.

Maybe I didn't explain it very well but here's the Arduino documentation for it.

Another possible solution could be perhaps you could try defining `int amount = 1024-lightBrightnessAdjust;` variable beforehand and then entering the variable into analogRead because it could be fussy about doing math inside the function params (just a thought)

# Answer
> 0 votes
* Overwriting an array could clobber that functions return address.
* Allocating from the heap, enough memory for the up-growing heap and the down-growing stack to collide, could cause or create the conditions for clobbering function-local data, function return-return address, or heap data, including the heap meta-data required to de-allocate that heap-block.
* Writing through an uninitialized or overwritten pointer can cause about any memory corruption you can imagine; and the result can be data dependent and/or data-memory map dependent, and quite possibly non-repeatable.
* Clobbering the interrupt vector of an enabled interrupt can cause improperly jumping into any part of your code, and is *quite likely* to be unrepeatable.

There's too much we don't know about the unseen rest of your code to do much more than speculate on possible points-of-failure.

---
Tags: esp8266, arduino-ide
---


# Question
Title: How can higher current devices (motors, solenoids, lights, etc.) be controlled by an Arduino?
I'm looking for a broadly applicable solution, one that can be adapted to a variety of projects.

I'm currently working on several projects that each require controlling devices ranging from 800mA to 2A from an Arduino Uno. One controls stepper motors, one controls 12vdc solenoid actuators, and one controls 12vdc pneumatic valves.

For example:

The Arduino monitors a button, and each time the button is pressed it triggers the solenoid actuator. Because the Arduino is unable to source the current required by the solenoid, a seperate power supply is required with the Arduino controlling a switch (relay, transistor, etc.) that allows the higher current to pass. For the stepper motor, the layout is more complex as there would need to be four pins controlling four separate switches (to maintain interoperability of the circuit). The relay controls an air valve and requires 12vdc as well.

I'm trying to figure out how to use a single circuit that can be used in each of these applications (and any future projects) that involve controlling higher current devices than the Arduino pins can handle.

Prototyping speed, standardized components, and low cost are the driving factors. Switching speed, useful life, and noise are also important.

Is there a breakout board, circuit, or component that can be connected to an Arduino pin and used to control a high current device? Ideally with a software controlled potentiometer so that the resistance for different projects could be set in the sketch itself.

# Answer
> 13 votes
To drive such high currents, you may have to cascade several transistors (you can also use a Darlington transistor). There are arrays of Darlingtons mounted in a chip (e.g. the ULN2803A has 8 darlington transistors, but is limited to 500mA).

You probably will have to deal with higher power transistors; as an example I have found STMicroelectronics TIP110 which can support switching a 2A current (4A peak), but it would probably need a heatsink to dissipate heat.

Note that I wonder if your steppers really need 2A current (are they that big?). For steppers, you can generally find IC that can drive them easily, e.g. the L293D but this one can drive "only" 600mA).

As a conclusion, I am afraid you will not find a "one size fits all" solution, as all your devices are different and should be driven by the appropriate circuit.

**Edit:**

Since oversizing is not an issue in your prototyping case, then you could go with a **MOSFET** instead of usual bipolar transistors. A MOSFET will be able to drive higher currents and voltages than standard transistors.

The downside is you can use it as a switch only (like e.g. a relay) and thus can't really **drive** the exact power for your devices. I guess that does not matter for a Stepper motor, or a Solenoid, but that may be important for driving lights for instance.

However, the good point is that you can still use PWM for that as the MOSFET switching speed is good enough for such purposes.

Regarding price, there are many diferent kinds of MOSFET out there, but I guess you can find one that fits yours needs (12V, 2A) for less than $1.

I advise you to take a look at this great article about this topic.

# Answer
> 7 votes
There are lots of ways to switch higher loads, and jfpoilpret has described some good options. I'll summarise a couple of relay-based solutions, which are mainly appropriate for comparatively slow switching speeds (i.e. not usually suitable for PWM).

**Solid State Relays**
Solid State Relays (SSRs) are effectively semiconductor-based switches. They come in a wide variety of configurations, depending on your requirements, but the key factor is that they have no moving parts. This means they can be very reliable in the long run if used properly.

Internally, they are usually comprised of MOSFETs and thyristors or similar. This can let them achieve fairly high switching speeds in theory. In practice though, the more power it's designed for, the harder it is to switch quickly. That means high speed + high power can get quite expensive.

A critical factor to bear in mind is that you'll usually need a different type of SSR if you intended to switch AC instead of DC. It's also good to note that some will come with a built-in opto-isolator or similar to keep your power supplies separate.

**Electro Mechanical Relays**
This is the more 'traditional' approach. An Electro Mechanical Relay (EMR) is a fairly simple component, containing a mechanical switch, controlled by a electromagnetic coil. If the switch is normally open, the coil pulls it closed when a control current is applied. In contrast, a normally-closed switch would be pulled open when a control current is applied.

There are a number of advantages of EMRs over things like SSRs. The most obvious is cost -- their simplicity makes them quite cheap, and the cost doesn't rise so sharply for higher-power versions. Additionally, the control and load are inherently isolated, and they don't care whether you're switching AC or DC.

There are several disadvantages though. The mechanical aspect means that EMRs are usually much slower than non-mechanical switching solutions, and can suffer from contact bounce. Additionally, they can physically wear out, and they can be affected by things like shocks, vibrations, and (potentially) other magnetic fields.

When designing a circuit to use an EMR, it's essential to be aware of back-EMF (electromotive force). When a control current is applied, the coil acts as an inductor, storing charge electromagnetically. When the control current is stopped, the stored charge can surge back through the control circuit, creating a large negative voltage spike (potentially much larger than what was originally applied).

This spike can unfortunately damage/destroy any attached components or microcontroller pins. It is typically prevented/mitigated by putting a diode *in reverse* across the relay's control contacts. In this context, it's sometimes known as a flyback diode, and it allows the EMF to dissipate safely.

# Answer
> 3 votes
As jfpoilpret already said, a power MOSFET is great for turning ON and OFF the 12 VDC power to devices that pull up to 44 A. There are dozens of such power MOSFETs for under $1 each. More expensive MOSFETs are available that can handle much higher current and voltage.

In principle it is possible to drive a stepper motor with a microcontroller and a handful of transistors and a few other little parts. However, many people prefer to use a "stepper driver chip", so it is impossible for a software bug to accidentally turn on transistors in such a way as to short the power supply to ground (typically destroying at least 2 transistors). Many recent stepper driver chips also handle microstepping, current limiting, thermal overload protection, and other nice features.

All the stepper driver chips that I've ever heard of, and a few off-the-shelf breakout boards using those chips, are listed at http://reprap.org/wiki/stepper\_motor\_driver .

In particular, many of the RepRap 3D printers I've seen connect an Arduino to four Pololu stepper drivers (under $15 each) to drive five stepper motors.

# Answer
> 1 votes
I made an Arduino( Arduino Nano) circuit to power a 12V Peltier(which is also a high power source.) using a MTP3055V MOSFET 60V 12A transistor. And the circuit is operating very well.

---
Tags: pins, voltage-level
---


# Question
Title: Does AWG size affect signal from sensors?
Would using a thicker cable like 16 AWG affect the signal being received from an RFID or Ultrasonic sensor?

I understand AWG can make a significant impact on voltage when a thick cable is used over a long distance. In my head signal data is delicate so a nice thin wire will ensure little disturbance....

Looked around and couldn't find a clear answer so hopefully someone can help!

# Answer
> 4 votes
A signal is just a varying voltage. A wire is just a (very long) small resistor. The device reading the signal is just a current sink.

That's three terms there: voltage, resistance, and current. Three terms you should know are related by Ohm's Law.

Also, some simple rules:

* The thinner the wire the bigger the resistance
* The longer the wire the bigger the resistance
* The more load on the wire the greater the current

And of course, that all means:

* The greater the resistance or the greater the current, the greater the voltage drop across the wire.

If the voltage drop gets too great then the device receiving the signal won't be able to work out what it is.

But then of course a wire is also an antenna picking up all sorts of noise. The longer the wire the more noise it will pick up. And the thinner the wire the greater the resistance and the greater the resultant voltage drop, meaning the lower the noise margin and immunity.

**So no, a thinner wire isn't better than a thicker wire. The exact opposite is true.**

---
Tags: arduino-uno, sensors, electronics, wires
---


# Question
Title: Addressable RGB strip works fine individually but cannot set all LEDs to full white
I have a 5 meter strip of 12V digital RGB LEDs. The chip is WS2811 (see photo of IC). There are 50 addresses on the strip.

Using the FastLED library, I am able to run the "FirstLight" example that chases full white with a single address at a time, up and down the length. That works fine. So I know they individually perform properly.

However, if I set all LEDs to full white (255), the first few addresses look white but then the higher the address, the more red it is. See photo below. The strip starts in the center of the reel.

```
#include <FastLED.h>

// How many leds are in the strip?
#define NUM_LEDS 50

// Data pin that led data will be written out over
#define DATA_PIN 5

// This is an array of leds.  One item for each led in your strip.
CRGB leds[NUM_LEDS];

// This function sets up the ledsand tells the controller about them
void setup() {
    // sanity check delay - allows reprogramming if accidentally blowing power w/leds
    delay(2000);
    Serial.begin(115200);
    Serial.print("### SETUP ###");

      //Both strips are ordered BRG
      FastLED.addLeds<WS2811, DATA_PIN, BRG>(leds, NUM_LEDS);
      //FastLED.addLeds<UCS1903, DATA_PIN, BRG>(leds, NUM_LEDS);

}

void loop() {

   for (int i = 30; i < NUM_LEDS; i++) {

       leds[i] = CRGB::White;

   }

   FastLED.show();
}

```

---

To debug, I tried turning on just the last half. The result was still problematic:

```
for (int i = 30; i < NUM_LEDS; i++) {

    leds[i] = CRGB::White;

}

```

---

I then tried setting all LEDs to white at half brightness, and that looks much better, but the LEDs at the outside are still off-color compared the inside:

---

I've tried setting the whole strip to full blue, and that works fine.

I also have another nearly identical LED strip that instead uses the 1903 chip. The same code (initialized for 1903 instead of WS2811) works just fine on the 1903 strip!

Other things I've ruled out:

* I'm using a bench power supply capable of 5A, this strip pulls less than 1.5A on full white.
* I have verified the supply holds at 12V
* I have not let the LEDs heat up while coiled in the reel. I make sure to unplug them after observing their color.

What could cause this on the WS2811 strip while the 1903 strip works perfectly?

# Answer
I would suspect that it is a voltage drop in the power rails caused by the current draw. Probably cheap construction with copper tracks that are just too thin and so have too high a resistance.

To combat it you will need to inject power into the strip at various points along it. Initially to prove the theory you can try connecting the power to both ends of the strip and see if the "dull" spot is half way along the strip. If it is, then it's certainly a voltage drop. (incidentally, a voltage drop will cause the blue LEDs to fade out first making it go yellow-red. Then the green ones would probably be next, making it go red).

Then, once proved, you will need to add extra power connections into the strip at the middle of any dim sections and feed the voltage directly in at those points.
> 40 votes

# Answer
Majenko's answer is correct, and you could also verify it with the test performed.

Since it is an issue I encountered myself in the past in a similar case, I want to share some measurements I took on the LED strip I have, in case it can be useful for you or other people.

Premise: the tests were done with a 5m 60 leds/m RGBW strip (SK6812, natural white).

The first test was done to measure the current from each LED. These are the results:

* All LEDs off: 230 mA (0.77 mA/led)
* 10 LEDs to max RED, GREEN or BLUE (one color): 320 mA
* 10 LEDs to max WHITE: 410 mA

This means that each R, G or B led absorbs at max 9 mA, while the W ones have a 18 mA current. Each LED, whether on or off, has a 0.77 mA current flowing through it.

In order to evaluate the voltage drop, I then turned on to full white the first 100 leds, then measured the current, the input voltage and output voltages of the strip. I got a voltage drop from 4.8 V to 4.16 V with a current of 2.11 A (which is almost equal to 230mA + 18mA/led * 100led).

I then modeled the strip as a sequence of ideal current generators joined by resistors:

simulate this circuit – Schematic created using CircuitLab

Calling R the resistance introduced by the strip, I\_Led the current flowing into one LED and N the number of LEDs turned on (and ignoring the effects of the standby current), the voltage drop on the first resistor is dV1 = R*N*I\_Led, the one on the second is dV2 = R\*(N-1)*I\_Led and so on, up to dVN = R*I\_Led. The total voltage drop is dV = R*N*(N+1)\*I\_Led/2.

Using the measured data, we can calculate the resistance between two consecutive LEDs:

R = (2\*dV)/(N\*(N+1)\*I\_Led) = (2\*0.64V) / (100\*101\*0.018A) = 7mOhm

NOTE: this is neglecting the effects of the standby current. However in my calculations I was searching for a worst case, and by excluding these effects I was in fact making worst assumptions, so I did not care about them

So, with this resistance I was able to calculate the voltage drop for arbitrary strips and consequently plan where to put the power supply joints. In my case I planned to have at max stubs 1.2m long (80 LEDs), so that the voltage at the end, in the very worst case (all LEDs on in RGBW, at max brightness), I had a voltage drop of slightly more than 1V.

Note that in my setup the voltage drop on the first element (the one with the largest drop) is (80\*0.045A\*0.007mOhm) = 25mV, with a power dissipation of 90mW.
> 5 votes

# Answer
For completeness, I want to include an RGB circuit simulation I made a while ago, along with some data. It's for analog RGB strips, but the concept regarding voltage drop is the same. I've since added a few more LEDs to show the effect of voltage drop across the length, and added the ability to switch the power connection as well.

The simulation shows the current through each 3-LED segment. 12V strips typically have 3 LEDs in series, and repeat that along the strip.

When I created this simulation, I chose exaggerated resistance values, however, this WS2811 strip may be rather close. I haven't modeled it with particular measurements though.

There are switches in simulation circuit that you can click on to switch the connection to 12V and ground at either end of the strip.

**\[Link to simulation\]**

---

**Results:**

With 12V and ground on the same end: 28.389mA - 27.892mA = **2.123mA difference**

With 12V and ground on both ends: 28.389mA - 27.892mA = **0.497mA difference**

With 12V and ground on opposite ends: 27.310mA - 26.834mA = **0.476mA difference**

**While both power and ground can be connected at both ends of the strip, this simulation actually shows a better balance by simply moving the ground to the opposite end of the strip that receives 12V.**

The only way for each LED segment to be truly balanced would be for each to have it's own connection to power and ground.
> 2 votes

# Answer
Those types of strip are simply not sized for full-on on all LEDs. It's expected that if you wanted that, you'd be running a parallel LED strip for lighting that is not addressible and that uses a much higher voltage such as 12 or 24V, where voltage drop is less critical.

Generally addressible LEDs aren't meant to be used in long strips, but are expected to be fit into an array of some kind with numerous short strips, where each can be fed individually.

Running a long stretch isn't a problem, but you will need to feed power at many locations if you want this level of illumination. And you will get murdered on either wire size or voltage drop because voltage drop is so critical when your voltage is only 5 volts. Crunch the numbers but you can find yourself buying big 1/0 feeder wire in a hurry. I recommend instead carrying power at 24V or mains and converting to 5V in many locations.

I would suggest rethinking the design intent and if illumination is also desired, run a separate strip just for that. Those are dirt cheap.
> 1 votes

# Answer
The LEDs require 12v but the chips require lower voltage. The WS chip requires 3.3v to 5v unlike the 6-7v that the IC require, the added resistance along with the fact that the last led has to run 10 metres on a return trip (5m on positive, 5m on negative = 10m total) could mean the drop is to much.

Easier way to find out is to connect in the middle, if it the problem persists (both ends are bad) it's the power supply
> 1 votes

# Answer
As others have answered, it is because of voltage drop.

If you feed positive to the connector at one end, and negative to the other end, all leds will see the same voltage drop, as all leds have 5m connection to the power supply.

If we call the ends L and R with L+ and L- and R+ and R-:

Connect + to L+ and - to R-

If you want to be advanced, get a power supply with separate output and sense connections.

Then connect sense+ to R+ and sense- to L-

This will ensure that the voltage across the LEDs are 12V, by raising the voltage to compensate for the voltage drop.

I started a drawing in CircuitLab, but they want money now?! How rude...
> 1 votes

---
Tags: rgb-led, led-strip
---


# Question
Title: Using the MIDI library in my own library
---

Error message :

```
"error: invalid declarator before 'MIDI'
         MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
                                                       ^
Plusieurs bibliothèque trouvées pour "libMidi.h"
/home/due32/Arduino/libraries/MIDI/midi_Defs.h:170:31: note: in definition of macro 'MIDI_CREATE_INSTANCE'
     midi::MidiInterface<Type> Name((Type&)SerialPort);"

```

---

libMidi.h

```
#ifndef libMidi_h
#define libMidi_h

#include <Arduino.h>
#include <MIDI.h>

    void midiSetup();
    void pmbMIDI();

//  void MIDI_CREATE_DEFAULT_INSTANCE(); //doesn't work

#endif

```

---

libMidi.cpp

```
#include "libMidi.h"
#include <MIDI.h>

void midiSetup(){

//midi::MidiInterface<Type> Name((Type&)SerialPort);

        void MIDI_CREATE_DEFAULT_INSTANCE();
        void MIDI.begin(MIDI_CHANNEL_OMNI);
}

void pmbMIDI(){
    if (MIDI.getType() == 144){
        digitalWrite(13, 1);}

    if (MIDI.getType() == 128){
        digitalWrite(13, 0);}
}

```

---

Thank you by advance

# Answer
```
void MIDI_CREATE_DEFAULT_INSTANCE();

```

This line should not be placed inside a function, because it is a forward function declaration.

However, I think there are more problems in your code.

My wild guess is to improve the following lines:

* Uncomment line that doesn't work

Change

```
MIDI_CREATE_DEFAULT_INSTANCE();

```

to

```
MIDI_CREATE_DEFAULT_INSTANCE();

```

and place it outside a function.

Remove the word `void` in the following lines

```
void midiSetup();
void pmbMIDI();

```

And also align the { and }

```
void MIDI.begin(MIDI_CHANNEL_OMNI);

```

So it's a function call.

Other improvements is to remove spaces or tabs in

```
    void midiSetup();
    void pmbMIDI();

```

Also align { and } in

```
if (MIDI.getType() == 144){
    digitalWrite(13, 1);}

if (MIDI.getType() == 128){
    digitalWrite(13, 0);}

```
> 0 votes

---
Tags: midi
---


# Question
Title: Sending the data for temperature and soil using esp8266-01 through software serial
The code I used was from online and I tried using it to send data to firebase through web server. But the ouput I get from serial monitor was just "ATE0" which means there's something wrong. Hence, I can't proceed in solving this issue.

I tried several resources online to match my current problem.

I hope someone can help me

Thank you :)

```
#include <SoftwareSerial.h>;
SoftwareSerial Serial1(10, 11);
#include "DHT.h"
#define Terra "terra1"
#define DHTPIN 2

#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

//const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; eyagagana soy

int j=0;
int prev=0;
int pres=0;
String status="";
String buff(64);
String getStr(128);

void setup() {

  Serial.begin(9600);
  Serial1.begin(9600);
//  Serial.println(F("Humiture and Soil Moisture Sensors"));
  delay(2000);
  Serial1.setTimeout(5000);
  dht.begin();

   if (!connectWiFi()) {
    Serial.println("Can not connect to the WiFi.");
    while (true)
      ; // do nothing
  }
  Serial.println("OK, Connected to WiFi.");
  sendCommand("AT+CIPSTA?");
  sendCommand("AT+CIPDNS_CUR?");
  sendCommand("AT+CIPSTAMAC?");

}

void loop() {
 j=analogRead(A0);
  j=map(j,0,982,148,0);
  pres=j;
  if(j>100)
  j=100;
  else if(j<0)
  j=0;

  prev=j;
  delay(1000);

  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
//  if (isnan(h) || isnan(t) || isnan(f)) {
//    Serial.println(F("Failed to read from DHT sensor!"));
//    return;
//  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

//  Serial.print(F("Humidity: "));
//  Serial.print(h);
//  Serial.print(F("%  Temperature: "));
//  Serial.print(t);
//  Serial.print(F("°C "));
//  Serial.print(("Soil Moisture: "));
//  Serial.print(j);
// Serial.println("%");

// connect to server
  if (sendCommand("AT+CIPSTART=\"TCP\",\"https://terraduino.000webhostapp.com\",80")) {
    Serial.println("connected to Cloud");
    // build HTTP request
    getStr = "GET /upload.php?terra=";
    getStr += Terra;
    getStr += "&j=";
    getStr += j;
    getStr += "&t=";
    getStr += t;
    getStr += "&h=";
    getStr += h;
    getStr += " HTTP/1.1\r\n";
    //WEBSERVER
    getStr += "Host: https://terraduino.000webhostapp.com\r\n\r\n";
    // open send buffer
    buff = "AT+CIPSEND=";
    buff += getStr.length();
    if (sendCommand(buff.c_str()) && Serial1.find(">")) { // AT firmware is ready to accept data
      // send HTTP request
      Serial.println(getStr);
      Serial1.print(getStr);
      // print HTTP response
      if (Serial1.find("+IPD,")) { // response received
        int l = Serial1.parseInt();
        while (l > 0) {
          if (Serial1.available()) {
            Serial.write(Serial1.read());
          }
        }
        Serial.println("--------------");
      } else {
        Serial.println("no response");
      }
    } else {
      Serial.println("send error");
    }
    sendCommand("AT+CIPCLOSE");
  } else {
    Serial.println("Error connecting");
  }
}
bool connectWiFi() {
  if (!sendCommand("ATE0")) // echo off
    return false;
  if (!sendCommand("AT+CIPMUX=0")) // set single connection mode
    return false;
  if (!sendCommand("AT+CWMODE=1")) // set STA mode
    return false;

  return sendCommand("AT+CWJAP=\"I Pronounce you Man and Wifi\",\"-PX?*z3A_1x@.exe\"");
}
bool sendCommand(const char* cmd) {
  Serial.println(cmd);
  Serial1.println(cmd);
  while (true) {
    buff = Serial1.readStringUntil('\n');
    buff.trim();
    if (buff.length() > 0) {
      Serial.println(buff);
      if (buff == "OK" || buff == "SEND OK" || buff == "ALREADY CONNECTED")
        return true;
      if (buff == "ERROR" || buff == "FAIL" || buff == "SEND FAIL")
        return false;
    }
  }
}

```

# Answer
> 1 votes
I would say you are trapped in the `sendCommand` function. You print the `cmd` (cmd="ATE0") variable to the terminal and then send the command to the ESP over Serial1 = software serial. Serial1 is configured with a baud rate of 9600 (`Serial1.begin(9600)`) it depends on your ESP but that might be wrong. A common value is 115200 (`Serial1.begin(115200)`). But because that can vary from board to board, it could also be wrong.

If I'm right and you configured a wrong baud rate, the command can not be understood by the ESP and even the newline after the command might be missing for it.

So the ESP send nothing back and the 'buff.length()' equals to 0. Then the `while(true)` runs and runs and runs ... .

---
Tags: arduino-uno, esp8266, temperature-sensor
---


title: Improvised Keyboard?

text:
# Question
Title: Improvised Keyboard?
I want to make a keyboard type panel, which will only have 7 buttons and two knobs, and connect it arduino to program it with functions, he heard that he needed the Keyboard library. but it is not available with arduino uno, which is what I work with, he heard about what I should do a keyboard mapping, it would help me explain to lay a foundation and carry out the project that I want "please do not leave me with the doubt". first of all, Thanks.

# Answer
If you plan to trigger function on a PC by keystroke and want to simulate a PC keyboard on the PC with your computer than I recommend to use the keyboard lib which is able to map your button to key codes and send them to a PC over USB. But the communication over USB and the simulation of a HID (Human Interface Device) connection is (as far as I know) not possible with an Arduino. (You need a 32u4 or SAMD micro based board) like the leonardo.

But if you just plan to trigger functions, that run on the Arduino, the kb lib is not necessary. That a standard job for the Arduino and can be done with 7 input pins and 2 analog pins.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Too slow start up with Atmega2560 on custom PCB
I have some several custom PCB's based on Atmega 2560. I am using AVRISP MarkII for flashing. No bootloader.

Flashing is flawless, it just works. I have one assembled PCB works as it should be, no issues.

But, the other one has a quite time lag in its functions. It has also been flashed OK but, it is not running quite OK.

**Here are my observations;**

By asserting Reset, I expect four leds on the pcb running (on and then off) by 100ms intervals one after each others. This is happening in the very beginning in Setup() section of the program.

**Note that:** Leds are connected to MCU via mosfets. If MCU output is LOW, they are ON and vice versa.

So, with this problematic PCB, all leds come ON all together after 10 seconds after pressing reset button and they stay almost 60 seconds before they start the sequence (on and then off) as coded.

And then that sequence is also slowly occurring. It is not 100ms as I coded but almost 4 seconds or so.

I am suspecting from the external clock (16Mhz) circuitry but I can't proof it accurately as I don't have oscilloscope at hand.

You may see the simple code I use to test that behavior;

```
void TestLeds() {
    unsigned long interval = 100;

    digitalWrite(LED1_PIN, LOW);
    delay(interval);
    digitalWrite(LED1_PIN, HIGH);
    delay(interval);

    digitalWrite(LED2_PIN, LOW);
    delay(interval);
    digitalWrite(LED2_PIN, HIGH);
    delay(interval);

    digitalWrite(LED3_PIN, LOW);
    delay(interval);
    digitalWrite(LED3_PIN, HIGH);
    delay(interval);

    digitalWrite(LED4_PIN, LOW);
    delay(interval);
    digitalWrite(LED4_PIN, HIGH);
}

```

How/where should I check the bottle-neck on that?

Thank you.

**EDIT:**

To be more specific, I add this output regarding programming; here

# Answer
> 1 votes
I am closing the case. It is not 100% satisfaction though. Because, using Visual Studio with Visual Micro didn't help me on that issue in a natural way but something else.

For the future reference for somebody might get benefit out of this, I like to explain here what I did to get over this issue briefly. As @Gerben (big credits go to him) has pointed the right direction, I did check fuses by installing Atmel Studio 7 and use its programmer.

Yes, the fuses were completely wrong. I have therefore read the fuses from my healthy PCB and noted aside and then applied these very same fuse settings to the slow working PCB. I have just programmed the fuses, Firmware was the one I programmed earlier in the uC. So, voilà, the slowness has gone.

I think I am going to use Atmel Studio 7 now on next to Visual Studio as it has everything built-in including Arduino support.

Thanks everybody involved.

# Answer
> 0 votes
Just burn the bootloader via arduino ide before you burn your firmware. During bootloader burning, ide also configures the fuse bits you needed.

---
Tags: arduino-mega
---


# Question
Title: Can't connect to my ESP32 board via serial
I'm completely new to electronics work.

Today I've received the ESP32 board that I ordered. (It's a WROOM-32.) I followed the instructions here. I connected the board to my computer via USB and I successfully installed the CP210x drivers and got a new serial port COM3, but when I tried to connect to the board with that serial port, I got nothing. I'm on Windows 7.

I tried with Tera Term, and it just shows an empty screen.

I tried `type COM3` in the shell, but got an empty string.

I tried doing `esptool.exe --chip esp32 -p com3 erase_flash`, but I get "Failed to connect to ESP32: Timed out waiting for packet header".

I tried playing with the two buttons on the WROOM32 board, but that didn't help.

Any idea what I'm doing wrong? I'm a complete newbie so it's likely that I'm forgetting something basic.

# Answer
> 1 votes
The issue is that the Serial port on the ESP32-WROOM setup is not like like on the Arduino. It seems that the initialisation will 'miss' the USB enumeration after reboot.

To fix this add a delay in your setup() function of 10 to 15-seconds before initialising the serial.

For example:

```
void setup() {
  delay(10000);
  Serial.begin(115200);

  Serial.println("Setting up Access Point...");
  .
  .
  .

```

---
Tags: serial, uart, esp32
---


title: EEPROM.get returns bad data

text:
# Question
Title: EEPROM.get returns bad data
I am using the attached code. What I am trying to do is:

Test if there is a personalized "board serial number" written in the EEPROM (by previous code run) If data found was not 7 characters (e.g `SN-XXXX`), then generate a serial number and save it to EEPROM

Problem is: it generates a serial correctly, it even stores and reads it a few times, but when I disconnect the USB cable and reconnect to test again, it returns some bad data from the EEPROM, like: `⸮^R⸮y⸮|` which seems to pass my 7 characters test and it doesn't generate a new one.

What am I doing wrong ?

```

#include <EEPROM.h>

// board SERIAL number
char serial_characters[] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"};
// will be filled as SN-A2KH
String serial_number;

void setup() {

  Serial.begin(9600);

  // Get the float data from the EEPROM at position 0
  EEPROM.get(0, serial_number);

  // serial from EEPROM valid
  if (serial_number.length() == 7) {
    Serial.println("Found valid serial in EEPROM");
    Serial.println(serial_number);
  }

  // serial from EEPROM not valid (e.g not: SN-XYZ5)
  if (serial_number.length() != 7) {

    Serial.println("Serial from eeprom is NOT 7 chars, generating a random serial");
    Serial.println(serial_number);

    // if analog input pin 0 is not connected, use noise from it in order to generate a random seed, otherwise random is not so random
    randomSeed(analogRead(0));

    // serial might be empty now, set a "SN-" prefix
    serial_number = "SN-";
    for (int i = 1; i <= 4 ; i++) {
      serial_number = serial_number + serial_characters[random(0, 35)];
    }
    Serial.println("Generated serial now: " + serial_number);

    // save to eeprom if format is valid
    if (serial_number.length() == 7) {
      EEPROM.put(0, serial_number);
      Serial.println("Written serial to EEPROM");
    }

  } // <<< serial from eeprom not correct, generated one

}

void loop() {}

```

# Answer
> 7 votes
You are saving a String object in EEPROM, which is useless. A string object does not store the contents of your string. Instead, it just stores:

* the memory address where the actual contents (the characters) is stored
* the amount of memory allocated for this contents
* the number of characters that actually make the string

This is what you are storing to, and retrieving from EEPROM. So you get the correct number of characters (third item in the list above), but the memory address now points to uninitialized RAM.

I suggest instead storing in the EEPROM a raw C string, i.e. an array of 8 chars (7 printable chars plus the terminating NUL). You could achieve this by just changing the declaration of `serial_number`:

```
char serial_number[8];

```

For checking the validity, I would just check that it starts with "SN-" and the last char is a NUL:

```
if (memcmp(serial_number, "SN-", 3) == 0 && serial_number[7] == '\0') {
    ...
}

```

You could do a more stringent validation though, and check that the other 4 chars are within the valid set.

**Edit**: to build `serial_number` with random chars:

```
strcpy(serial_number, "SN-");
for (int i = 3; i < 7; i++)
  serial_number[i] = serial_characters[random(0, 36)];
serial_number[7] = '\0'; // terminating NUL

```

# Answer
> 3 votes
Just to have the full working code, I ended up with this:

```
#include <EEPROM.h>

char serial_characters[] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"};
// 7 chars for serial and one for string end '\0'
char serial_number[8];

void setup() {

  Serial.begin(115200);

  EEPROM.get(0, serial_number);

  // check found format
  if (serial_number[0] == 'S' && serial_number[1] == 'N'  && serial_number[2] == '-' && serial_number[7] == '\0') {

    Serial.println("serial from eeprom is valid");
    Serial.println((char*)serial_number);

  } else {

    Serial.println("no valid serial found in eeprom, generating new serial");

    // if analog input pin 0 is unconnected, use noise from it in order to generate a random seed, otherwise random is not so random
    randomSeed(analogRead(0));

    // generate a new serial
    serial_number[0] = 'S';
    serial_number[1] = 'N';
    serial_number[2] = '-';

    // overwrite ending chars of serial with random values
    serial_number[3] = serial_characters[random(0, 35)];
    serial_number[4] = serial_characters[random(0, 35)];
    serial_number[5] = serial_characters[random(0, 35)];
    serial_number[6] = serial_characters[random(0, 35)];

    // end string with null as raw C strings ?!
    serial_number[7] = '\0';

    Serial.println((char*)serial_number);

    // write new serial to eeprom
    EEPROM.put(0, serial_number);

  }

}

void loop() {

}

```

---
Tags: serial, eeprom, datalogging, flash, baud-rate
---


# Question
Title: Calling functions from an array of pointers in a library causes 'undefined reference to' error
I am trying to create a library, where I have an array of pointers to functions in it. This array is used by other functions in the library. This is the code of the header file:

```
class Lib {
  public:
    static void call();
    static void (*caller[])();
  private:
};

```

This is the code of the .cpp-file:

```
#include "Lib.h"

void (*caller[2])();

void Lib::call() {
  caller[0]();
}

```

The sketch executing this is

```
#include <Lib.h>

void setup() {
  Lib::call();
}

void loop() {}

```

When I try to compile this, I get the following error:

> undefined reference to \`Lib::caller'
> collect2: error: ld returned 1 exit status
> Mehrere Bibliotheken wurden für "Lib.h" gefunden

Another weird thing is that the error about the multiple found libraries goes away if I take away the line

```
Lib::call();

```

However, if I put the same code directly into the sketch like so:

```
void (*caller[2])();

void call() {
  caller[0]();
}

void setup() {
  call();
}

void loop() {}

```

I get no error. What's the problem here?

# Answer
> 0 votes
```
void (*caller[2])();

```

should be:

```
void (*Lib::caller[2])();

```

Since you are defining storage space for a static member variable you have to tell the compiler what class it's a static member of.

---
Tags: library, pointer
---