# Question
Title: Detect certain characters and if not a consequence
How can I program in Arduino Uno a `serial.available` that will detect some chars that aren't supposed to belong in a list of options, like this:

```
void lerRespostaUtilizador(){
  if(Serial.available('s' && 'v' && 'r'){
    Serial.println("Podes visualizar: (s)inais de controlo, (v)ariaveis do sistema e conteudo de (r)egistos.")
  }
  switch(Serial.read()){
    case 's': // Mostrar sinais de controlo
      mostrarSinais();
      Serial.println("Podes visualizar ainda: (v)ariaveis do sistema e conteudo de (r)egistos.");
      Serial.println("");
      break;
    case 'v': // Mostrar variáveis do sistema
      mostrarVariaveis();
      Serial.println("Podes visualizar ainda: (s)inais de controlo e conteudo de (r)egistos.");
      Serial.println("");
      break;
    case 'r': // Mostrar conteúdo de registos
      mostrarRegistos();
      Serial.println("Podes visualizar ainda: (s)inais de controlo e (v)ariaveis do sistema.");
      Serial.println("");
      break;
    }
}

```

What I want is if the user inserts some chars that aren't 's', 'v' or 'r', a message will appear saying what they can insert to obtain certain results.

# Answer
I would rewrite that as something like this:

```
void lerRespostaUtilizador(){
  while (!Serial.available());
  switch(Serial.read()){
    case 's': // Mostrar sinais de controlo
      mostrarSinais();
      break;
    case 'v': // Mostrar variáveis do sistema
      mostrarVariaveis();
      break;
    case 'r': // Mostrar conteúdo de registos
      mostrarRegistos();
      break;
    default:
      Serial.println(F("Podes visualizar: (s)inais de controlo, (v)ariaveis do sistema e conteudo de (r)egistos."));
    }
}

```
> 1 votes

---
Tags: arduino-uno, programming
---


title: 5pt font for Neopixel shield

text:
# Question
Title: 5pt font for Neopixel shield
I have a 5x8 Neopixel shield for my Arduino. I want to display text on it, while it is in "landscape mode", i.e. a only 5pt high text. The default font that is used by the `print`command is 8pt high. How can I load a font with 5pt height into my code?

I understand that the Neopixel library depends on `Adafruit GFX`, which allows for different fonts. But changing the font according to the Adafruit tutorial on GFX to one of the supplied fonts does not return any readable text (only a moving line of dots). I found this font converter and used it to produce a 5pt font, but again only a moving dot appears.

This is my code (basically the Neomatrix example with modified orientation of the matrix):

```
// Adafruit_NeoMatrix example for single NeoPixel Shield.
// Scrolls 'Howdy' across the matrix in a portrait (vertical) orientation.

#include <Adafruit_GFX.h>
#include <Adafruit_NeoMatrix.h>
#include <Adafruit_NeoPixel.h>
#include <Fonts/Dialog_plain_5.h>
#ifndef PSTR
 #define PSTR // Make Arduino Due happy
#endif

#define PIN 6

Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(8, 5, PIN,
  NEO_MATRIX_TOP     + NEO_MATRIX_LEFT+
  NEO_MATRIX_ROWS + NEO_MATRIX_PROGRESSIVE,
  NEO_GRBW  + NEO_KHZ800);

const uint16_t colors[] = {
  matrix.Color(255, 0, 0), matrix.Color(0, 255, 0), matrix.Color(0, 0, 255) };

void setup() {
  matrix.setFont(&Dialog_plain_5);
  matrix.begin();
  matrix.setTextWrap(false);
  matrix.setBrightness(30);
  matrix.setTextColor(colors[0]);
}

int x    = matrix.width();
int pass = 0;

void loop() {
  matrix.fillScreen(0);
  matrix.setCursor(x, 0);
  matrix.print(F("Howdy"));
  if(--x < -36) {
    x = matrix.width();
    if(++pass >= 3) pass = 0;
    matrix.setTextColor(colors[pass]);
  }
  matrix.show();
  delay(100);
}

```

and this is the content of the font file:

```
// Created by http://oleddisplay.squix.ch/ Consider a donation
// In case of problems make sure that you are using the font file with the correct version!
const uint8_t Dialog_plain_5Bitmaps[] PROGMEM = {

    // Bitmap Data:
    0x00, // ' '
    0xF0, // '!'
    0xC0, // '"'
    0x07,0xF2, // '#'
    0x79,0xF4, // '$'
    0xD1,0x10,0xB0, // '%'
    0x88,0xCA, // '&'
    0x80, // '''
    0x2A,0x00, // '('
    0x15,0x00, // ')'
    0x08,0x00, // '*'
    0x01,0x1C,0x40, // '+'
    0x00, // ','
    0xC0, // '-'
    0x00, // '.'
    0x6A,0x00, // '/'
    0xD6,0xE0, // '0'
    0xC9,0x20, // '1'
    0x62,0x48, // '2'
    0xE8,0xE0, // '3'
    0x26,0x62, // '4'
    0x08,0x90, // '5'
    0x7A,0xE0, // '6'
    0x25,0x20, // '7'
    0xEA,0xE0, // '8'
    0xD5,0xE0, // '9'
    0x00, // ':'
    0x00, // ';'
    0x02,0xC6, // '<'
    0x77, // '='
    0x06,0x16, // '>'
    0xD0, // '?'
    0x27,0xB7,0x66,0x00, // '@'
    0x4A,0x68, // 'A'
    0xFA,0xD0, // 'B'
    0x68,0x86, // 'C'
    0xE9,0x9A, // 'D'
    0xDA,0x40, // 'E'
    0x9A,0x40, // 'F'
    0x78,0xB5, // 'G'
    0xBE,0xD0, // 'H'
    0xF0, // 'I'
    0x55,0x40, // 'J'
    0xAC,0xCA, // 'K'
    0x92,0x40, // 'L'
    0x9F,0xF9, // 'M'
    0xBF,0xD0, // 'N'
    0x69,0x96, // 'O'
    0xF7,0x40, // 'P'
    0x69,0x96,0x00, // 'Q'
    0xEA,0xCA, // 'R'
    0x91,0x60, // 'S'
    0x21,0x08,0x40, // 'T'
    0xB6,0xE0, // 'U'
    0xAA,0xA4, // 'V'
    0xAF,0xBC,0xA0, // 'W'
    0xA4,0x4A, // 'X'
    0x53,0x08,0x40, // 'Y'
    0x64,0x88, // 'Z'
    0xAA,0x80, // '['
    0xAA,0x40, // '\'
    0x55,0x40, // ']'
    0x61, // '^'
    0x70, // '_'
    0x00, // '`'
    0xDE,0x80, // 'a'
    0x9A,0xE0, // 'b'
    0x92,0x00, // 'c'
    0x3E,0xD0, // 'd'
    0xDE,0x00, // 'e'
    0x49,0x20, // 'f'
    0xF6,0xA0, // 'g'
    0x9E,0xD0, // 'h'
    0xF0, // 'i'
    0x55,0x40, // 'j'
    0x9A,0x60, // 'k'
    0xF0, // 'l'
    0xFD,0x6A, // 'm'
    0xF6,0x80, // 'n'
    0xD7,0x00, // 'o'
    0xD7,0x40, // 'p'
    0xF6,0xB0, // 'q'
    0x2A, // 'r'
    0x4C,0x80, // 's'
    0x49,0x20, // 't'
    0x16,0xD0, // 'u'
    0xB9,0x00, // 'v'
    0xD7,0x60, // 'w'
    0xCB,0x00, // 'x'
    0xB9,0x40, // 'y'
    0x68, // 'z'
    0x4A,0x24, // '{'
    0xF8, // '|'
    0x48,0xA4 // '}'
};
const GFXglyph Dialog_plain_5Glyphs[] PROGMEM = {
// bitmapOffset, width, height, xAdvance, xOffset, yOffset
      {     0,   1,   1,   3,    0,    0 }, // ' '
      {     1,   1,   4,   3,    0,   -4 }, // '!'
      {     2,   2,   2,   3,    0,   -4 }, // '"'
      {     3,   4,   4,   5,    0,   -4 }, // '#'
      {     5,   3,   5,   4,    0,   -4 }, // '$'
      {     7,   5,   4,   6,    0,   -4 }, // '%'
      {    10,   4,   4,   5,    0,   -4 }, // '&'
      {    12,   1,   2,   2,    0,   -4 }, // '''
      {    13,   2,   5,   3,    0,   -4 }, // '('
      {    15,   2,   5,   3,    0,   -4 }, // ')'
      {    17,   3,   3,   4,    0,   -4 }, // '*'
      {    19,   5,   4,   6,    0,   -4 }, // '+'
      {    22,   2,   3,   3,    0,   -2 }, // ','
      {    23,   2,   1,   3,    0,   -2 }, // '-'
      {    24,   2,   1,   3,    0,   -1 }, // '.'
      {    25,   2,   5,   3,    0,   -4 }, // '/'
      {    27,   3,   4,   4,    0,   -4 }, // '0'
      {    29,   3,   4,   4,    0,   -4 }, // '1'
      {    31,   4,   4,   4,    0,   -4 }, // '2'
      {    33,   3,   4,   4,    0,   -4 }, // '3'
      {    35,   4,   4,   5,    0,   -4 }, // '4'
      {    37,   3,   4,   4,    0,   -4 }, // '5'
      {    39,   3,   4,   4,    0,   -4 }, // '6'
      {    41,   3,   4,   4,    0,   -4 }, // '7'
      {    43,   3,   4,   4,    0,   -4 }, // '8'
      {    45,   3,   4,   4,    0,   -4 }, // '9'
      {    47,   2,   3,   3,    0,   -3 }, // ':'
      {    48,   2,   4,   3,    0,   -3 }, // ';'
      {    49,   4,   4,   5,    1,   -4 }, // '<'
      {    51,   4,   2,   5,    0,   -3 }, // '='
      {    52,   4,   4,   5,    0,   -4 }, // '>'
      {    54,   2,   4,   4,    0,   -4 }, // '?'
      {    55,   5,   5,   6,    0,   -4 }, // '@'
      {    59,   4,   4,   4,    0,   -4 }, // 'A'
      {    61,   3,   4,   4,    0,   -4 }, // 'B'
      {    63,   4,   4,   4,    0,   -4 }, // 'C'
      {    65,   4,   4,   5,    0,   -4 }, // 'D'
      {    67,   3,   4,   4,    0,   -4 }, // 'E'
      {    69,   3,   4,   4,    0,   -4 }, // 'F'
      {    71,   4,   4,   5,    0,   -4 }, // 'G'
      {    73,   3,   4,   4,    0,   -4 }, // 'H'
      {    75,   1,   4,   2,    0,   -4 }, // 'I'
      {    76,   2,   5,   2,   -1,   -4 }, // 'J'
      {    78,   4,   4,   4,    0,   -4 }, // 'K'
      {    80,   3,   4,   4,    0,   -4 }, // 'L'
      {    82,   4,   4,   5,    0,   -4 }, // 'M'
      {    84,   3,   4,   4,    0,   -4 }, // 'N'
      {    86,   4,   4,   5,    0,   -4 }, // 'O'
      {    88,   3,   4,   4,    0,   -4 }, // 'P'
      {    90,   4,   5,   5,    0,   -4 }, // 'Q'
      {    93,   4,   4,   4,    0,   -4 }, // 'R'
      {    95,   3,   4,   5,    1,   -4 }, // 'S'
      {    97,   5,   4,   4,   -1,   -4 }, // 'T'
      {   100,   3,   4,   4,    0,   -4 }, // 'U'
      {   102,   4,   4,   4,    0,   -4 }, // 'V'
      {   104,   5,   4,   6,    0,   -4 }, // 'W'
      {   107,   4,   4,   4,    0,   -4 }, // 'X'
      {   109,   5,   4,   4,   -1,   -4 }, // 'Y'
      {   112,   4,   4,   6,    1,   -4 }, // 'Z'
      {   114,   2,   5,   3,    0,   -4 }, // '['
      {   116,   2,   5,   3,    0,   -4 }, // '\'
      {   118,   2,   5,   3,    0,   -4 }, // ']'
      {   120,   4,   2,   5,    0,   -4 }, // '^'
      {   121,   4,   1,   4,   -1,    1 }, // '_'
      {   122,   2,   1,   4,    0,   -4 }, // '`'
      {   123,   3,   3,   5,    1,   -3 }, // 'a'
      {   125,   3,   4,   4,    0,   -4 }, // 'b'
      {   127,   3,   3,   4,    0,   -3 }, // 'c'
      {   129,   3,   4,   4,    0,   -4 }, // 'd'
      {   131,   3,   3,   5,    1,   -3 }, // 'e'
      {   133,   3,   4,   3,   -1,   -4 }, // 'f'
      {   135,   3,   4,   4,    0,   -3 }, // 'g'
      {   137,   3,   4,   4,    0,   -4 }, // 'h'
      {   139,   1,   4,   2,    0,   -4 }, // 'i'
      {   140,   2,   5,   2,   -1,   -4 }, // 'j'
      {   142,   3,   4,   4,    0,   -4 }, // 'k'
      {   144,   1,   4,   2,    0,   -4 }, // 'l'
      {   145,   5,   3,   6,    0,   -3 }, // 'm'
      {   147,   3,   3,   4,    0,   -3 }, // 'n'
      {   149,   3,   3,   4,    0,   -3 }, // 'o'
      {   151,   3,   4,   4,    0,   -3 }, // 'p'
      {   153,   3,   4,   4,    0,   -3 }, // 'q'
      {   155,   2,   4,   3,    0,   -4 }, // 'r'
      {   156,   3,   3,   5,    0,   -3 }, // 's'
      {   158,   3,   4,   3,   -1,   -4 }, // 't'
      {   160,   3,   4,   4,    0,   -4 }, // 'u'
      {   162,   3,   3,   4,    0,   -3 }, // 'v'
      {   164,   4,   3,   5,    0,   -3 }, // 'w'
      {   166,   3,   3,   4,    0,   -3 }, // 'x'
      {   168,   3,   4,   4,    0,   -3 }, // 'y'
      {   170,   2,   3,   5,    1,   -3 }, // 'z'
      {   171,   3,   5,   4,    0,   -4 }, // '{'
      {   173,   1,   6,   2,    0,   -4 }, // '|'
      {   174,   3,   5,   4,    0,   -4 } // '}'
};
const GFXfont Dialog_plain_5 PROGMEM = {
(uint8_t  *)Dialog_plain_5Bitmaps,(GFXglyph *)Dialog_plain_5Glyphs,0x20, 0x7E, 7};

```

# Answer
> 3 votes
I was having the same problem until I read the library source code. Later I found the documentation reference.

The classic font cursor position is defined as the top-left corner of the character cell. For GFX and custom fonts it is the 'y' position is relative to the baseline of the character cell.

My display is 5 by 5. The TomThumb font is 3 by 5. Instead of `matrix.setCursor(x, 0);` I needed to use `matrix.setCursor(x, 5);` so the 'y' coordinate corresponds with the bottom of the pixel matrix, not the top.

It's described in Adafruit's docs.

---
Tags: led, adafruit, neopixel
---


title: Should I use OOP?

text:
# Question
Title: Should I use OOP?
I am a long time participant in a competition called Robocup Rescue Line. For next year's competition, I am building a robot (and the code for the robot) from the ground up. The tasks that the robot has to do are complex enough for the code to be a fairly complex thing. I have some experience with classes and OOP so I thought I could try to organize the code in a OOP fashion. I thought I could have a class for each type of Sensor (e.g: LineSensor(), RGBSensor UltraSound()...) and another for the Motors (e.g: Motor()) that would have two instances on the code. Basically, all the code has to do is take sensor readings and produce a motor response. With this class structure, where would I do this correspondence? Is this not appropriate for this kind of project? Is there a better way to do this, that is still OOP?

# Answer
> 1 votes
I have a lot of experience with OOP, but mostly in embedded/pure software designs. However, I'm sure you can use it in a robot project too.

Avoid creating lots of objects dynamically, this results in gap in the very small memory available for the Uno. Try to create the object instances beforehand (this will also benefit performance hits during execution, by placing it into the initialization).

About the Sensors: you can make a baseclass if needed (Sensor) and let other classes derive from it (there is a small performance hit when calling methods though).

For the controlling:

* Put sensor readings in the sensor classes
* Put motor responses in the motor classes
* Put the control in a special class (Control?) that couples the sensor response to the motor response.

---
Tags: c++, c, class
---


title: LED series Resistor- Noob question

text:
# Question
Title: LED series Resistor- Noob question
Can someone please explain to me, like I'm 5, why this circuit does not work?

Every resistance calculator I use says that there is not enough voltage to calculate a resistance. If I understand correctly, wouldn't the LEDs light but just at a lower brightness?

Using R = V/I, The source voltage is 5v, the LED voltage is 6 divided by the current of 20mA equals -50ohms. All of the charge is used up by the time it reaches the arduino right?

# Answer
> 2 votes
The simple reason is that LEDs are not light bulbs. An LED is not a passive device and does not follow Ohms law.

To a first approximation if the voltage across an LED is below the forward voltage then no current will flow. In that situation the voltage across the LED pins is whatever the supply voltage is.
If the voltage across an LED is over the forward voltage then an unlimited current can flow and the voltage between the pins is fixed at the forward voltage.

This approximation isn't perfect but 90% of the time it's good enough.

So with 1 LED and no resistor you get 3V over the LED and then 2V left over with zero resistance, I=V/R = 2/0 = infinite current flow. The LED is dissipating 3\*infinity watts of energy and instantly vaporizes. Clearly this isn't exactly what happens in the real world but the result is enough to tell you that bad things will happen.

With 1 LED and a 200 ohm resistor you get 3V over the LED and then 2V extra with 200 ohms resistance, I=V/R = 2/200 = 10mA. The LED is within its operating current and will light up.

With 2 LEDs and no resistor you get 3V on one LED and 2 V on the second (or 2.5 on both if you prefer). Either one or both LEDs are below their forward voltage and so no current flows. The LEDs remain off.

# Answer
> 2 votes
The two LEDs in series have a forward voltage of 6v which is more than the Arduino's supply voltage.

Forward voltage is the bare minimum amount of voltage required for the LEDs to start conducting electricity (ie: to allow the current to pass through)

Read this: https://www.baldengineer.com/led-basics.html :

> Forward Voltage
>
> The Forward Voltage defines the amount of voltage required in order to conduct electricity. Any voltages below this amount will cause the LED to remain “Open” and non-conductive. This also means any components in-series with the LED will not have current flowing through them either! Once the voltage dropped across the LED reaches the Forward Voltage, it will begin to conduct electricity. Not only that, but the LED will only drop its Forward Voltage at any given time.
>
> For example, consider a LED with a Forward Voltage rated at 3.0V. Now what happens if you attach the Anode to the Positive (+) Terminal of a AA (LR-6) Battery and the Cathode to the Negative (-) Terminal? Will the LED do anything? No! The AA (LR-6) Battery only has a nominal voltage of 1.5V. Until you add a second battery, the LED will not light up.

# Answer
> 1 votes
LEDs won't necessarily light at lower brightness (or conform to Ohm's law at all), it's explained here. If an appliance apparently does provide a "dim" LED mode, it's usually using a clocked signal (and blinking rapidly).

# Answer
> 0 votes
> Can someone please explain to

With the right leds, the circuit can work.

Where it may fail:

1. Two less with combined forward voltage greater than the one applied to them. The meds wouldnt light up or wouldn't light up brightly, depending on the leds used.
2. The two leds with combined forward voltage much less than the supply which has low output resistance. The two leds may light up very brightly, or so briefly ending up in led heaven permanently. If you can capture them in high frame rate code on the glow before their death is quite pretty.

---
Tags: arduino-uno
---


# Question
Title: Do I need to run an expand drive sketch if I update the Yun Firmware subsequent to expanding?
I have a Geeetech Iduino Yun shield, that initially had Geetech's System image (v2.02, 2015) on it. I then ran a USB storage expander sketch to take advantage of the space on a flash drive. I then installed a number of packages (such as `vim`). I subsequently flashed/updated the firmware with Dragino v2 yun-4.1.2 sysupgrade firmware, only to find that `vim` and other packages have disappeared, as well as my Python code.

Has the update undone the expansion and is the Linux system now confined to what's provided by the firmware? Do I need to run an expansion sketch and install packages again?

# Answer
> 0 votes
After upgrading the firmware and rebooting:

1. Log in to your Yun through your browser and use the LuCI interface.
2. Navigate to "System" \> "Software" and observe the "Free space" meter. You will see that the total space shown is between 800KB and 1MB, instead of the size of your flash drive. This indicates that the system is that of the memory available on the board.

Yes, you will need to run the expander sketch again and reinstall software that was previously there. (You might want to back up the contents of the drive beforehand, using a PC running GNU/Linux.)

---
Tags: arduino-yun, linux, firmware
---


# Question
Title: Is the use of malloc() and free() necessary in my Kalman noise Filter function?
I had a code that implements Kalman noise filtering on Arduino, and there is a use of malloc() and free(). I'm wondering if this will affect the Arduino or not (for example, the program will not function as I wanted, ...).

This is because when I got all raw (unfiltered) data and wrote the same Kalman Noise Filter function on Matlab, the filtering works well. However, when I write this FKalman function directly in Arduino, it doesn't work like it did on Matlab.

The Kalman Noise Filter is based on this article: http://www.bzarg.com/p/how-a-kalman-filter-works-in-pictures/

Here is the code (just have a look at the function Fkalman and the tick, ignore the other parts):

```
#define START_MSG

#define NBDATASEND 6
#define NBBYTE2SEND (2*NBDATASEND)

char StartMessage[] = "START";
char StopMessage[] = "STOP";
uint8_t byteRead;
uint8_t StartAsked = 0;
uint8_t StopAsked = 0;
unsigned long previous = 0;
int mod_11k = 12;
int mod_17k = 13;
uint8_t Header = 174;
uint8_t tab_1[NBBYTE2SEND]={0,0,0,0,0,0,0,0,0,0,0,0};
uint16_t data_toSend[NBDATASEND]={0,0,0,0,0,0};

float P1[4];float P2[4];float P3[4]; float P4[4];float P5[4];float P6[4];
float xprec1[2];float xprec2[2];float xprec3[2];float xprec4[2];float xprec5[2];float xprec6[2];
float *sol1;float *sol2;float *sol3; float *sol4;float *sol5;float *sol6;
float Te;
float Tbeg;

void setup() {
  pinMode(mod_11k,OUTPUT);
  pinMode(mod_17k,OUTPUT);
  digitalWrite(mod_11k,LOW);
  digitalWrite(mod_17k,LOW);
  //Start serial port with Gumstix
  Serial1.begin(115200);

//Initialize KF
 P1[0] = 0.05; P1[1] =0; P1[2] =0; P1[3] = 0.05;
 P2[0] = 0.05; P2[1] =0; P2[2] =0; P2[3] = 0.05;
 P3[0] = 0.05; P3[1] =0; P3[2] =0; P3[3] = 0.05;
 P4[0] = 0.05; P4[1] =0; P4[2] =0; P4[3] = 0.05;
 P5[0] = 0.05; P5[1] =0; P5[2] =0; P5[3] = 0.05;
 P6[0] = 0.05; P6[1] =0; P6[2] =0; P6[3] = 0.05;
 xprec1[0] =0; xprec1[1] =0;
 xprec2[0] =0; xprec2[1] =0;
 xprec3[0] =0; xprec3[1] =0;
 xprec4[0] =0; xprec4[1] =0;
 xprec5[0] =0; xprec5[1] =0;
 xprec6[0] =0; xprec6[1] =0;

  //Wait for start message
#ifdef START_MSG
  //Waiting START message to begin
  StartAsked = 0;
  while (StartAsked == 0)
  {
    if (Serial1.available() >= strlen(StartMessage))        //?????
    {
      //Serial.write("Bytes available");
      // verifiy that the received stream is well the start stream
      for (i = 0; i < strlen(StartMessage); i++)
      {
        byteRead = Serial1.read();
        if ((uint8_t)StartMessage[i] == byteRead)
        {
          StartAsked = 1;
        }
       // Serial.println(byteRead);
      }
    }
    delay(1);
  }
  Serial1.write("START");
  //Serial.write("START");
#endif

//KF first time
    Tbeg = millis();
    digitalWrite(mod_11k,HIGH);
    delayMicroseconds(2000);
    data_toSend[0] = analogRead(0);   //phi1 11k
    data_toSend[1] = analogRead(1); //phi2 11k
    data_toSend[2] = analogRead(2);
    digitalWrite(mod_11k,LOW);
    delayMicroseconds(200);
    digitalWrite(mod_17k,HIGH);
    delayMicroseconds(2000);
    data_toSend[3] = analogRead(0);
    data_toSend[4] = analogRead(1);
    data_toSend[5] = analogRead(2);
    digitalWrite(mod_17k,LOW);
    delayMicroseconds(200);
    xprec1[0] = data_toSend[0];
    xprec2[0] = data_toSend[1];
    xprec3[0] = data_toSend[2];
    xprec4[0] = data_toSend[3];
    xprec5[0] = data_toSend[4];
    xprec6[0] = data_toSend[5];
    Te = (millis() - Tbeg)/1000;
    sol1 = Fkalman(xprec1,data_toSend[0],P1,Te);
    sol2 = Fkalman(xprec2,data_toSend[1],P2,Te);
    sol3 = Fkalman(xprec3,data_toSend[2],P3,Te);
    sol4 = Fkalman(xprec4,data_toSend[3],P4,Te);
    sol5 = Fkalman(xprec5,data_toSend[4],P5,Te);
    sol6 = Fkalman(xprec6,data_toSend[5],P6,Te);
    Tbeg= millis();
}

void loop()
{
    tick();
}

void tick() {
    //Previous value for filtering
    P1[0] =sol1[2]; P1[1] =sol1[3]; P1[2] =sol1[4]; P1[3] =sol1[5];
    P2[0] =sol2[2]; P2[1] =sol2[3]; P2[2] =sol2[4]; P2[3] =sol2[5];
    P3[0] =sol3[2]; P3[1] =sol3[3]; P3[2] =sol3[4]; P3[3] =sol3[5];
    P4[0] =sol4[2]; P4[1] =sol4[3]; P4[2] =sol4[4]; P4[3] =sol4[5];
    P5[0] =sol5[2]; P5[1] =sol5[3]; P5[2] =sol5[4]; P5[3] =sol5[5];
    P6[0] =sol6[2]; P6[1] =sol6[3]; P6[2] =sol6[4]; P6[3] =sol6[5];
    xprec1[0] =sol1[0]; xprec1[1] =sol1[1];
    xprec2[0] =sol2[0]; xprec2[1] =sol2[1];
    xprec3[0] =sol3[0]; xprec3[1] =sol3[1];
    xprec4[0] =sol4[0]; xprec4[1] =sol4[1];
    xprec5[0] =sol5[0]; xprec5[1] =sol5[1];
    xprec6[0] =sol6[0]; xprec6[1] =sol6[1];

    free(sol1);
    free(sol2);
    free(sol3);
    free(sol4);
    free(sol5);
    free(sol6);

    //Get data
    digitalWrite(mod_11k,HIGH);
    delayMicroseconds(2000);
    data_toSend[0] = analogRead(0);   //phi1 11k
    data_toSend[1] = analogRead(1); //phi2 11k
    data_toSend[2] = analogRead(2);
    digitalWrite(mod_11k,LOW);
    delayMicroseconds(200);
    digitalWrite(mod_17k,HIGH);
    delayMicroseconds(2000);
    data_toSend[3] = analogRead(0);
    data_toSend[4] = analogRead(1);
    data_toSend[5] = analogRead(2);
    digitalWrite(mod_17k,LOW);
    delayMicroseconds(200);
    Te = (millis() - Tbeg)/1000;

    //Filter
    sol1 = Fkalman(xprec1,data_toSend[0],P1,Te);
    sol2 = Fkalman(xprec2,data_toSend[1],P2,Te);
    sol3 = Fkalman(xprec3,data_toSend[2],P3,Te);
    sol4 = Fkalman(xprec4,data_toSend[3],P4,Te);
    sol5 = Fkalman(xprec5,data_toSend[4],P5,Te);
    sol6 = Fkalman(xprec6,data_toSend[5],P6,Te);
    Tbeg= millis();

    data_toSend[0] = sol1[0];
    data_toSend[1] = sol2[0];
    data_toSend[2] = sol3[0];
    data_toSend[3] = sol4[0];
    data_toSend[4] = sol5[0];
    data_toSend[5] = sol6[0];

    //Send data
    Codage(data_toSend,tab_1);
    HeaderSendnUInt8_RS232(tab_1,NBBYTE2SEND,Header);
}

void Codage(int16_t *d_send, uint8_t *tab_Send)
{
    int i;
    for(i=0; i<NBDATASEND ;i++)
    {
       d_send[i]=d_send[i]+8192;
       tab_Send[2*i]= (uint8_t) ((d_send[i] & 127));              //lấy 7 bit đầu
       tab_Send[2*i+1]= (uint8_t) ((d_send[i] & 16256)>>7);       //lấy 7 bit sau
    }
}

uint8_t HeaderSendnUInt8_RS232(uint8_t *ToSend, uint8_t NbToSend, uint8_t Header)
{
    Serial1.write(&Header,1);         //Header đâu phải pointer??
    return(Serial1.write((const uint8_t*)ToSend, NbToSend));
}

float *Fkalman(float xprec[2],float ymes,float P[4],float Te){
                     // Filtre proprement dit
    float *sol = NULL ;
    sol = (float*) malloc (sizeof(float) * 6);
    float xpred[2];
    float Ppred[4] ;
    float Kf[2] ;
    int q = 0.05;
    int r = 100;

    //x prediction
    xpred[0] = xprec[0] + Te*xprec[1];
    xpred[1] = xprec[1];

    //P_pred = F.P.F'+Q
    Ppred[0] = q + P[0]+ Te*(P[2] +P[1]+Te*P[3]);
    Ppred[1] = P[1] + Te*P[3];
    Ppred[2] = P[2] + Te*P[3] ;
    Ppred[3] = q+ P[3];

    //Kf = (P_pred.C').inv(C.P_pred.C'+R)
    Kf[0]  = (Ppred[0]/(r+Ppred[0]));
    Kf[1]  = (Ppred[2]/(r+Ppred[0]));

    //X_est
    sol[0] = xpred[0] + Kf[0]*(ymes-xpred[0]);
    sol[1] = xprec[1] + Kf[1]*(ymes-xprec[0]);

    //P_est = (I-Kf*C)*P_pred
    sol[2] = Ppred[0]*(1-Kf[0]);
    sol[3] = Ppred[1]*(1-Kf[0]);
    sol[4] = -Kf[1]*Ppred[0]+Ppred[2];
    sol[5] = -Kf[1]*Ppred[1]+Ppred[3];
    return sol;
  }

```

If you find any problem related to the Fkalman function or my loop function, please tell me. Thank you!!

# Answer
It's not recommended, however you're only working with small amounts, and the same amount each time (6 floats per "sol" and 6 "sols", so 36 floats, or 144 bytes). Since it's always the same amount I would expect the same block of memory to be allocated each time.

Personally I would use local array variables in the calling function and pass them as a parameter to the function(s) that manipulate them, rather than returning a pointer to an allocated array.

```
float sol1[6];
Fkalman(xprec1,data_toSend[0],P1,Te,sol1);

....

void Fkalman(float xprec[2],float ymes,float P[4],float Te, float *sol){

```

etc.

However I can't see it causing an issue, so if you would clarify "doesn't work as well" we may be able to point you in a better direction.
> 1 votes

# Answer
As Majenko already explained it is only 144 bytes. You can use local variables as he proposes.

If you need to keep the values over multiple calls to the Fkalman function, create the space as a variable of an array for each of the calls (if the function is called a fixed number of times).

Besides this, malloc cost some time and for performance reasons it is better to do this during start up once, so the loop function is not hindered by mallocs and free.
> 0 votes

---
Tags: arduino-due, memory-usage
---


title: Problems adding ESP8266 wifi board

text:
# Question
Title: Problems adding ESP8266 wifi board
I just received an ESP8266 wifi module and I am trying to add the board. However I am having an issue. All websites/tutorials say to use http://arduino.esp8266.com/stable/package\_esp8266com\_index.json, however nothing is there. Can it be found somewhere else?

# Answer
> 1 votes
It looks like the server is down. Isitdownrightnow reports that it's been down for almost 4 days: http://www.isitdownrightnow.com/arduino.esp8266.com.html

There is a discussion about it over on the ESP8266 forums: http://www.esp8266.com/viewtopic.php?f=26&t=3134&start=8

Let's hope it will be back again soon.

---
Tags: esp8266
---


# Question
Title: SPI Problem with K-Thermocouple and Potentiometer?
I have a setup where the Arduino reads input from the k-thermocouple and uses that info to regultate the an output voltage through a potentiometer. I know the potentiometer is not faulty because able to read the output from the wiper when I run the program but for some reason, k-thermocouple is stuck at 0 Celsius. I know that the k-thermocouple is not faulty either because it works accordingly when I run a program specifically by itself.

Does anybody know why there is a problem with how the k-thermocouple is operating in junction with the potentiometer? Here is a declarations of my program.

```
#include <SPI.h>

// K-couple dependent DigiPot Regulator

#include "SPI.h"
#include "max6675.h"

byte address = 0x10;
int CLK = 13;
int CS = 10;
int SDI = 11;
const int ktcSO = 12;
int ktcCS = 9;
int ktcCLK = 13;

MAX6675 ktc(ktcCLK, ktcCS, ktcSO);

int digitalPotWrite(int value) //Everything that happens when the DigiPot is
called
{
  digitalWrite(CS, LOW); // Chip Select is ACTIVE LOW (so now it's selected)
  SPI.transfer(address);
  SPI.transfer(value);
  digitalWrite(CS, HIGH);
}

void setup()
{
  SPI.begin();
  pinMode (CLK, OUTPUT);
  pinMode (CS, OUTPUT);
  pinMode (SDI, OUTPUT);
  Serial.begin(9600);
  // give the MAX a little time to settle
  delay(500);
}

void loop()
{
  if (ktc.readFahrenheit() < 60)  // While it's still in Safe Zone
  {
    digitalPotWrite(255);
    // Show the current temp in C and F
    Serial.print("Deg C = ");
    Serial.print(ktc.readCelsius());
    Serial.print("\t Deg F = ");
    Serial.print(ktc.readFahrenheit());
    int sensorValue = analogRead(A0);
    float voltage = sensorValue * (5.0 / 1023.0);
    Serial.print("\t V = ");
    Serial.println(voltage);
    int clockValue = analogRead(A1);
    Serial.print("\t Clock = ");
    Serial.println(clockValue);
  }
        if (ktc.readFahrenheit() < 65) // While in Caution Zone
        digitalPotWrite(51);
        else if (ktc.readFahrenheit() < 70)
        digitalPotWrite(102);
        else if (ktc.readFahrenheit() < 75)
        digitalPotWrite(153);
        else if (ktc.readFahrenheit() < 78)
        digitalPotWrite(184);
        else if (ktc.readFahrenheit() < 80) //Getting into Danger Zone
        digitalPotWrite(204);
        else if (ktc.readFahrenheit() < 81)
        digitalPotWrite(214);
        else if (ktc.readFahrenheit() < 82)
        digitalPotWrite(224);
        else if (ktc.readFahrenheit() < 83)
        digitalPotWrite(235);
        else if (ktc.readFahrenheit() < 84)
        digitalPotWrite(245);
        else (ktc.readFahrenheit() < 85); //Complete Shutoff
        digitalPotWrite(255);
    {
     Serial.print("Deg C = ");
     Serial.print(ktc.readCelsius());
     Serial.print("\t Deg F = ");
     Serial.print(ktc.readFahrenheit());
     int sensorValue = analogRead(A0);
     float voltage = sensorValue * (5.0 / 1023.0);
     Serial.print("\t V = ");
     Serial.println(voltage);
     int clockValue = analogRead(A1);
     Serial.print("\t Clock = ");
     Serial.println(clockValue);
    }
}

```

Also, the code I used to test the K-Thermocouple is one that can be found on the internet (with just a little bit of adjustments)...

```
// Sample Arduino MAX6675 Arduino Sketch

#include "max6675.h"

int ktcSO = 12;
int ktcCS = 9;
int ktcCLK = 13;

MAX6675 ktc(ktcCLK, ktcCS, ktcSO);

void setup() {
  Serial.begin(9600);
  // give the MAX a little time to settle
  delay(500);
}

void loop() {
  // basic readout test

   Serial.print("Deg C = ");
   Serial.print(ktc.readCelsius());
   Serial.print("\t Deg F = ");
   Serial.println(ktc.readFahrenheit());
   int clockValue = analogRead(A1);
    Serial.print("\t Clock = ");
    Serial.println(clockValue);

   delay(500);
}

```

# Answer
The wiring diagram, if accurate, shows a couple of problems.

First, A0 has nothing attached to it, so `sensorValue` may read in as zero or some small random number.

Second, attaching the digital pot's analog output pin 6, P1W, to the Uno's digital input pin 12 is pointless. Instead connect P1W to whatever it is supposed to control. If you want to handle data *from* the MCP42X1, connect its pin 13, SDO, to an Uno input.

However, neither of those problems appears to be related to misreading the MAX6675 temperature. I don't know of a good approach to solving that problem, but if I were working with the circuit, would remove the wire between P1W and the Uno's digital pin 12, and would use 12 as the input from the MAX6675; that is, would wire it to d12 instead of d8, and instead of `int ktcSO = 8` would say `const int ktcSO = 12`. Also, I'd probably replace the bit of code

```
  }
  else
  {
    while (ktc.readFahrenheit() < 85)
      {

```

with just a closing `}`. In the Arduino paradigm, `loop()` runs repeatedly, and the if–else sequence adequately guards each of the `digitalPotWrite()` calls.

Note, the `digitalPotWrite()` function should be defined or declared before any calls to it appear. Instead of placing that function at the end, put it before `loop()` or before `setup()`.
> 1 votes

---
Tags: arduino-uno, spi, potentiometer
---


# Question
Title: Multiple SPI reads slows down read time dramatically
I have a two channel 24bit ADC(LTC2402- http://cds.linear.com/docs/en/datasheet/24012f.pdf) that I am communicating with via Arduino Leonardo(Leonardo because it was free!). If I attempt to do multiple reads the SPI becomes very slow while if I do a single read the time to send is what is expected. I have have integrated with python and timed the different transactions. A single read takes around 170ms( this is for both channels and the datasheet of the ADC indicates about 65ms per conversion(table 3 arduino as external sck etc.)) BUT if I do 5 reads the time taken is about 1.5s(expected about 0.65s) 10 reads take about 3s and 20 about 6.5s. Doing no ADC conversions and just serial comm to python is less than 2ms.

The relevant python code is as follows:

```
def getdata(ser,code):#ser is the arduino that has been connected, code is for writting to arduino
    ser.write(code)
    ch0=float(ser.readline().decode()[:-2])
    ch1=float(ser.readline().decode()[:-2])
    return ch0,ch1

code='1'
code=code.encode()

a=datetime.datetime.now()
ch0,ch1=getdata(ser,code)
b=datetime.datetime.now()
print(b-a)

```

The arduino code is as follows. The code has been simplified to just the necessary byte reads from the ADC, all other code has been removed to ensure the delays are coming from the SPI.transfer(0x00). The full code retrieves 4 bytes per channel and converts this to voltage and returns these values.

```
#include <SPI.h>

const int ltcs = 3; //active low ADC enable

float ch0=0.0;
float ch1=0.0;
byte b0;

void setup() {
SPI.begin();
SPI.beginTransaction(SPISettings(200000, MSBFIRST, SPI_MODE0));

Serial.begin(9600); // set the baud rate

pinMode(ltcs, OUTPUT);
digitalWrite(ltcs, LOW);
}

void loop() {
if(Serial.available()){

   int data = Serial.read() - '0';
   if(data>0){

   getdata2(ch0,ch1);
    //getdata2(ch0,ch1); //run multiple getdata2 to test multiple conversions
   //getdata2(ch0,ch1);
    //getdata2(ch0,ch1);
   //getdata2(ch0,ch1);

    Serial.println(0.2);
    Serial.println(0.4);

  }
  }
  }

 void getdata2(float &ch0, float &ch1) {
   ch0 = 0.0;
   ch1 = 0.0;

   for (int i = 0; i < 2; i++) { //Do twice to retrieve both Channels
     while (digitalRead(MISO) == HIGH) {
     }

       b0 = SPI.transfer(0x00);
       b0 = SPI.transfer(0x00);
       b0 = SPI.transfer(0x00);
       b0 = SPI.transfer(0x00);
   }
   }

```

Can anyone help me? I have tried different SPISettings with no change. Interestingly I also find that the Baud rate does not change either.

Thanks for the help if any

# Answer
I found the error. Unfortunately I was so busy blaming the code and assuming it was my lack of arduino knowledge that I forgot to check the hardware specs. I thought I was using the maximum external oscillator frequency(f\_EOSC) of 300KHz, but in fact was using the 50Hz internal oscillator frequency with an external f\_sck from the arduino. This means that the conversions where in fact running at expected times. The thing that threw me off was that the first reading was much faster than the rest. This was most likely because at first read I only had to wait for one channel conversion as the other was already done before I request the data and so the first readings wait time is only as long as a single channels conversion. I would need to implement a 300KHz external clk if I want faster conversion speeds. Thanks for the help for those who tried:)
> 2 votes

# Answer
You probably want to take a look at the datasheet and work on one routine that returns adc results from a channel selected by the user. The typical process is to read the register until EOC is asserted (\_EOC is low).

and you would go from there.
> 0 votes

---
Tags: spi
---


title: Two devices on one UART/Serial

text:
# Question
Title: Two devices on one UART/Serial
I'm using an Arduino Mega which has 4 RX/TX UARTS/serials. 3 RX's of them I use for MIDI In 2 TX's of them I use for MIDI Out (maybe later a DMX out too)

One I use currently for debugging. On the other hand, in the future I want:

* Using an ESP8266 WIFI which also seems to use an UART (both RX/TX)

Of course I can remove the debugging RX/TX, but maybe some more additions are needed and for the first RX/TX I need to remove the RX each time I upload (so I rather leave it for debugging).

I was wondering, is it possible to share an UART if I don't use the WIFI module and MIDI port at the same time?

# Answer
> 2 votes
It's certainly possible to multiplex a UART port, yes, though you will need extra hardware to do it. You will need:

* A multiplexer to select between the two RX lines and feed the right one to the Arduino's RX pin
* A demultiplexer to select which of the devices to send the Arduino's TX pin to.

"Analog" (de)multiplexers (e.g., CD4052) may be the simplest option since they can work in both directions. Another alternative would be combinations of tri-state buffers and glue logic to control them.

# Answer
> 1 votes
If your application can tolerate the limitations of SoftwareSerial, it's the easiest way to add a port. The terminal may be the better candidate for it.

# Answer
> 1 votes
Consider running the RX and TX of the first UART to the common terminals of an On-Off-On DPDT switch or relay. Calling the On positions A and B, connect the A terminals to RX and TX of one device, and the B terminals to RX and TX of another device. Use position A for the first device, position B for the second device, and the Off position for program loading.

It isn't clear to me whether your debugging is via USB serial or via a separate device. In the former case, a DPST switch would be adequate. Also, two SPDT's could be used in place of a DPDT if you wish to switch RX and TX separately, or four SPST switches can be used if you have nothing better.

This is premised on the idea that during development you need to be able to send/receive debugging IO. I don't know how to interpret your “don't want to be rely on a user having to remove the cable” phrase, but suppose a user-cabled setup won't need debug-channel switching.

---
Tags: serial, arduino-mega, wifi, uart
---


# Question
Title: Make Sure \n is the last character in serial string
I have an Arduino that I've put between a computer and an RS485 device. The job of the Arduino now is just to transmit data but will eventually do data logging and have a small user interface as time goes by.

So far, this serial read code has worked for me to communicate to the Arduino from the computer:

```
 void serialEvent()
 {
  while(Serial.available())
  {
    // get new byte
    char inChar = (char)Serial.read();
    if (inChar == '\n')
    {
      stringComplete = true;
    }
    else
    {
      inputstring += inChar;
    }
  }
 }

```

The downside here is that I cannot send the '\n' char to my RS485 unit. Is there a way I can refine the code so I can send an arbitrary string of chars while still having a termination \[thing\] to turn on the stringComplete flag?

EDIT To clarify this the process by how my message string is being created:

```
Input: U16 Address, U16 Data, U8 Function Code
U16 Address -> U8 Address Split High, U8 Address Split Low
U16 Data -> U8 Data Split High, U8 Data Split Low

U8 Array of [U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]

U8 Array -> Message String

Output: Write Message String

```

# Answer
> 4 votes
Since you are using all 8 bits of the serial data for your data there is nothing "in band" that you can use for a delimiter.

Instead you will have to think outside the box somewhat and create some form of "out of band" data that can signal the end of a packte.

One option (probably the simplest) would be to include the concept of time into your protocol. If you go more than X milliseconds (X is to be determined by you) without receiving a byte then you are at the end of your packet. This has the disadvantage that it slows down your maximum packet rate, since each packet has to have a suitable delay between them.

Another option may be to use a serial *break* character between packets. This is a special event where the UART output is held low for at least 10 symbol lengths, which results in an framing error (the STOP bit is wrong) and a flag being set. It would mean though that you have to implement all the UART code yourself since the Arduino's UART code doesn't support breaks.

A third option, which also would require you to write your own UART code, or alter the Arduino UART code, would be to operate the UART in 9-bit mode. You then have 0-511 instead of 0-255, so you can send your 8-bit data as per normal (with the 9th bit set to 0) and any control and protocol characters with the 9th bit set, so between 256 and 511.

Finally, you could halve your overall transmission speed by sending the data as ASCII-encoded HEX digits. That would be two characters (0-9,A-F) for each byte sent, leaving all the other characters (including `\n`) available for you to use as you wish.

# Answer
> 2 votes
Normally strings end with a '/0' item ... than /n is part of the string and can be handled as normally.

So you have to change the check to

```
if (inchar == '\0')

```

Also consider not adding a character every time to the string, since it will cause the string to be replaced/copied every time, which is not good for both performance and memory gaps resulting.

Instead make a predefined buffer if possible (if you know the maximum string length, don't forget to add +1 for the ending '0' character). In that case you can add the '\0' yourself or even better:

```
char inputString[101];
uint8_t inputStringLength = 0;

while(Serial.available())
{
    // get new byte
    char inChar = (char) Serial.read();
    inputString[inputStringLength++] = inChar;

    stringComplete = (inChar == '\0')
}

```

# Answer
> 1 votes
`Serial.avilable()` returns the number of bytes available in the buffer. One solution could be to try reading that many bytes at a time. This assumes that the buffer contains only entire strings.

Note: If your RS485 device sends multiple, non-delimited strings between buffer reads then this may not work as desired.

```
void serialEvent()
{
  int bytes = Serial.available();

  if ( bytes == 0 ) // empty buffer, bail
    return;

  for (; bytes > 0; bytes-- )
  {
    // get new byte
    char inChar = (char)Serial.read();
    inputstring += inChar;
  }
  stringComplete = true;
}

```

---
Tags: arduino-uno, serial, softwareserial
---


# Question
Title: How to logically tell than an UNO is being, or about to be programmed
I have an MIDI application that uses the RX and TX serial interface. When I program the UNO there is a collision between the on board programmer and the MIDI application RX serial port. The MIDI shield provides a jumper to disconnect to prevent the collision during programming.

I would like to add a FET switch to open and close if I am programming, but it's not clear to me that there is a signal I can tap into on the UNO that indicates programming is about to start or that it has just finished.

I was thinking about using a pull up on a digital pin on the UNO that drives low when the program starts up. That might be the way to go, but I assumed that this must be a common issue with a common solution that I am just not finding on stack exchange.
Is there a standard logical way to tell that UNO is about to be programmed via the onboard USB port?

# Answer
Your proposed solution is the normal method. A GPIO pin which is an "Activate Device" signal. It's pulled in one direction, the "inactive" direction, and you actively drive it in the other "active" direction in your program.
> 2 votes

---
Tags: serial, programming, midi
---


# Question
Title: OSX upload error: avrdude: ser_open(): can't open device "/dev/cu.mydev" : Resource Busy
I'm trying to upload the blink script to my unnamed Arduino-like board. However, the USB port appears to be busy.

This is all the output I get:

```
Archiving built core (caching) in: /var/folders/43/7_h5zwcs1csdr2dc635m1yq40000gp/T/arduino_cache_942504/core/core_arduino_avr_uno_51f02b7210b938436b779d1c032618e1.a
De schets gebruikt 928 bytes (2%)  programma-opslagruimte. Maximum is 32256 bytes.
Globale variabelen gebruiken 9 bytes (0%) van het dynamisch geheugen. Resteren 2039 bytes voor lokale variabelen. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "/dev/cu.mydev": Resource busy

```

I've tried all solutions I could find on internet, but they haven't solved my issue. The main difference with my error and online solutions/errors is that I only have this error. Other people experienced extra errors which enabled the debugging of the problem.

Can anyone help me please?

# Answer
I think my available serial ports were insufficient or something. I installed the ch34\* driver which allowed an additional device showing up. Here's the download: http://www.wch.cn/download/CH341SER\_MAC\_ZIP.html

Then I selected this port and I finally could upload.
> 1 votes

---
Tags: usb, uploading, clones
---


title: Simple Ground circuit layout

text:
# Question
Title: Simple Ground circuit layout
I am making a circuit without using a PCB or perfboard and i am unsure if i am running the ground wire correctly.

I usually prototype on a breadboard with the ground all joining on the far right, is this the same concept? I wanted to know if this is the accepted convention for running the ground back to the board.

# Answer
> 0 votes
Yes, based on basic electrical theory, you have the ground connected correctly.

---
Tags: arduino-nano, electricity
---


title: Arduino Temperature sensor with a LED

text:
# Question
Title: Arduino Temperature sensor with a LED
I want to program a temperature sensor with a LED using Arduino. the goal is to make a sensor, when the temperature is over than Temperature max, the LED turns off and when the temperature is small than temperature max we turn on the LED.

my problem is when I programed the void setup() as followed, the LED doesn't work, and when I comment Serial.begin (9600) the LED work but I cannot diplay the value of the temperature.

```
void setup() {
   Serial.begin(9600);
   pinMode(tempPin, INPUT);
   pinMode(led, OUTPUT);
}

```

here you find my complet code:

```
    int tempPin = A0;   // the output pin of LM35
float Max_temp = 24.0;
int led = 1;

float  temp, cel;
void setup() {
   Serial.begin(9600);
   pinMode(tempPin, INPUT);
   pinMode(led, OUTPUT);
}
void loop() {
      cel = readTemp();
  if(cel< Max_temp) {        // if temp is higher than tempMax
      digitalWrite(led, HIGH);  // turn on led
      delay(300);
     }
     else {                    // else turn of led
       digitalWrite(led, LOW);  // turn on led
      delay(100);
  }
   Serial.print("TEMP: ");
   Serial.print(cel);      // display the temperature
   Serial.print("C ");
   Serial.println();
   delay(300);
}

float readTemp() {  // get the temperature and convert it to celsius
  temp = analogRead(tempPin);
  return temp * 0.48828125;
}

```

thank you very much in advance

# Answer
```
int led = 1;

```

You do know that pins 0 and 1 are the serial port don't you?

Take your pick.... Either use pin 1 for the LED *OR* use pin 1 for the serial connection. You can't do both!

As it says *in the manual*:

> In addition, some pins have specialized functions:
>
> * Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data. These pins are connected to the corresponding pins of the ATmega8U2 USB-to-TTL Serial chip.
> 4 votes

# Answer
Your logic is backwards. Your program says if the temp is LESS THAN max then turn on the LED.

But worse than that, you should not use pin 1. Pick any other pin.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Connecting a 5v dc fan to ultrasonic sensor
I am currently doing a simple uni project where i want the distance read by an ultrasonic sensor to control the speed of a dc 5v fan. I have attached a schematic of how i think i can link the ultrasonic sensor and fan components in order to achieve my main goal. Please tell me if this circuit is right or wrong and give some helpful feedback, thank you!

# Answer
It's wrong.

A fan is a motor. A motor is a power hungry inductive device.

Just like any other motor or similar device (such as a relay or solenoid) you cannot drive it directly from the Arduino. Instead you need (at the very least) a transistor to switch a higher current and a diode to absorb back EMF.
> 1 votes

---
Tags: arduino-uno, sensors, motor
---


title: Arduino Nano and ESP8266

text:
# Question
Title: Arduino Nano and ESP8266
I am trying to use Arduino Nano with ESP8266 (01). I tried to follow a lot of online tutorial with no result.

In particular this one http://www.martyncurrey.com/arduino-to-esp8266-serial-commincation/. I think connections between Arduino Nano and ESP8266 are fine, when I upload the code on Arduino the red led on the ESP8266 turns on, I set the Arduino Monitor to 9600 BAUD and try to send command like "AT" but I got not reply from ESP8266. I also tried to switch to 115200 BAUD with no result too.

I don't if is something wrong or ESP8266 is damaged. Is there any tutorial that you may suggest?

Thank you.

# Answer
The Serial Monitor's baud rate must match what you have in

```
Serial.begin(9600);

```

The EDP8266's baud rate is specified in the line

```
ESPserial.begin(9600);

```

and that is the one you need to change to try different baud rates with the ESP8266. The newer AIThinker firmwares default to 115200 baud, not 9600 baud.

Be warned, though, that SoftwareSerial isn't that great at 115200 baud - you tend to get some data corruption. It is best to change the baud rate to 9600 baud with

```
AT+CIOBAUD=9600

```

I'd also recommend investing in one of the ESP-01 programming boards from eBay. Make sure you get one of the ones with a switch on it that switches between programming and UART mode. Something like this one. It makes working with the ESP-01 much simpler - you can directly use your PC to set it up right for your system, and even upgrade the firmware (or program it directly with a sketch from the Arduino IDE if you install the right core) with minimum hassle.
> 2 votes

---
Tags: esp8266, arduino-nano
---


# Question
Title: Make lights come on and off depending on which button is pressed
Imagine a strip of LEDs with O being HIGH and X being LOW.

X O X O X

Now if I pressed the button below the second O and wanted it to switch the last two LEDs (4th one to LOW and 5th to HIGH or any opposite value of what it was), but if I pressed the first X wanted it to switch that one HIGH, the second one LOW, and the third HIGH.

I want to continue this type of pattern where each button press will result in two or three of the LEDs changing their effective state.

How might I achieve this? I have researched using the modulo function and can only get it to work every other click of a button. I have also tried using a pullup function and couldn't get it to work at all.

Can someone please just point me in the right direction?

# Answer
> 0 votes
> I want to continue this type of pattern where each button press will result in two or three of the LEDs changing their effective state.

I'll assume there are *nLED* LEDs and buttons, and that the buttons are momentary buttons and need debouncing. I presume you have one button beneath each LED, numbered say 0 to *nLED-1*, and that the two or three LEDs that will change when button *k* is pressed have numbers *k, k+1,* and possibly *k+2*.

To simplify the coding, create an array (or a bit map), say *Lsts*, with *nLED* entries, to represent the current state of LEDs, and a similar array, say *Bsts* for button statuses, and an array of bytes *bounce* to track debouncing status.

On each pass through `loop()`, use a `for` loop to read each eligible switch. A switch with a nonzero *bounce* entry is debouncing and doesn't get read. If a switch is read and it changes, update the LED statuses in *Lsts* and at ports. For example:

```
enum { nLED=5, debouncePasses=50 };
byte Lsts[nLED]={0}, Bsts[nLED]={1,1,1,1,1}, bounce[nLED]={0};
const byte Lpins[nLED] = { 3,4,5,6,7 };
const byte Bpins[nLED] = { 8,9,10,11,12 };
//... etc

void setup() {
  for (byte i=0; i<nLED; ++i) {
    pinMode(Lpins[i], OUTPUT);
    // Buttons will have negative logic, hi for open, lo for pressed
    pinMode(Bpins[i], INPUT_PULLUP);
  }
  // ... any other initialization ...
}
void loop() {
  for (byte i=0; i<nLED; ++i) {
    // See if button is eligible for reading, and if it changed
    if (bounce[i]) {
      --bounce[i]; // Decrease bounce pass counter
    } else {
      if (digitalRead(Bpins[i]) != Bsts[i]){
        // Yes,  it's eligible and it changed
        bounce[i] = debouncePasses; // Set button's debounce counter
        if (Bsts[i]) { // Test if switch was pressed vs released
          // Toggle the button's light and the next one or two lights
          for (int j=i; j<nLED && j<i+3; ++j) {
            Lsts[j] = !Lsts[j];
            digitalWrite(Lpins[j], Lsts[j]);
          }
        }
        Bsts[i] = !Bsts[i]; // Toggle button state
      }
    }
  }
  // ... any other stuff
  delayMicroseconds(500); // Delay for bounce-pass timing
  // alternately, instead of delayMicroseconds, sleep until timer tick
}

```

---

*Edit 1:* If there are more LEDs than buttons, then use separate constants for the counts, adjust the initializations, etc. For example:

```
enum { nButton=5, nLED=6, debouncePasses=50 };
byte Lsts[nLED] ={1,0,1,0,1,0};
byte Bsts[nButton]={1,1,1,1,1}, bounce[nLED]={0};

//... etc

void setup() {
  for (byte i=0; i<nLED; ++i) {
    pinMode(Lpins[i], OUTPUT);
    digitalWrite(Lpins[i], Lsts[i]);
  }
  // Buttons will have negative logic, hi for open, lo for pressed
  for (byte i=0; i<nButton; ++i) {
    pinMode(Bpins[i], INPUT_PULLUP);
  }
  // ... any other initialization ...
}

```

In `loop()`, change the initial `for` from `for (byte i=0; i<nLED; ++i)` to `for (byte i=0; i<nButton; ++i)`. This will work ok if there is an extra LEDs after the LEDs that line up with buttons.

---

*Edit 2:*

> Why when using an array doesn't the arduino recognize the HIGH or LOW state of an led? I tried adding this simple code:
> `if (42 && 44 && 46 && 48 && 50 == HIGH){`
> `digitalWrite (ledWin, LOW); } else {digitalWrite (ledWin, HIGH);}`

Evidently you want to test if all the LEDs are on, and apparently the numbers 42, 44, ... 50 are supposed to somehow represent LED states.

However, numbers like 42, 44, ... are constant values and cannot properly represent the value of something that varies. The condition in that `if` statement will always evaluate to the same value, false, as follows.

According to the C/C++ standard, a condition like `42 && 44 && 46 && 48 && 50 == HIGH` consisting of a series of terms separated by `&&` operators will be evaluated left to right until either one is false (making the whole expression false) or all are true (making it true). (For example, see the *Remarks* section of Logical AND Operator: &&.)

In this case, 42 is non-zero, hence true. Next, 44 is true, 46 is true, and 48 is true. But `50 == HIGH` is false – the value of `HIGH` is 1, and 50 is not equal to 1. Therefore the whole expression is false.

A better approach to finding out if all the LEDs are on or off is to test the values of `Lsts[]` entries. For example, you could add them up, and then see if the sum is equal to 0 (all off) or equal to `nLED` (all on):

```
byte nOn = 0;
for (byte i=0; i<nLED; ++i) nOn += Lsts[i];
digitalWrite (ledWin, nOn < nLED);

```

That will set the `ledWin` pin if not all of the LEDs are on, else will clear it.

# Answer
> 0 votes
> Can someone please just point me in the right direction?

what is "right" is highly subjective. I would consider a good solution to be one where the functionalities desired is broken down into natural modules that are then integrated to perform the desired functions. By that (highly subjective) standard, the solution posted earlier would be a poor one -\> due to its tightly coupled / inter-mingled approach.

if I were to take a shot at this, I would consider the implementation below:

```
  key_state = read_keys(); //read keys / buttons, with or without debouncing
  led_process(key_state);  //process the key_state, and light up / off leds based on key_state

```

Essentially, you scan the keys / buttons, and based on that, turn on / off the leds.

All you need to do after that is to implement the individual functions based on your particular hardware design, or even software approaches: for example, read\_keys() can be implemented in the isr, as can led\_process().

A solution like this is highly portable: it works on pretty much anything that supports a C compiler, and is implementation-independent: the logic holds true, and all you do is to change the two functions to perform different kinds of lighting.

To me, modulizing your code is a huge advantage for a high-level language like C, and vital in taking on a real life project of moderate complexity.

---
Tags: arduino-uno, programming, led
---


# Question
Title: Arduino MPU6050 not working due to LED PWM
I'm having some problem with the MPU6050 example sketch. I added a few bits of code of my own, so that my LEDs change color based on the yaw-pitch-roll. However when I try to run it, the values of the yaw-pitch-roll get all distorted, like this:

```
ypr -38.68  -30.05  41.34
ypr -55.42  -35.25  -31.68
ypr -101.02 23.53   -65.01
ypr 101.29  -19.63  12.81
ypr -51.97  -37.49  44.85
ypr 37.89   38.20   -37.95
ypr 72.15   -13.70  22.68
ypr 0.00    0.00    90.00
ypr -45.73  74.52   -11.89
ypr 134.36  31.89   -31.08
ypr -13.86  -21.51  3.54

```

And when I disable `analogWrite` on the LED lights the yaw-pitch-roll gives normal output again.

Below is the code for changing the LED colors.

```
void setColor (float red, float blue){
  int redColor = (int)255 - red;
  int blueColor = (int)255 - blue;
  analogWrite(redPin, redColor);
  analogWrite(bluePin, blueColor);
}

```

Does anyone know what is going wrong here?

EDIT:

The wiring:

The code:

```
// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

// uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
// quaternion components in a [w, x, y, z] format (not best for parsing
// on a remote host such as Processing or something though)
//#define OUTPUT_READABLE_QUATERNION

// uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
// (in degrees) calculated from the quaternions coming from the FIFO.
// Note that Euler angles suffer from gimbal lock (for more info, see
// http://en.wikipedia.org/wiki/Gimbal_lock)
//#define OUTPUT_READABLE_EULER

// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
#define OUTPUT_READABLE_YAWPITCHROLL

// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
//#define OUTPUT_READABLE_REALACCEL

// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
// components with gravity removed and adjusted for the world frame of
// reference (yaw is relative to initial orientation, since no magnetometer
// is present in this case). Could be quite handy in some cases.
//#define OUTPUT_READABLE_WORLDACCEL

// uncomment "OUTPUT_TEAPOT" if you want output that matches the
// format used for the InvenSense teapot demo
//#define OUTPUT_TEAPOT

#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

int redPin = 11;
int bluePin = 9;

int startR = 100;
int startB = 10;

int eindR = 255;
int eindB = 255;

int gyroMin = 0;
int gyroMax = 80;
int gyroRange = 0;
float rangeR = 0;
float rangeB = 0;

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    gyroRange = (gyroMax - 10) - (gyroMin + 10);
    rangeR = (float)(eindR - startR)/gyroRange;
    rangeB = (float)(eindB - startB)/gyroRange;

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

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // wait for ready
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    /*while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again*/

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);
    pinMode(redPin, OUTPUT);
    pinMode(bluePin, OUTPUT);
    //digitalWrite(redPin, LOW);
    //digitalWrite(bluePin, LOW);
    setColor(100.0,100.0);
}

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

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        // other program behavior stuff here
    }

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

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

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));
        } else if (mpuIntStatus & 0x02) {
          // otherwise, check for DMP data ready interrupt (this should happen frequently)
         // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            Serial.print("quat\t");
            Serial.print(q.w);
            Serial.print("\t");
            Serial.print(q.x);
            Serial.print("\t");
            Serial.print(q.y);
            Serial.print("\t");
            Serial.println(q.z);
        #endif

        #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
            int degree = ypr[1] * 180/M_PI;
            if (degree <= (gyroMin + 10)){
              setColor(startR, startB);
            }
            if ((degree > (gyroMin + 10)) && (degree < (gyroMax - 10))){
              float calcR = (startR + ((degree-10) * rangeR));
              float calcB = (startB + ((degree-10) * rangeB));
              setColor(calcR,calcB);
            }
            if (degree >= (gyroMax - 10)){
              setColor(eindR, eindB);
            }
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_READABLE_WORLDACCEL
            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif

        #ifdef OUTPUT_TEAPOT
            // display quaternion values in InvenSense Teapot demo format:
            teapotPacket[2] = fifoBuffer[0];
            teapotPacket[3] = fifoBuffer[1];
            teapotPacket[4] = fifoBuffer[4];
            teapotPacket[5] = fifoBuffer[5];
            teapotPacket[6] = fifoBuffer[8];
            teapotPacket[7] = fifoBuffer[9];
            teapotPacket[8] = fifoBuffer[12];
            teapotPacket[9] = fifoBuffer[13];
            Serial.write(teapotPacket, 14);
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
        #endif

        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
    }
}
void setColor (float red, float blue){
  int redColor = (int)255 - red;
  int blueColor = (int)255 - blue;
  analogWrite(redPin, redColor);
  analogWrite(bluePin, blueColor);
}

```

EDIT 2: After a lot of testing with and without resistors and new cables (I thought there might be some sort of cable damage), it still isn't working fully. The weird thing is that when every component is hooked up via a breadboard it works (without resistors). But as soon as I try to solder everything it works randomly.

Is there a chance that the type of cable (copper vs aluminium) has any effect on this? The breadboard cables are aluminium and the soldered cables are copper.

# Answer
You have no resistors on your LEDs. The PWM signals are causing huge amounts of noise in the MCU corrupting all your data and communications.

Add resistors (say 330Ω) to each LED cathode pin (so 9 resistors).
> 1 votes

---
Tags: arduino-uno, pwm, rgb-led, mpu6050
---


# Question
Title: Attiny85 not recognized at windows startup
I'm using an Attiny85 to interact with a computer using an USB connection, and everything works fine except when I restart my computer and the Attiny85 is connected. When Windows end to boot up the Attiny85 isnt't recognized, and on Device Manager it's listed like this:

If I unplug the Attiny85 and then plug it back in, everything works just fine.

Is there any to make it detectable at boot time without having to always unplug/plug it?

**EDIT:**

More details:

I'm using this board

and **libusb-win32** as the USB driver

# Answer
> 1 votes
I don't have enough reputations to make a comment so I will drop my 2 cents here.

There should be more elegant way to do this but as a fast solution I would recommend two things:

1. If it is possible, add a push button to your board to reset the MCU manually when the PC is booted up.
2. You can make a software reset after powering up the board by a certain time (e.g. 10 sec) by using watchdog timer.

---
Tags: usb, avr, attiny
---


# Question
Title: Trying to send .wav files between NodeMCU
Im trying yo send wav files between two nodeMCU. My setup is like this uSD Card Module -\> Arduino Mega -\> Node MCU

So this is my setup, where I have 4 devices like this. One will serve as the central network(where I called it "server") where it will create an access point for the 3 other devices("modules") to connect to. The server will send data by using UDP so it can broadcast to the three modules simultaneously. I'm able to send .txt files which is stored on the uSD module. Pass the .txt file contents to the nodeMCU through serial port, then recieve it on the other NodeMCU which will then send the data to the Arduino Mega also through serial port and will store it on its uSD Shield.

When I would try .wav files. It is able to send the whole .wav file to the NodeMCU from Arduino Mega (since .wav files are too big, I divide the .wav files into sets since the serial port can't handle too large data being sent/recieved. But when it would send the data from the nodeMCU to the other nodeMCU there are parts which are not being sent. When I try to observe what are not being sent, its part of the WAV Header Format, so it needs to be sent. Ill be posting the codes Im using to send and recieve and also a screenshot/example of the wav file as it is being sent.

Server's Arduino Mega Sending data to NodeMCU Serially:

```
void sendFiletoSerial(char fileSend[12]){
  Serial.println();
  Serial1.println();
  if (!myFile.open(fileSend, O_READ)) {
    sdf.errorHalt("opening test.txt for read failed");
  }
  Serial.print(fileSend);
  Serial.print(" Size:");
  Serial.println(myFile.fileSize());

  Serial1.print(fileSend);
  Serial1.print(" Size:");
  Serial1.println(myFile.fileSize());
  delay(1500);
  fileofSize = myFile.fileSize();
  myFile.close();
  // read from the file until there's nothing else in it:
  char data;
  long int index=0;
    for(int i =0; i<(fileofSize/tempSize);i++){
    if (!myFile.open(fileSend, O_READ)) {
    sdf.errorHalt("opening test.txt for read failed");
  }
    //Serial.println(i);
    myFile.seekSet(index);
  for(int j =0; j<tempSize;j++){
  int temp = myFile.read();
 intTempFile[j]=temp;
  index++;

  }
  for(int k =0;k<tempSize;k++){
  Serial1.write(intTempFile[k]);
  }
    myFile.close();
    delay(1500);
  }
  Serial.println("LAST SET OF DATA");
    if (!myFile.open(fileSend, O_READ)) {
    sdf.errorHalt("opening test.txt for read failed");
  }
    myFile.seekSet(index);
    int lastSetSize=fileofSize-((fileofSize/tempSize)*tempSize);
    Serial.println(fileofSize-((fileofSize/tempSize)*tempSize));
  for(int j =0; j<lastSetSize;j++){
 int temp = myFile.read();

 intTempFile[j]=temp;
  index++;

  }
  Serial.println();
  Serial.println("tempFile");
  for(int k =0;k<lastSetSize;k++){
  Serial1.write(intTempFile[k]);
  }
    myFile.close();

}

```

Server's code for Sending from NodeMCU to other Node MCU:

```
    if (Serial.available()) {
          byte readStr[100];
        Serial.readBytes(readStr,100);
       // Serial.write(readStr[i]);
        }

         port.beginPacket("192.168.4.255",2390);
         for(int i =0; i <100; i++){
        port.write(readStr[i]);
         }
         port.endPacket();
      }

```

Module's Code for NodeMCU to recieve data from other NodeMCU:

```
void dumpMode(){
  while(1){
    int packetSize = port.parsePacket();
      if (packetSize) {
        port.read(packetBuffer, fileSentSize);
        Serial.write(packetBuffer);

  }
  if(Serial.available()){
    String reply = Serial.readString();
    if(reply == "STOP"){
      break;
    }

    }
  }
}

```

Server's NodeMCU Sent Data:

```
RIFFäN  WAVEfmt      À]  À]    dataÀN  €€€€€€€€€€€€€€€€€€€€€€€€

```

Module's NodeMCU Recieved Data:

```
RIFFäN€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€

```

Is there something im doing wrong thats why NodeMCU is not either sending or recieving every content of the wav file?

Thank you for those who will help out. :)

# Answer
> 0 votes
You *could* just program the NodeMCUs and skip the Megas; they have sufficient pins to drive an SD card. There's so much wrong with your code: opening and closing the same file so many times and *then* having to seek for every chunk because of the previous nastiness, writing and reading bytes singly instead of just passing in a buffer, among others. I also hope you know that you didn't send only the WAV data to the transmitting NodeMCU; there's a bunch of stuff (CRLF, file size, etc) before that.

Your particular problem's most likely the fact that your Mega "server" is just sending chunks continuously to the NodeMCU, never minding if the latter is reading them quickly enough that its serial buffer doesn't overflow, especially considering you're sending data over the network between chunks. You should also note that UDP isn't exactly the most reliable protocol; it's connection-less and so packets will be lost. It's generally used if packet loss isn't a big deal (in your case, it is) or if upper layers implement error control.

What you need to implement is a way for each party to confirm that they've received the next chunk before the their sender transmits the next. The Mega needs to wait for a 'go-ahead' from the NodeMCU before sending the next chunk; for instance, the NodeMCU can reply each chunk with the number of bytes it actually read, so you can know if you should reduce your chunk size to not overwhelm the NodeMCU buffer.

The packets sent over the network also need to be tagged with a sequence number (because of aforementioned error control). The NodeMCU at the receiver needs to acknowledge the packet it received each packet, perhaps by sending that packet's number to the transmitting NodeMCU. This will help ensure all packets are received and in order. Or you could just use TCP which already implements these and more.

---
Tags: arduino-mega, wifi, nodemcu
---


# Question
Title: Testing ID and Serial Communication (Update)
Here is my challenge: I have to create a sketch where I would have a prompt asking the user to enter an ID. If it is successful, it would turn on the green LED and response with "Hello, your name is so-so." If it failed, it would turn on the red LED and response with "Invalid username! Try again."

The code is here:

```
//Establish myID as CHAR data type
 char myID = 'tg123';
 //Establish testID to receive data to be tested against myID
 char testID;

 //Establish green and red LEDs to PWM pins
 const int gLED = 10;
 const int rLED = 5;

 void setup()
 {
  //Establishing baud rate at 9600
  Serial.begin(9600);
  pinMode(gLED, OUTPUT);
  pinMode(rLED, OUTPUT);
 }

 void loop()
 {
  //Act when there are data in the buffer
  while (Serial.available())
  {
    testID = Serial.read();
    //If data = myID, turn on green LED and acknowledge
    if (testID == myID)
    {
      digitalWrite(gLED, HIGH);
      digitalWrite(rLED, LOW);
      Serial.println("Hello! Your name is Trevor.");
      delay(5000);
    }
    else
    {
      digitalWrite(rLED, HIGH);
      digitalWrite(gLED, LOW);
      Serial.println("Invalid ID! Try again.");
      delay(2000);
    }
  }
 }

```

Two problems I have had with this:

1. The damn thing would print the line "Please enter your ID:" infinitely if it was inside the loop, so I got fed up and moved it to the set up, and
2. no matter what I enter in the serial monitor, it does not do anything.

Update: After reading Arduino's website, I found I can predefine the char data type by adding `char myID = 'tg123';`. It is getting closer to achieving what I want, but it's exhibiting some strange behavior. When I type in exactly tg123 in the serial monitor, it would report the error message as defined in the sketch before passing.

# Answer
You are assigning a string to a single character here.

> char myID = 'tg123';

Instead you should make it a String variable. And compare it after all the characters are recieved.

> String myID = "tg123";

And Here is the modified code you should test with. In this case I have assumed you simply write the ID (string) in serial terminal and hit enter.

N.B. If you want to enter each character one by one, then it will not be able to catch the whole string. For this case you have to add some time-out to wait for next character to arrive.

```
String recvData = "";
void loop()
{
  while (!Serial.available());
  while (Serial.available())
  {
    char ch = Serial.read();
    recvData += ch;
  }
  if (myID == recvData)
  {
    digitalWrite(gLED, HIGH);
    digitalWrite(rLED, LOW);
    Serial.println("Hello! Your name is Trevor.");
    delay(5000);
  }
  else
  {
    digitalWrite(rLED, HIGH);
    digitalWrite(gLED, LOW);
    Serial.println("Invalid ID! Try again.");
    delay(2000);
  }
  recvData = "";
 }

```
> 1 votes

# Answer
When you use the Arduino IDE to compile your code for an Uno, it will tell you

> Sketch uses 2106 bytes (6%) of program storage space. Maximum is 32256 bytes.
> Global variables use 237 bytes (11%) of dynamic memory, leaving 1811 bytes for local variables. Maximum is 2048 bytes.

as if there had been a clean and correct compilation. However, if you compile it via `make` and a makefile (see, eg, sudar's Arduino Makefile) you will see a warning like the following:

> stringInit1.ino:2:14: warning: character constant too long for its type \[enabled by default\]
> char myID = 'tg123';

where `stringInit1` stands for whatever you call your sketch.

The `char` data type stands for a single character. To represent a text string, use either an array of characters (for example, `char *myID = "tg123"` or `char myID[] = "tg123"`) or a `String` type (which, in general, is problematic on small-RAM embedded processors).

Then, to make the comparison, keep track of how many characters have been input so far, and as you input each character, compare it to the current character of `myID`, clearing a match-flag if characters don't match. Eg, `if (testChar != myID[currentCount]) matchFlag = false;`. Note, initialize `currentCount` to zero and `matchFlag` to true in `setup()` and before each retry.
> 0 votes

---
Tags: arduino-uno, serial, communication, data-type
---


title: Arduino nano Serial port not recognized

text:
# Question
Title: Arduino nano Serial port not recognized
First sorry for my bad english, not my native lenguage.

Today I started working on my Arduino nano (first time used). When plugged for the first time the "L" led started blinking, after that I tried to write a simple program but I noticed that the "Port" option on the Arduino IDE was Gray. So I couldn't choose the port. After that I searched A LOT but nothing seems to work.

While trying to test if the problem was the Arduino and not the PC, I make a simple circuit with 1 LED, 1 resistor of 1Kohm, and a breadboard. I connected the 5V pin to the LED and GNG to the other point, And when I did this the "L" LED stopped blinking forever. I am 100% sure that I did not make a short circuit. ¿Maybe the breadboard is in a bad state?

Additional info:

-Windows 10.
-The port doesn't appear at Device manager (tried every port of my notebook).
-The "POW" led is ON when I plug the USB.
\- The Arduino is a clone (chip CH340G).

So now I don't know if the problem is the port or if the Arduino Nano is dead because of a possible short circuit between 5V and GND pins.

thanks in advance!

# Answer
I think your Arduino got short or the transmitter-receiver in it is damaged so the device manager cannot recognize the COM port.It once happened with my Arduino Uno. Try changing the USB cable.If it does not help your Arduino is damaged.
> 1 votes

---
Tags: arduino-nano
---


title: Yun UBoot Prompt Not Showing

text:
# Question
Title: Yun UBoot Prompt Not Showing
I have a Geeetech Iduino Yun Shield. I accidentally flashed the wrong firmware image (not the sysupgrade) to the board. I then tried using the Yun UBoot Reflash method. However, when I open the console monitor from the IDE and restart/reboot the board, I do not get the UBoot prompt. I have attempted to run it at least ten times without receiving any console/serial output.

*EDIT*: The shield is running on a Leonardo base board.

Is there anything I can do to load the correct firmware onto the board and get it operational or is the board truly bricked? If so, is it possible to obtain a new Atheros AR9331 board to replace the existing one or should I buy a new Yun?

**Update**: I have tried to get the shield to do an FTP boot, as detailed here by Majenko. I get to the stage where I get the `dr_boot>` prompt. However, when I type in `tftpboot 0x81000000 dragino2-yun-common-v2.0.6-kernel.bin`, I get no feedback; it just sits there indefinitely (unless I interupt the process). I can't figure out what I'm doing wrong.

# Answer
> 0 votes
The shield is very different to the real Yun when it comes to serial communication.

Typically the Atheros's UART is mapped to pins 0/1 of the shield for communication with the board it is plugged in to. Those pins are also the pins you use to communicate with the PC, so the normal YunSerialTerminal sketch can't be used.

Instead you will have to lift those pins out of the socket they go into (depending on the shield you may just be able to bend them slightly) and then manually connect them (along with ground) to an external USB to UART adaptor (e.g., FT232) to use for the communication. Nothing needs to be installed into the Arduino board since that is now just being used as a power supply.

See this answer for which pins to use to run the shield stand-alone.

---
Tags: shields, arduino-leonardo, arduino-yun, firmware
---


# Question
Title: Makeblock Arduino keeps stopping from motor overpower protection
I got a makeblock Arduino. Sometimes when I make it go forward at full speed, all motors stop for 3 seconds and it beeps shortly. I think it is that the motors are a little hard to turn for a moment and it stops to prevent damage to the motors. It is getting very annoying. Is there any way to disable it or make it less sensitive?

# Answer
It is unlikely the pause in operation is because of the motors. It is more likely the Makeblock is stopping because the motor controllers are too hot. Next time try to identify which chips on the board are controlling the motors and test if they are getting hot to the touch. If so, consider adding heat sinks to these chips to mitigate any heat dissipation problems.

An alternative explanation involves a limited power supply. It could be that when the motors are demanding high current, the voltage drops and the processor resets. Consider a power supply that can offer more amperage. Or larger capacity batteries.
> 0 votes

---
Tags: motor
---


title: FastLED int + float problem

text:
# Question
Title: FastLED int + float problem
I'm working on a code based on PaletteCrossfade.ino example. But I found the motion speed too fast. It's stated in this:

```
  static uint8_t startIndex = 0;
  startIndex = startIndex + 1; /* motion speed */
  FillLEDsFromPaletteColors(startIndex);
  FastLED.show();
  FastLED.delay(1000 / UPDATES_PER_SECOND);
}

void FillLEDsFromPaletteColors( uint8_t colorIndex) {
  uint8_t brightness = 255;
  for( int i = 0; i < NUM_LEDS; i++) {
    leds[i] = ColorFromPalette( currentPalette, colorIndex + sin8(i*16), brightness);
colorIndex += 3;

```

Since the startIndex defined in `uint8_t`, it cant be lower than 1. So I used float and set it to 0.2 in my code. Which seems to work, and animation slowed down. However I'm not sure how is that float value added into the `ColorFromPalette` function.

Its documentations states:

> CRGB ColorFromPalette (const CRGBPalette16 &pal, uint8\_t index, uint8\_t brightness=255, TBlendType blendType=LINEARBLEND)

To my understanding it accepts only integer, and also int based sin8 being added to float value. So, what exactly happens there? Is this method viable, or is there any better way to slow down the animation?

I'm thinking about adding a millis() based delay and only increasing the colorindex every 2-3 seconds or so.

# Answer
> 1 votes
The code you have seems to fill the lights with a colour and change every nth of a second. You could control that to change every 1ms to 2^16ms (which is 65 seconds) just by changing the FastLED.delay() value.

sin8() might return a float or I suspect an int, but colourIndex is an uint8\_t so that is a whole number. All it is doing is picking a colour, based on some scheme. If the value passed to the function is a float i.e. 1.611 then it will be converted to an int by taking just the whole number part, in this case 1. It does not round up.

Its not clear what you are trying to do.

If you are trying to slow the rate that the LEDs change colour, you need to change the delay statement.

If you want to smooth the transition between colours you need to change in the area of the sin8 statement, but what you change it to will depend on what your palette is loaded with.

Hope that helps, if not please can you try and describe what it is you are tying to achieve.

# Answer
> 0 votes
In order to change the update rate you have to change it.

You have two choices in ColourPalette example:

1st:

# LINE 10

```
#define UPDATES_PER_SECOND 100 // higher number means more frames a second

```

2nd:

# LINE 58

```
FastLED.delay(1000 / UPDATES_PER_SECOND); // change it to:
FastLED.delay(2000); //2000ms means 0.5 frame per second or 1 frame every two seconds

```

---
Tags: arduino-uno, float
---