# Question
Title: How do I wire a ground rail to a VEROboard?
I’m looking to move my project from a breadboard to a vero board. However, I’m not sure how to go about soldering in my ground and power connections as the veroboard doesn't seem to have dedicated ground and power rails like the breadboard.

I’ve also attached a photo of my schematic in its current state.

Also, I’m using an Arduino Nano Board as opposed to the UNO featured in the schematic. (I’ve just used it as a placeholder as I could find a component for the nano.

Any help would be greatly appreciated.

Here’s a photo of the type of veroboard I have:

# Answer
> 0 votes
There's nothing special about ground. It's just a wire like any other.

You *could* designate a row of holes as ground then link them all together, but you don't need to. Just wire your grounds together as you would any other connection.

---
Tags: breadboard
---


title: Serial communication between Arduinos

text:
# Question
Title: Serial communication between Arduinos
I'm trying to send data from Arduino Mega to UNO. The master code sends characters 'x' and 'a' every half second to the slave Arduino UNO. Slave receives the characters and switches the state of the onboard LED. Here I'm trying to print some text in the beginning of the loop and the characters received. Instead of the letters it is printing numbers as given below. Why this line `Serial.println('Soft serial avaialble')` prints numbers? How to print real text received from the master?

```
> 27749
> 97
> 27749
> 120
> 27749

```

**Master code:**

```
// Include the Software Serial library
#include <SoftwareSerial.h>
// Define a Software Serial object and the used pins
SoftwareSerial softSerial(8, 9);  // RX, TX
void setup()  {
    Serial.begin(9600);
    softSerial.begin(9600);
}
void loop()  {
    // Sends characters 'x' and 'a' every half second.
    if (Serial.available())  {
        softSerial.write('x');
        delay(500);
        digitalWrite(LED, LOW);
        delay(500);
    }
}

```

**Slave code:**

```
// Include the Software Serial library
#include <SoftwareSerial.h>
// Define a Software Serial object and the used pins
SoftwareSerial softSerial(8, 9);
// LED Pin
int LED = 13;

void setup()  {
    softSerial.begin(9600);
    Serial.begin(9600);
    pinMode(LED, OUTPUT);

}
void loop()  {
    Serial.println('Soft serial avaialble');
    if (softSerial.available())  {
        int com = softSerial.read();
        if (com == 'x')  {
            Serial.println(com);
            digitalWrite(LED, LOW);
        } else if (com == 'a'){
            Serial.println(com);
            digitalWrite(LED, HIGH);
        }
    }
}

```

# Answer
In your slave, you've declared `com` as an int, so Serial.println() interprets it that way. If you want to keep it as int except for printing, cast Serial.println()'s argument to char:

```
Serial.println((char)com);

```
> 1 votes

# Answer
In addition to JRobert's remark, note that strings in C++ are delimited by *double* quotes, thus:

```
Serial.println("Soft serial avaialble");

```
> 0 votes

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


# Question
Title: Global array doesn't get assigned the space it would take up in memory
I have this sketch:

```
const uint32_t len = 65536;
uint8_t arr[len];

void setup() {}

void loop() {}

```

The length of the array should fit into the dynamic memory. However, when I compile the sketch it says this in the output window:

```
Sketch uses 10528 bytes (0%) of program storage space. Maximum is 2031616 bytes.
Global variables use 13504 bytes (1%) of dynamic memory, leaving 1034224 bytes for local variables. Maximum is 1048576 bytes.

```

If I change `len` to 10, that doesn't change. The compiler is set to "Debug", so it should not get optimized away. This indicates, that the memory isn't actually being allocated. What seems to be the problem here?

I am compiling for the Teensy 4.0, but the output is the same in essence for the Arduino Uno and other boards (with lower memory sizes).

# Answer
There is no problem here. Only the compiler is a bit smarter than you anticipated. It sees, that you are not using `arr` anywhere, so it just optimizes it out.

There are two ways to prevent that, if you really want to:

* I think you can use flags to tell the compiler, that this shouldn't be optimized out. I'm no expert in this, others might know more about this and add their own answer
* You can just start using it.
> 4 votes

---
Tags: array, memory-usage, teensy, memory, compiler
---


# Question
Title: LED sometimes don't turn off when a button is pressed
I'm still very new to this but I've put together some code that when a button is pressed, my servo runs continuously, a second button rotates it the other way and a third cancels everything.

A red or green comes on depending on the rotation and this can be one using an IR receiver also.

Issue I'm having is that randomly, 1/5 of the time, the red or green LED does not turn off. I can manually kill it using the third cancel button or just press it a couple times until it turns off as it should on the next push of the button.

Cant work out where im going wrong.

I also find my IR remote works maybe 60% of the time. Any help would be greatly appreciated.

```
#include <Servo.h>
Servo servo1;
int servoPin = 9;
#include "IRremote.h"

/*----- Variables, Pins -----*/

int receiver = 12; // Signal Pin of IR receiver to Arduino Digital Pin 6
int RledPin = 5;
int GledPin = 3;
int buttonApin = 7;
int buttonBpin = 8;
int buttonCpin = 4;
unsigned long elapsedTime;
unsigned long onTime;

/*-----( Declare objects )-----*/
// Setup of proper sequencing for Motor Driver Pins
// In1, In2, In3, In4 in the sequence 1-3-2-4

IRrecv irrecv(receiver);    // create instance of 'irrecv'
decode_results results;     // create instance of 'decode_results'

void setup()
{
  irrecv.enableIRIn(); // Start the receiver
  servo1.attach(servoPin);
  servo1.write(90);
  pinMode(RledPin, OUTPUT);
  pinMode(GledPin, OUTPUT);
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
  pinMode(buttonCpin, INPUT_PULLUP);

}

void loop(){

if (digitalRead(buttonApin) == LOW)   // Switch is closed to start LED timer
         {
          digitalWrite(RledPin, HIGH);  // Red LED comes On
          digitalWrite(GledPin, LOW);  // Green LED Goes Off
          servo1.attach(servoPin); //Servo is activated
          servo1.write(0);  //Servo turns on clockwise
            onTime = millis();  //time set
          }

      if(onTime > 0 && millis() - onTime > 1500)  //time limit target
            {
            servo1.write(90); //Servo stops
            servo1.detach(); //servo deactivated
            delay(500); //used to sync the servo stop with the LED off
            digitalWrite(RledPin, LOW);  // LED goes off
              onTime = 0;  //time reset
            }

if (digitalRead(buttonCpin) == LOW)   // Switch is closed to start LED timer
         {
          digitalWrite(GledPin, HIGH);  // Green LED comes On
          digitalWrite(RledPin, LOW);  // RED LED Goes Off
          servo1.attach(servoPin); //Servo is activated
          servo1.write(180);  //Servo turns on anti-clockwise
            onTime = millis();  //time set
          }

      if(onTime > 0 && millis() - onTime > 1500)  //time limit target
            {
            servo1.write(90); //Servo stops
            servo1.detach(); //servo deactivated
            delay(500);
            digitalWrite(GledPin, LOW);
              onTime = 0;  //time reset
            }

if (digitalRead(buttonBpin) == LOW) //Deactivation Sequence KILL SWITCH
  {
    digitalWrite(RledPin, LOW);
    digitalWrite(GledPin, LOW);
    servo1.write(90);
    servo1.detach();
      onTime = 0;  //time reset
  }

  if (irrecv.decode(&results)) // have we received an IR signal?

  {
    switch(results.value)

    {

      case 0xFFE01F: // DOWN button pressed
                      {
          digitalWrite(RledPin, HIGH);  // Red LED comes On
          digitalWrite(GledPin, LOW);  // Green LED Goes Off
          servo1.attach(servoPin); //Servo is activated
          servo1.write(0);  //Servo turns on clockwise
          onTime = millis();  //time set
          }

          if(onTime > 0 && millis() - onTime > 2000)  //time limit target
            {
            servo1.write(90); //Servo stops
            servo1.detach(); //servo deactivated
            digitalWrite(RledPin, LOW);  // LED goes off
             onTime = 0;  //time reset
            }
            break;

      case 0xFF906F: // UP button pressed
                      {
          digitalWrite(GledPin, HIGH);  // Green LED comes On
          digitalWrite(RledPin, LOW);  // RED LED Goes Off
          servo1.attach(servoPin); //Servo is activated
          servo1.write(180);  //Servo turns on anticlockwise
          onTime = millis();  //time set
          }

      if(onTime > 0 && millis() - onTime > 2000)  //time limit target
            {
            servo1.write(90); //Servo stops
            servo1.detach(); //servo deactivated
            digitalWrite(GledPin, LOW);  // LED goes off
             onTime = 0;  //time reset
            }
            break;

      case 0xFF02FD: // PAUSE button pressed
                      servo1.write(90);
                      servo1.detach();
                      digitalWrite(GledPin, LOW);
                      digitalWrite(GledPin, LOW);
                      break;

    }

      irrecv.resume(); // receive the next value

  }
}/* --end main loop -- */

```

# Answer
> 3 votes
Found the answer!

I added serial print to every line and realised that my kill process after the time elapsed was switching between the red led and green led.

I didn't need the if time elapsed function many times, just once. Deleted that portion and it worked perfectly. Seems to have fixed the IR troubles too.

Working code:

```

#include <Servo.h>
Servo servo1;
int servoPin = 9;
#include "IRremote.h"

/*----- Variables, Pins -----*/

int receiver = 12; // Signal Pin of IR receiver to Arduino Digital Pin 6
int RledPin = 5;
int GledPin = 3;
int buttonApin = 7;
int buttonBpin = 8;
int buttonCpin = 4;
unsigned long elapsedTime;
unsigned long onTime;

/*-----( Declare objects )-----*/
// Setup of proper sequencing for Motor Driver Pins
// In1, In2, In3, In4 in the sequence 1-3-2-4

IRrecv irrecv(receiver);    // create instance of 'irrecv'
decode_results results;     // create instance of 'decode_results'

void setup()
{
  irrecv.enableIRIn(); // Start the receiver
  servo1.attach(servoPin);
  servo1.write(90);
  pinMode(RledPin, OUTPUT);
  pinMode(GledPin, OUTPUT);
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
  pinMode(buttonCpin, INPUT_PULLUP);
  Serial.begin(9600);
  pinMode(LED_BUILTIN, HIGH);

}

void loop(){

if (digitalRead(buttonApin) == LOW)   // Switch is closed to start LED timer
         {
          digitalWrite(RledPin, HIGH);  // Red LED comes On
          Serial.println("RED comes on");
          digitalWrite(GledPin, LOW);  // Green LED Goes Off
          Serial.println("green off");
          servo1.attach(servoPin); //Servo is activated
          Serial.println("red servo attach");
          servo1.write(0);  //Servo turns on clockwise
          Serial.println("red servo spins");
            onTime = millis();  //time set
         }

if(onTime > 0 && millis() - onTime > 1500)  //time limit target
            {
            servo1.write(90); //Servo stops
            Serial.println("servo stops spinning");
            digitalWrite(RledPin, LOW);  // LED goes off
            digitalWrite(GledPin, LOW);  // LED goes off
            Serial.println("red RED goes off");
            delay(500);
            Serial.println("delay");
            servo1.detach(); //servo deactivated
            Serial.println("servo Rled dettach");
              onTime = 0;  //time reset

         }
if (digitalRead(buttonCpin) == LOW)   // Switch is closed to start LED timer
         {
          digitalWrite(GledPin, HIGH);  // Green LED comes On
          Serial.println("green comes on");
          digitalWrite(RledPin, LOW);  // RED LED Goes Off
          Serial.println("RED goes off");
          servo1.attach(servoPin); //Servo is activated
          Serial.println("green servo attached");
          servo1.write(180);  //Servo turns on clockwise
          Serial.println("green servo spins");
            onTime = millis();  //time set
         }

if (digitalRead(buttonBpin) == LOW) //Dectivation Sequence KILL SWITCH
  {
    digitalWrite(RledPin, LOW);
    Serial.println("total red off");
    digitalWrite(GledPin, LOW);
    Serial.println("total green off");
    servo1.write(90);
    Serial.println("total servo off");
    servo1.detach();
    Serial.println("total detach");
      onTime = 0;  //time reset
  }

  if (irrecv.decode(&results)) // have we received an IR signal?

  {
    switch(results.value)

    {

      case 0xFFE01F: // DOWN button pressed
                      {
          digitalWrite(RledPin, HIGH);  // Red LED comes On
          digitalWrite(GledPin, LOW);  // Green LED Goes Off
          servo1.attach(servoPin); //Servo is activated
          servo1.write(0);  //Servo turns on clockwise
          onTime = millis();  //time set
          }
          break;

      case 0xFF906F: // UP button pressed
                      {
          digitalWrite(GledPin, HIGH);  // Green LED comes On
          digitalWrite(RledPin, LOW);  // RED LED Goes Off
          servo1.attach(servoPin); //Servo is activated
          servo1.write(180);  //Servo turns on clockwise
          onTime = millis();  //time set
          }
          break;

      case 0xFF02FD: // PAUSE button pressed
          servo1.write(90);
          digitalWrite(GledPin, LOW);
          digitalWrite(GledPin, LOW);
          delay(500);
          servo1.detach();
          break;
    }

      irrecv.resume(); // receive the next value

  }
}/* --end main loop -- */

```

---
Tags: led
---


# Question
Title: Why does Adafruit guide for motors use transistors on ground rather than modulating the power source
I'm going through the Adafruit Motors guide for Arduino, found here, and I'm struggling to understand how each of these parts play in. From what I understood, pulse width modulation is basically a way to send varying levels of power through a digital output source. Additionally, it seems that the guide is using a transistor with the PWM signal as the gate, so it can allow the percentage given by the PWM signal to control how much flow is given to the motor. However, what I'm confused here is that both the power and ground are interfacing with this transistor/diode setup.

This is more specifically what I mean, on the bottom seems really simple: the PWM signal comes on the yellow wire, fed through the resistor so that it doesn't fry the transistor into the gate.

After this though, there's a ground signal being passed into the source leg of the transistor, and the sink leg is connected to both a diode for power AND the ground of the motor? I might be misunderstanding how a diode works but this doesn't seem to make sense as to why the ground signal is being modulated.

My initial thought for this would be a system where only the power of the motor is varied by the PWM signal, sorta like in this way (apologies for the terrible drawing style, I haven't gotten used to some of the Arduino sketching software online):

I've not gotten to try this yet, but I assume it wouldn't work or would destroy components somehow since this does seem to be a simpler solution, and it's not being used. I was sorta trying to figure out 1) why my solution would be bad and 2) how the official solution works, as they haven't really given any actual schematic (not that I would understand it, haha) Any help would be appreciated! Thanks!

# Answer
I think your confusion does indeed stem from the diode. You can forget the diode, it doesn't feature in the switching of the motor. When a motor runs it can generate large negative voltages caused by the repeatedly collapsing magnetic field. The diode, which is *connected backwards*, exists to take those negative voltages and prevent them damaging the rest of the circuit.

The transistor arrangement in use is called *common emitter*, and is also known as a *low-side switch* when used in *saaturation* between the load and GND, as in this situation. It doesn't matter to the motor if you have the switch between the motor and GND (using an N-channel MOSFET or NPN bipolar transistor) or between power and the motor (using a P-channel MOSFET or PNP bipolar transistor), but it does matter to the Arduino.

It is harder to switch a "high side switch" from an Arduino, especially if your power supply is *higher* than the voltage the Arduino runs at. Since the switching is controlled by the difference in voltage between the "common" point (emitter \[BJT\] / source \[MOSFET\]) and the switching signal (Arduino), which is limited to 5V, any "common" point voltage that is higher than that is unreachable by the switching signal, so ends up in being always on and the switching fails.

It *is* possible to switch the high side, but you need an extra driving stage to allow the higher voltage switching.

For this *specific* circuit where the power is 5V it's not as susceptible to the problem, but this is a rare case. Normally you will be driving motors at a higher voltage, such as 12V, and there you *will* need an extra driving stage, or just use the far simpler low-side switch arrangement this circuit teaches you.
> 2 votes

# Answer
**Your schematic**

The blue line in your first schematic "going up" that you marked GND, is not really GND but one of the motor connections. If you look at the Adafruit schematic you can see this.

The motor in the Adafruit schematic in the link you provided is connected between 5V and the diode's Anode (and the transistor's collector).

**Flyback diode**

The diode is a so-called "flyback diode", connected between the motor connections to "soak up" back-EMF that occurs when the motor is turned off and its magnetic field collapses. If the diode would not be there, there would be a voltage spike on the transistor's collector, possibly damaging it.

**Low-side switching**

The "Adafruit" solution uses an NPN transistor as a switch on the low side of the motor when the I/O pin is high, like the schematic on the right. This is a very common setup as it has almost no disadvantages.

**High-side switching**

Your own suggestion (called high-side switching, shown on the right) would work as well (with the addition of a flyback diode) but it would need a different type of transistor, a PNP transistor. Also, the I/O inputs would work in an inverted way: when the I/O pin is low, the motor will be on and when the I/O pin is high, it will be off.

Note that high-side switching will only work when the supply voltage is lower or equal to the voltage that's on the I/O pins. You can't turn on a 12V motor this way, for example. With low side switching, you will not have this problem and you can switch higher voltages.

simulate this circuit – Schematic created using CircuitLab
> 1 votes

---
Tags: motor
---


# Question
Title: First Arduino Project - Need Advice (powering WS2812B LEDs)
I'm making a long LED display made up of 3 (8x32) LED matrices to go inside of a car. I can't seem to find any in-depth guides on this sort of thing. If anybody has examples that they would like to share please do!

The major issue I'm having is power. I'm extremely new to electronics, and I don't understand how these lights can be powered separately, and still be addressably lit by the Arduino?

Parts: 3\* LED matrices (8x32)

https://www.amazon.com/gp/product/B088BTXHRG/ref=ppx\_yo\_dt\_b\_asin\_title\_o01\_s00?ie=UTF8&psc=1

1\* Mega 2560

Here's the mock-up schema:

I forgot to draw in a switch, and a power line leading to the Arduino. But let's assume there will be a switch before the resistor and a line that feeds power to the MEGA 2560.

What in this schematic doesn't look or sound right?

Thank you all in advance for your help. This is probably not at all how to go about building circuits, and I'm trying my best to learn. All advice is wanted!

# Answer
**Powering the LED panels**

Powering your panels will be your greatest challenge!

These LED panels are powered by a single +5V power input per panel and *do not need a resistor in the power supply path* (they actually need a very low resitance path). You do need a good quality +12V DC -\> +5V DC power supply (or multiple, as explained below).

Since 3 x 256 RGB LEDs require a large amount of power when they're all lighted at the same time (something like 60mA * 768 =~ 46A), the power supply should be able to accomodate that. It might be better to use three individual, smaller (~15A) power supplies. You could opt for power supplies smaller than 15A, but you should ensure that all LEDs will never light up at full intensity at the same time.

For supplying power from a 12V car battery, you could use high quality 12V DC to 5V DC buck converters (they're efficient). Use good quality cable with a diameter large enough for transporting the large currents necessary. If you need connections in the path of the power supply, make sure they are good quality as well. To reduce losses in long stretches of wire, you should place the buck converter(s) near the LED panels.

**Connecting the data lines**

The color and intensity of Individual LEDs is controlled via the data input coming from your Arduino and it only needs one input to control all 768 LEDs. The first panel's "data out" should be connected to the next panel's "data in" and so on, like your drawing.

**Software**

I recommend you look up the *FastLED library* and some of its examples to get familiar with controlling large amounts of addressable RGB LEDs. There are many good examples and interesting projects out there.
> 2 votes

---
Tags: arduino-mega, power, project
---


# Question
Title: Message is sent multiple times from one arduino to another, using nRF24L01
I am trying to build a bidirectional communication channel, using nRF24L01 and two arduinos. The message is introduced using a button (but) in Morse code, decoded and then sent when another button (but\_send) is pressed. Although everything seems to work fine, the message is sent multiple times even though I added delays. I am a beginner in Arduino and I have no idea what else i could do. I even tried deleting the string right after radio.write, but it doesn't seem to work either. If anyone has an idea, please help!

These are the two codes. They are quite similar, but i added them both just in case:

```
#include <LiquidCrystal.h>
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
struct record
{
  char mesaj[10];
  boolean state = 1;
};

typedef struct record Record;
Record  button_state, button_state1 ;
RF24 radio(9, 10); // CE, CSN(pini nrf01)
const byte addresses [][6] = {"00001", "00002"};  //Setting the two addresses. One for transmitting and one for receiving
String code = "";
int len = 0;
char ch;
int ok;
char new_char;
int i1 = 0;
int i2 = 1;
const int but_send = 8;
const int but = 5;
const int led = 4;
const int del = 3;
String a = "";
unsigned long pres_len = 0, rel_time, pres_time = 0, old_time_len = 0, old_pres = 0, space = 0;
int state = 0;
int unit_delay = 250;
int min_delay = 10;
int buttonState = 0;

char MakeString()
{
  if (pres_len < (unit_delay * 3) && pres_len > 50)
  {
    return '.';                        //if button press less than 0.6sec, it is a dot
  }
  else if (pres_len > (unit_delay * 3))
  {
    return '-';                        //if button press more than 0.6sec, it is a dash
  }
}

void Morse_decod()
{
  static String morse[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....",
                           "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
                           ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "!"
                          };
  int i = 0;
  while (morse[i] != "!")
  {
    if (morse[i] == code)
    {
      Serial.print(char('A' + i));
      a = a + char('A' + i);
      Serial.print(" ");
  }
  if (morse[i] == "!")
  {
    Serial.println("");
    Serial.println("This code is not exist!");
  }

  code = "";
}
void sendText()
{
  // Aici trebuie sa fe codul pentru trimiterea efectiva a msj
  if (ok == 1) {
    Serial.println("Lavinia:" + a);
  }
  ok = 0;

  delay(100);
}
void setup() {
  Serial.begin(9600);
  pinMode(but, INPUT_PULLUP);
  pinMode(but_send, INPUT_PULLUP);
  pinMode(del, INPUT_PULLUP);

  pinMode(led, OUTPUT);
  radio.begin();                           //Starting the radio communication
  radio.openWritingPipe(addresses[0]);     //Setting the address at which we will send the data
  radio.openReadingPipe(1, addresses[1]);  //Setting the address at which we will receive the data
  radio.setPALevel(RF24_PA_MIN); //You can set it as minimum or maximum depending on the distance between the transmitter and receiver.

}
void loop() {

label:
  while (digitalRead(but) == HIGH) {
    delay(5);
    radio.startListening();

    if (radio.available())                     //Looking for incoming data
    {
      radio.read(&button_state, sizeof(button_state));
      if (button_state.state == 0)
      {

        ok = 1;
        sendText();
        String final = "";

        for (int i = 0; i < strlen(button_state.mesaj); i++)
        {
          final += String(button_state.mesaj[i]);
        }
        ok = 1;
        Serial.println("Iulia: " + final);
        button_state.state = 1;
        radio.stopListening();
      }
      else
      {
        //nu se intampla nimic daca eu nu am trimis mesaj

      }
      delay(5);

      radio.stopListening();                           //This sets the module as transmitter
      button_state1.state = digitalRead(but_send);
      int n = a.length();
      char char_array[n + 1];
      strcpy(char_array, a.c_str());
      strcpy(button_state1.mesaj, char_array);
      radio.write(&button_state1, sizeof(button_state1));   //Sending the data
    }

    if (digitalRead(del) == LOW && a[0] != '\0' ) {
      Serial.println("Deleted string");
      a = "\0";
      Serial.println(a);
    }

  }
  old_pres = rel_time;
  pres_time = millis();
  digitalWrite(led, HIGH);
  while (digitalRead(but) == LOW) {}
  rel_time = millis();
  digitalWrite(led, LOW);
  pres_len = rel_time - pres_time;
  space = pres_time - old_pres;
  if (pres_len > min_delay)
  {
    code += MakeString();
  }
  while ((millis() - rel_time) < (unit_delay * 3))
  {
    if (digitalRead(but) == LOW)
    {
      goto label;
    }

  }

  Morse_decod();
  delay(1000);

}

```

```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(9, 10); // CE, CSN(pini nrf01)
#include <LiquidCrystal.h>
struct record
{
  char mesaj[10];
  boolean state = 1;
};

typedef struct record Record;
const byte addresses [][6] = {"00001", "00002"};  //Setting the two addresses. One for transmitting and one for receiving
String code = "";
int len = 0;
char ch;
int ok;
int ok2;
char new_char;
int i1 = 0;
int i2 = 1;
const int but_send = 8;
const int but = 5;
const int led = 4;
const int del = 3;
String a = "";
unsigned long pres_len = 0, rel_time, pres_time = 0, old_time_len = 0, old_pres = 0, space = 0;
int state = 0;
int unit_delay = 250;
int min_delay = 10;
Record  button_state, button_state1 ;

char MakeString()
{
  if (pres_len < (unit_delay * 3) && pres_len > 50)
  {
    return '.';                        //if button press less than 0.6sec, it is a dot
  }
  else if (pres_len > (unit_delay * 3))
  {
    return '-';                        //if button press more than 0.6sec, it is a dash
  }
}

void Morse_decod()
{
  static String morse[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....",
                           "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
                           ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "!"
                          };
  int i = 0;
  while (morse[i] != "!")
  {
    if (morse[i] == code)
    {
      Serial.print(char('A' + i));
      a = a + char('A' + i);
      Serial.print(" ");
  }
  if (morse[i] == "!")
  {
    Serial.println("");
    Serial.println("This code is not exist!");
  }

  code = "";
}
void sendText()
{
  // Aici trebuie sa fe codul pentru trimiterea efectiva a msj
  if (ok == 1) {
    Serial.println("Iulia:" + a);
  }
  ok = 0;

  delay(100);
}
void setup() {
  Serial.begin(9600);
  pinMode(but, INPUT_PULLUP);
  pinMode(but_send, INPUT_PULLUP);
  pinMode(del, INPUT_PULLUP);

  pinMode(led, OUTPUT);
  radio.begin();                           //Starting the radio communication
  radio.openWritingPipe(addresses[1]);     //Setting the address at which we will send the data
  radio.openReadingPipe(1, addresses[0]);  //Setting the address at which we will receive the data
  radio.setPALevel(RF24_PA_MIN); //You can set it as minimum or maximum depending on the distance between the transmitter and receiver.

}
void loop() {
label:
  while (digitalRead(but) == HIGH) {

    delay(5);
    radio.stopListening();                             //This sets the module as transmitter
    button_state.state = digitalRead(but_send);

    int n = a.length();
    char char_array[n + 1];
    strcpy(char_array, a.c_str());
    strcpy(button_state.mesaj, char_array);
    radio.write(&button_state, sizeof(button_state));  //Sending the data
    delay(5);

    radio.startListening();                            //This sets the module as receiver
    if (radio.available())
    {
      radio.read(&button_state1, sizeof(button_state1)); //Reading the data
      String final = "";
      if (button_state1.state == 0)      {
        ok = 1;

        sendText();
        for (int i = 0; i < strlen(button_state1.mesaj); i++)
        {
          final += String(button_state1.mesaj[i]);
        }
        Serial.println("Lavinia: " + final);
        button_state1.state = 1;
      }

    }

    if (digitalRead(del) == LOW && a[0] != '\0' ) {
      Serial.println("Deleted string");
      a = "\0";
      Serial.println(a);
    }

  }
  old_pres = rel_time;
  pres_time = millis();
  digitalWrite(led, HIGH);
  while (digitalRead(but) == LOW) {}
  rel_time = millis();
  digitalWrite(led, LOW);
  pres_len = rel_time - pres_time;
  space = pres_time - old_pres;
  if (pres_len > min_delay)
  {
    code += MakeString();
  }
  while ((millis() - rel_time) < (unit_delay * 3))
  {

    if (digitalRead(but) == LOW)
    {
      goto label;

    }

  }

  Morse_decod();
  delay(1000);

}

```

I believe the relevant part would be:

```
    int n = a.length();
    char char_array[n + 1];
    strcpy(char_array, a.c_str());
    strcpy(button_state.mesaj, char_array);
    radio.write(&button_state, sizeof(button_state));  //Sending the data
    delay(5);

```

where a is the message to be sent.

# Answer
(Too few characters in comments, so writing as answer instead)

It's a bit hard to figure out without having the setup here and I don't think I have any of the radio modules in my box.

What I think is happening is this.

It seems like the first code will not send anything unless it receives a message from the second code, because the radio.write is inside the radio.available if-block. But when it receives a message, the message to send back must be present, so you start by entering a message on Arduino1.

Then you enter a message on Arduino2. You press the button, it skips the while loop below the label. When you release the button, it will enter the while loop and send the message. For both versions, the message will be sent as soon as 'but' is released. but\_send is copied to the record that is sent, but the sending does not depend on the state of this button. You need an if statement that checks but\_send to do this. The effect is, that you can only send '.' or '-' because the message is sent right away, before you get to enter more dots or dashes.

Anyways, the message from Arduino2 is received by Arduino1. If the state field of the message is 1, the message is written to Serial. Then the message from Arduino1 is send to Arduino2. Since we are not pressing any buttons, the message from Arduino 2 is send again and again and again. The state field will be 0, because but\_send is not pressed, but the message is sent anyway. This triggers a new send on Arduino 1, because it receives something from Arduino 2 and gets into the radio.available part.

It seems like the messages will bounce back and forth. The only reason you don't see your Serial console filled with letters is that state is 0 for most of the messages, because you release btn\_send. But as long as you hold down btn\_send, it will set state=1 and print the message at the receiving end.

To prevent this, you should not call radio.write unless btn\_send is released. That is going from LOW to HIGH. To test this, have a variable called old\_btn\_send and do something like this: Initialize old\_btn\_send to HIGH in setup()

```
if (old_btn_send == LOW && digitalRead(btn_send) == HIGH {
    [do the sending thing]
}
old_btn_send = digitalRead(btn_send);

```

That is, you press btn\_send. We will not enter the if block, but old\_btn\_send will be LOW. When you release, the condition will be true, but only once, because old\_btn\_send will be HIGH after the if block.

Please note, that what I write is from reading the code and not doing any testing, so I might be completely wrong :)
> 1 votes

---
Tags: arduino-uno, communication, nrf24l01+
---


title: AT 09 BLE module not transmitting data

text:
# Question
Title: AT 09 BLE module not transmitting data
I have recently started working with the Arduino Pro Mini 5v/16Mhz and an AT 09 BLE module for an IoT project. I am controlling the BLE module using Software Serial and am leaving the hardware serial for for my laptop. I am using an app called "Serial Bluetooth Terminal" on Android to send/receive messages. The BLE module is able to receive messages and the "AT" command is also working. But when I try to get the BLE module to send a message, I get no response in the app. Any idea why this is happening and how can I resolve it?

My connections are:

> Laptop -\> Arduino UNO, MB-102(USB to breadboard power adapter)
> Arduino UNO(without IC) Rx -\> Pro mini Tx0
> Arduino UNO(without IC) Tx -\> Pro mini Rx1
> Arduino UNO(without IC) RESET -\> Pro mini Rst
> MB-102 5V -\> Pro Mini Pin RAW
> MB-102 GND -\> Pro Mini Pin GND
> Pro Mini Pin 2 -\> AT 09 TXD
> Pro Mini Pin 3 -\> AT 09 RXD
> Pro Mini Pin VCC -\> AT 09 VCC
> Pro Mini Pin GND -\> AT 09 GND

This is my code:

```
#include<SoftwareSerial.h>

SoftwareSerial ble(2, 3);

int statePin = 4;
char c;
void setup()
{
  Serial.begin(9600);
  ble.begin(9600);
  ble.print("AT\r\n");
  delay(100);
  while(!ble.available())
    Serial.print(".");
  while(ble.available())
  {
    Serial.print(char(ble.read()));
  }
}

void loop()
{
  while(ble.available() > 0)
  {
    c = char(ble.read());
    delay(10);
    Serial.print(c);
    ble.print(c);
  }
}

```

This is the first time I am posting here so please tell me if I missed out on any information.

# Answer
> 1 votes
So my AT 09 module is most likely faulty. I got a new HM 10 and connected it without changing any connections or code and it worked like a charm. I do not know the exact nature of the defect but since the chip was responding to commands, I think the PCB might have been damaged.

---
Tags: arduino-pro-mini, ble
---


# Question
Title: How to get version of Arduino board remotely
I have multiple Arduino WeMos D1 boards, with a mix of versions bought months apart. One of these boards is working but I need to update it and I am not sure if it is R1 or R2 (the pinouts are different). I do not have physical access to it (it is 200+ miles away in an area that is locked down) but I can connect through another device over WiFi.

It has the following included:

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

#include <WiFiUdp.h>
#include <ArduinoOTA.h>

```

So, I can even browse to a Webserver to run commands. How can I add to the code (or even replace it) to return a value that tells me which version the board is? According to this you can do it with an AT command, but I am not sure how to pass an AT command from the WebServer interface (or any other way).

EDIT: I guess I may have confused the issue with my phrasing. I can connect to the board and upload a new sketch (using OTA). My question is, can I put something in a new sketch to determine the board details and upload it. Once I get that, I can then put in a the actual sketch that I want.

# Answer
There's nothing you can do with your currently loaded sketch. The board can *only* do exactly what you have programmed it to do and nothing more.

* There *are* no "AT" commands. They only exist if you load the AT firmware instead of your own firmware
* You can't magically make your code do things it wasn't programmed to do1

However the only real differences between the two boards is the version of the ESP8266 module in use: ESP-12E vs ESP-12F, (and the *only* difference between those modules is the layout of the PCB antenna in order to achieve FCC certification) and the addition of some unpopulated serial and I2C pins.

~~Aside from that the only other differences are purely cosmetic or of no consequence to your software.~~

~~So it really doesn't matter which board you have or which you compile your code for.~~

---

1: Unless you can cause some buffer overflow and inject new code into memory to execute, but to do that you'd need to be a l33t h4x0r.

---

**Addendum:**

It appears they have two boards, named the same, with different pin arrangements (both sadly very stupidly designed, but there you are). All I can suggest is compile for one, install it, and see if it works. If it doesn't, then compile for the other and see if that works.

Or compile some special firmware that will probe what you have attached and work out what is attached where - then install and run that.
> 1 votes

---
Tags: esp8266webserver
---


title: I2S read() is which channel?

text:
# Question
Title: I2S read() is which channel?
The Arduino I2S reference describes the I2S standard and functions available with the standard I2S library, (Bizarrely it doesn't reference the existing `read()` function which is used in the examples but that is beside the point). There also exists an ArduinoSound library, however I have the same issue with this.

I would like to record audio from WM8731 connected up to Arduino. I am using an SAMD arduino part.

But, I have a tremendous issue with the `I2S.read()` function. The `I2S.read()` function only returns a singular value, however the I2S standard is *intrinsically* stereo.

This is particularly important for my project as I am only interested in the LEFT channel as the RIGHT channel is muted.

I would expect this to either:

* return a pair of values (i.e left /right) samples for that particular point in time , OR
* return a singular sample with extra information telling me which channel that is was retrieved from.

However it seems this is not the case. (Github)

I also assume that the I2S is buffered making it impossible to simply read the WS pin state, as I will probably be popping a sample from the buffer that was push into the buffer at some point in the past.

So, is it possible to know *which* channel the sample was returned from the `I2S.read()` function or does this mean that the library needs to be modified?

I am more interested in using the samd library as other libraries such as AudioLibrary is limited to 16-bit - I need 32-bit resolution.

# Answer
From my understanding it's just retrieving subsequent samples from the DMA buffer, which means you will alternately get left and right samples from each read. It would be more normal to use the `read(buffer, len)` variant to read two (or more) samples at once.

```
int16_t pair[2]; // change to int32_t for 32 bit samples
I2S.read(pair, sizeof(pair));

```
> 0 votes

---
Tags: library, audio
---


# Question
Title: Send packet of multiple sensors data to Bluetooth module
In my project I am using 3 sensors. I am sending a regular stream of sensors data to Bluetooth module but now I want to send data in form of packet (which may be 30 bytes or 40 bytes of size) in which first 10 bytes contain the first sensor data while next 10 bytes contain second sensor data and so on. But problem here is I am not finding something relevant to my approach. Can any one suggest me some link or some way to do this.

Thanks in advance.

# Answer
> 1 votes
There are many ways to transmit binary data over a byte-stream based interface like `Serial` (which is used by common bluetooth modules like the HC-05/HC-06). I will only describe one here.

First we need to define a start byte, which marks the start of a new packet. That can be any arbitrary value, for example `0xFF`. It is also possible to use a specific byte sequence as start marker. This start byte/sequence is what we send first when transmitting a packet.

Then we want to transmit the size of the following data. With small to normal packet sizes a single byte is enough here (giving room for up to 255 bytes).

Sometimes you might want to compute a CRC hash value to check for data corruption. That could also be send here. But unless you have a system, which really is loosing/corrupting data, you don't need it. I suggest you first try it without and check, if corrupted data is really a thing for your setup.

And then we are sending the actual data. How exactly you are doing this depends on how the data is stored in your code. Though you will use `Serial.write()` in some way. If you want a more specific answer in this regard, you need to include your code, so that we can see how you are storing your sensor data.

On the receiving side you would then wait for the start marker, read the size byte and then read bytes until you have received as many, as the size byte said. As you have multiple sensors, you could send the sensor data of each sensor in it's own packet. The data could then be formatted like: 1 byte sensor ID, X byte sensor data.

---
Tags: arduino-mega, programming, serial-data, android, data
---


title: Mass testing of Arduinos

text:
# Question
Title: Mass testing of Arduinos
I am using Arduino for an IoT class (40 students). I have set up a test program to check all sensors and actuators used in the class (we need to recycle for next semester). However, I would also like to check the Arduino's themselves (and also NodeMCU´s) in case some of the units have been broken. I have an idea of testing input/output of each pin to make sure its working - using LEDs and buttons, but if anyone has some ideas to improve testing, it would be great to hear from you.

# Answer
> 1 votes
Testing microcomputers is a very complicated task. In your case I would suggest writing some programs to do exactly what you are saying. Then let the students do the testing. When the class starts you have to teach them the basics, this will check the computers etc and also the test equipment on there benches. At the end of testing they will have knowledge of the basics they will need to continue with the class. You can also have the students do this at the end of the semester to get a head start on any problems.

# Answer
> 1 votes
A *complete* test would obviously be something fairly complex, and would probably require building some sort of rig. You can, however, perform a *minimal* test that checks for common failure modes, without connecting any extra hardware.

I assume the pin I/O stages are the easiest thing to break. You can then check that, when you read a pin that is set to `OUTPUT`, you get the value that the pin is supposed to be outputting. You can leverage the stray capacitances of floating pins to test them as inputs: the capacitance should make the pin “remember” its previous output value for some time, and that time should be really short if the internal pull-up is enabled.

The following program tests pins 2–13 and A0–A5 of an Uno. It checks that:

1. a pin set to `OUPUT` `LOW` reads `LOW`
2. a pin set to `OUPUT` `HIGH` reads `HIGH`
3. a pin switched from `OUPUT` `HIGH` to `INPUT` reads `HIGH`
4. a pin switched from `OUPUT` `LOW` to `INPUT` reads `LOW`
5. a pin switched from `OUPUT` `LOW` to `INPUT_PULLUP` reads `LOW`, then switches to `HIGH` less than a microsecond later

Pins 0 and 1 are not tested, as they are connected to the serial port. On the other hand, if you can upload a sketch, you know those pins work at least as RX/TX.

Note that the program uses direct port access, as the Arduino functions for accessing the pins are too slow for this kind of tests. If all works, the program prints “All tests passed.”. Otherwise specific error messages are printed, followed by “Some tests failed.”

```
#include <avr/cpufunc.h>
#include <util/delay.h>

int failures = 0;

static void log_failure(char port_name, const char * reason)
{
    failures++;
    Serial.print("FAIL: Port ");
    Serial.print(port_name);
    Serial.print(", read ");
    Serial.println(reason);
}

static inline __attribute__((always_inline))
void test_port(const char port_name, uint8_t mask,
    volatile uint8_t *pin, volatile uint8_t *ddr, volatile uint8_t *port)
{
    *port = 0;
    *ddr = mask;   // OUTPUT LOW
    _NOP();
    if ((*pin & mask) != 0)
        log_failure(port_name, "OUTPUT LOW");
    *port = mask;  // OUTPUT HIGH
    _NOP();
    if ((*pin & mask) != mask)
        log_failure(port_name, "OUTPUT HIGH");
    *ddr = 0;      // INPUT_PULLUP
    *port = 0;     // INPUT -> HIGH
    _NOP();
    if ((*pin & mask) != mask)
        log_failure(port_name, "INPUT HIGH");
    *ddr = mask;   // OUTPUT LOW
    *ddr = 0;      // INPUT -> LOW
    _NOP();
    if ((*pin & mask) != 0)
        log_failure(port_name, "INPUT LOW");
    *port = mask;  // INPUT_PULLUP
    _NOP();
    uint8_t r1 = *pin;
    _delay_us(1);
    uint8_t r2 = *pin;
    if ((r1 & mask) != 0 || (r2 & mask) != mask)
        log_failure(port_name, "INPUT_PULLUP");
}

void setup()
{
    Serial.begin(9600);
    TIMSK0 &= ~_BV(TOIE0);  // disable timer interrupt

    test_port('B', 0x3f, &PINB, &DDRB, &PORTB);  // PB0..PB5
    test_port('C', 0x3f, &PINC, &DDRC, &PORTC);  // PC0..PC5
    test_port('D', 0xfc, &PIND, &DDRD, &PORTD);  // PD2..PD7

    if (failures == 0)
        Serial.println("All tests passed.");
    else
        Serial.println("Some tests failed.");
}

void loop(){}

```

As an extension, analog inputs could be tested in a manner similar to test 5: if the analog sampling is done at the right time, you can get a reading that is somewhere mid-range.

# Answer
> 0 votes
I'd add a second Arduino to supply a HIGH and LOW signal to the Arduino being tested (to test the INPUT), and to verify that the tested Arduino can output HIGH and LOW. Testing inputs, outputs, and being able to upload you test sketch will catch the most common problems.

Testing the regulator would be my next thing, but that also depends on whether you're previous course was using the regulator.

# Answer
> 0 votes
When I make a new (Uno-like) board, I test for shorts and opens with sketch that blinks each pin in sequence. @Gerben's suggestion to test the inputs as well makes a lot of sense for your application. Plus the basic ability to power up (working barrel-connector input & voltage regulator, working USB connector and USB communication) would another test I'd make. I'd probably boards that have a socketed chip for my future purchases (if you're not already).

# Answer
> 0 votes
There are a number of open issues which need to be addressed in order to narrow the scope of this project to a manageable and reasonable effort. For instance:

1. Which Arduino (board and processor) are you using? Does the board power off a regulated USB 5 volt source? Or does it use a regulator which needs testing?
2. How many GPIO pins are there? Will they be used to drive, sense or both?
3. Are there any Analog pins? Do they need to be tested over a range or just a select voltage?
4. Are there any PWM outputs which need to be tested?

To simplify testing we might make some assumptions. For example:

1. If the GPIO aspect of a pin works any PWM feature for that pin may be assumed functional.
2. If a given voltage at a Analog Input pin results in a reasonable analog to digital conversion then all other reasonable voltages will result in the expected analog to digital conversion.

For testing many UUTs (Units Under Test), it is almost always better to build a fixture. This might be simple cables connected to another (carefully controlled) Arduino all the way to a bed-of-nails In Circuit Tester (ICT).

The "Make a Pogo Pin Test Jig" project at Adafruit addresses many of these concerns at a level that may be suitable to implement at the college level.

---
Tags: arduino-uno, testing
---


# Question
Title: Arduino EEPROM retains old data after flashing with a new program
I have a custom 5V 16Mhz Arduino Uno (a breadboard Uno of sorts) that runs the grbl firmware. After the initial flashing I can see all the settings (through the serial monitor) and everything works. However, if I make any changes to the firmware files and re-flash it, I can see that the old settings values have not been replaced with the new ones. I can only assume that these values are in the EEPROM and are not being erased on every re-flash cycle. I then tried the `eeprom_clear` program from Examples in the Arduino IDE and then re-flashed with the new firmware settings, after which I can see the new settings values.

I did some digging and found that the EESAVE fuse is responsible for this. However the Uno does have this fuse bit unprogrammed (set to 1). Why then am I able to see the old EEPROM settings and have to explicitly run an eeprom clear program before re-flashing with the updated firmware?

# Answer
> 2 votes
Flash isn't EEPROM. When you reprogram the flash it doesn't touch the EEPROM.

It's controlled by the `-U...` flag to `avrdude`:

```
avrdude ... -Uflash:w:<hex file>

```

If you want to set the EEPROM to something specific you can use `avrdude` to program an EEPROM file if the bootloader supports it (not sure it does, so you may need a programmer for it):

```
avrdude ... -Ueeprom:w:<hex file>

```

# Answer
> 1 votes
The -e parameter in avrdude should only erase the EEPROM if the fuse bit

Preserve EEPROM memory through the Chip Erase cycle; \[EESAVE=0\]

is not set. However it appears it is not possible to SET this fuse bit. (at least not with AVRDUDESS.

---
Tags: arduino-uno, avr, eeprom, flash
---


# Question
Title: How to program and arduino UNO via NodeMCU ESP8266?
I don't have my USB type A cable to program my UNO, I would like to program it via a NodeMCU ESP8266.

Maybe with the TX and Rx pins, I've seen people program certain versions of ESP with a UNO board.

How do I do this and is it possible?

# Answer
The UNO's USB connection is little more than a USB to UART converter. The NodeMCU's USB connection is *also* little more than a USB to UART converter.

With a little *jiggery pokery* (yes, that's a technical term) you can replace one with the other.

By keeping the NodeMCU in RESET mode (tie the EN pin low, or hold the RESET button) you can use the TX and RX pins as the output to the onboard USB to UART converter to connect to the TX and RX pins of the Arduino.

The tricky part is getting the Arduino to reset at the right time: you have to press the Arduino's RESET button at just the right time. Normally this is done by a small capacitor between the DTR signal of the USB to UART converter and the RESET pin, but you don't have access to the DTR signal, so you will have to do it manually. Timing here is everything. Press upload, and *just as AVRDude starts to execute* you press RESET. Having verbose compilation turned on in the IDE can help.

It may take a few attempts to get it right.
> 1 votes

---
Tags: arduino-uno, nodemcu
---


# Question
Title: Is it possible to program Arduino in transpiled JavaScript?
Coming from JS, I find it very difficult to program Arduino in C++ *(not even knowing which version or what features are supported)*, being bound to the `loop` and `delay`, not being able to (easily) use anonymous functions in parameters or async code.

I know JS isn't natively supported by Arduino, but I know languages can be transpiled.

I have seen many solutions, so just to pick few:
JohnnyFive J5, which runs via cable on a host PC,
NectarJS with their `arduino-uno` target,
or andrei-markeev/ts2c which converts ES3 to C89.

Each of them come with their own limitations and it's very difficult to find the right without prior experience with IoT. Did anyone walk this path already and found a viable solution?

# Answer
Even if such a transpiler exists (which I don‘t know) you will still have to deal with the `loop` structure and the fact that you should avoid using `delay`s. On a microcontroller you have to forget about things like multithreading and even dynamic memory allocation should be used carefully. Most of those things that make a programmer‘s life easy on bigger systems are usually paid with ram or cpu power, but on a microcontroller with some kB RAM there are only few resources to pay with.

So my recommendation is to learn C++ instead of looking for ways to convert code from another language, which will probably introduce its own problems. You‘ll soon find yourself one layer below and there are exciting things that higher languages hide from you.
> 2 votes

# Answer
Why don't you just start with a microcontroller that supports Javascript?

I find the Adafruit Circuit Playground Express quite fun to work with. You can still connect sensors and other hardware, the same as you can do with Arduino. It also has a bunch of sensors built-in.

You can try it out right now without owning a hardware board at adafruit.makecode.com. Click the Javascript tab on the top of the page.

Using a JS\>Arduino transpiler will probably cause a lot of headache, since it often won't do what you expect it to do.
> 0 votes

# Answer
andrei-markeev/ts2c JavaScript/TypeScript to C transpiler looks promising.

I'll probably give it a go tonight.

### According to the github page:

Produces readable C89 code from JS/TS code.

For example, this JavaScript:

```
console.log("Hello world!");

```

transpiles to the following C code:

```
#include <stdio.h>

int main() {
    printf("Hello world!\n");
    return 0;
}

```

src: https://github.com/andrei-markeev/ts2c
> 0 votes

---
Tags: arduino-micro, teensy
---


# Question
Title: Error in I2C Communication Between Arduino and Raspberry Pi
The code below sends data to Raspberry Pi every 20 millisecond. The code works fine but sometimes python throws an error. Why this is happening? Should I give more time between `writeData`?

**Error:**

```
> Traceback (most recent call last):   File "rpi-I2C.py", line 33, in
> <module>
> writeData("360")   File "rpi-I2C.py", line 12, in writeData
> bus.write_i2c_block_data(address,0x00,byteValue) OSError: [Errno 121] Remote I/O error

```

**Python code:**

```
import smbus
import time
# for RPI version 1, use bus = smbus.SMBus(0)
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

#http://www.raspberry-projects.com/pi/programming-in-python/i2c-programming-in-python/using-the-i2c-interface-2
def writeData(value):
    byteValue = StringToBytes(value)
    bus.write_i2c_block_data(address,0x00,byteValue)
    #first byte is 0=command byte.. just is.
    return -1

def StringToBytes(val):
        retVal = []
        for c in val:
                retVal.append(ord(c))
        return retVal

while True:
    print("sending test")
    writeData("left")
    time.sleep(0.02)

    #print('Sending OPEN-00-00');
    writeData("right")
    time.sleep(0.02)

    #print('Sending WIN-12-200');
    writeData("360")
    time.sleep(0.02)

```

**Arduino code**:

```
#include <Wire.h>
#define SLAVE_ADDRESS 0x04

volatile boolean receiveFlag = false;
char temp[32];
String command;

void setup() {
  Wire.begin(SLAVE_ADDRESS);
  // define callbacks for i2c communication
  Wire.onReceive(receiveEvent);
  Serial.begin(115200);
  Serial.println("Ready!");
}

void loop() {
  if (receiveFlag == true) {
    Serial.println(temp);
    receiveFlag = false;
  }
}

void receiveEvent(int howMany) {
  for (int i = 0; i < howMany; i++) {
    temp[i] = Wire.read();
    temp[i + 1] = '\0';  //add null after ea. char
  }

  //RPi first byte is cmd byte so shift everything to the left 1 pos so temp contains our string
  for (int i = 0; i < howMany; ++i)
    temp[i] = temp[i + 1];
    receiveFlag = true;
  }

```

# Answer
> 1 votes
A RPI uses 3.3v logic while an arduino uses 5v logic you can use a logic converter but by now it's probly to late and maybe your arduino or RPI is broken (***Sorry!***)

---
Tags: arduino-uno, arduino-mega, i2c, communication, raspberrypi
---


# Question
Title: LED Blink in assembly with timer1 output compare interrupt not working
I was trying to have some fun with avr-assembly on my arduino and I tried the following codes to blink my LED

first I tried the ISR approach and when It didn't work I tried the CTC mode one, both codes are listed respectively. on the first one the LED lightsup and stay that way (no blinking) on the second one it just stays off

one more thing to note is on trying to load OCR1AL first The led would blink nicely if my hand got near PORTD pins for some reason,

I guessed it's some grounding problem and It's fixed when I pulled high all PORTD pins and it disappeared completely when I figured out that I need to load (the high byte) OCR1AH first

```
.nolist
.include "m328Pdef.inc"
.list

.org    0x0000
jmp     Init

.org    0x0016
jmp     TIMER1_COMPA

.EQU    LED_PIN = PB1

Init:
    ;ldi    r16, 255
    ;out        DDRD, r16
    ;out    PORTD, r16

    ;First configure The led pin as output and initilize it to high
    sbi     DDRB, LED_PIN
    sbi     PORTB, LED_PIN

    ;Second Enable Global Interrupts
    sei

    ;Enable the Output compare Interrupt in the TIMSK1 Register
    ldi     r16, 0b00000010
    sts     TIMSK1, r16

    ; Reset the TCCR1A
    ldi     r16, 0b00000000
    sts     TCCR1A, r16

    ; Set the prescalar to 256 in the Timer Control 1B register
    ldi     r16, 0b00000111
    sts     TCCR1B, r16

    ;Now load the value for Output compare register 31250 or   01111011 00100000  or 15625 =  00111101 00001001
    ldi     r16, 0b00111101
    ldi     r17, 0b00001001
    sts     OCR1AH, r16
    sts     OCR1AL, r17

LOOP:

    rjmp    LOOP

TIMER1_COMPA:
    ;First Reset the coutner
    ldi     r16, 0
    sts     TCNT1H, r16
    sts     TCNT1L, r16

    ;Second Toggle the Pin (LED) state
    sbi     PINB, LED_PIN

    reti

```

**CTC:**

```
.nolist
.include "m328Pdef.inc"
.list

.org    0x0000
jmp     Init

.org    0x0016
jmp     TIMER1_COMPA

.EQU    LED_PIN = PB1

Init:
    ;ldi    r16, 255
    ;out        DDRD, r16
    ;out    PORTD, r16

    ;First configure The led pin as output and initilize it to high
    sbi     DDRB, LED_PIN
    sbi     PORTB, LED_PIN

    ;Second Enable Global Interrupts
    sei

    ;Enable the Output compare Interrupt in the TIMSK1 Register
    ldi     r16, 0b00000010
    sts     TIMSK1, r16

    ; Reset the TCCR1A
    ldi     r16, 0b01000000
    sts     TCCR1A, r16

    ; Set the prescalar to 256 in the Timer Control 1 registers
    ldi     r16, 0b00001111
    sts     TCCR1B, r16

    ;Now load the value for Output compare register 31250 or   01111011 00100000  or 15625 =  00111101 00001001
    ldi     r16, 0b00111101
    ldi     r17, 0b00001001
    sts     OCR1AH, r16
    sts     OCR1AL, r17

LOOP:
    rjmp    LOOP

TIMER1_COMPA:
    ;First Reset the coutner
    ;ldi    r16, 0
    ;sts    TCNT1H, r16
    ;sts    TCNT1L, r16

    ;;Second Toggle the Pin (LED) state
    ;sbi        PINB, LED_PIN

    reti

```

# Answer
> 3 votes
I am not set up to test your code right now, perhaps later. But:

```
    ; Set the prescalar to 256 in the Timer Control 1B register
    ldi     r16, 0b00000111
    sts     TCCR1B, r16

```

When set to ones, the low order three bits of TCCR1B, select an external clock source at the T1 pin, for clocking on a rising edge. Probably what's happening is that when you finger is near enough the T1 pin you are capacitively coupling mains frequency to it causing it to tick.

/256 prescaler would have `100` in the lower three bits.

If I manage to get a proper environment up to test your code, I'll look into it a bit more thoroughly.

---
Tags: arduino-uno, atmega328, assembly
---


title: How to test custom cables?

text:
# Question
Title: How to test custom cables?
I'm trying to make a cable checker to help me make custom cables for my computer. I'm thinking I plug the cable ends into sockets on the device, then the Arduino checks between different pins to make sure that no wires are in the wrong spot or unplugged.

So I'm thinking it runs through like this:

I plug the cable into connectors on the device. The Arduino has the PSU pinouts saved. Pin 1 represents one end of the cable, pin 2 represents the opposite end. Same with 3-4/5-6 etc. If the cable is assembled correctly, it should act as a connection between pins 1-2, pins 3-4, 5-6 etc.

tests pin 1 - 2 to see if they're connected, if yes, light up a green LED, if not, light up a red LED

tests pin 3 - 4, does the same thing

Repeats this for every wire in the cable

Am I on the right track? How would I do this? I've seen people talking about pullup resistors but I'm also seeing people say that shorting can damage the board

# Answer
> 2 votes
The scope of your question is too wide for a simple answer so let us constrain it to slow signals (audio frequencies or less) over short cables (not more than several meters) in a electrically clean environment (such as found in most homes).

That said, it is likely most looking for similar solutions reading your question will have different specific requirements. So to make this question and answer useful to others let us consider the most generic, economical and Arduino based solution.

1. Most cables worth automatically testing will have far more individual connections than common Arduino boards, such as the Arduino Uno, have GPIO pins. Consider using a GPIO expander or multiple Arduinos which communicate with each other to coordinate efforts.
2. When testing a cable that will be used for low frequencies, short distance and low immunity to noise it is likely the only faults that are of concern are OPENS and SHORTS.
3. As this design uses GPIO pins we have the following options at any given GPIO pin: Drive High, Drive Low and Input With Pull Ups.
4. Build a cable test rig where one end (the near end) of the cable under test is connected to GPIO pins designated as the driver side and the other end of the cable under test (the far end) is connected to GPIO pins designated as the sensing side.
5. For a SHORTS and OPENS test set all the sensing and driving GPIO pins to Input With Pull Ups. Verify that all sensing GPIO pins report a 1. Next change one and only one of the driver GPIO pins to an output and send a 0. Record that state of all sensing GPIO pins. Return the driver GPIO pin to Input with NO PULL UPS and repeat these steps for the next GPIO driver pin.
6. If this is a STRAIGHT THROUGH cable only 1 sensing GPIO pin should report a 0 in each testing pattern recorded. If more than 1 sensing GPIO pin reports a 0 then there is a short between the 0 reporting pins. If none of the GPIO pins reports a 0 then there is an open for that GPIO pin.
7. Use the same test for cables containing intentional SHORTS (perhaps multiple ground pins are shorted together) expecting to see the associated GPIO pins to all change to 0 at the same time.
8. For even more complex cables containing loop backs at both ends consider only the "GPIO pin set to an output sending 0" as the driver and record the state of ALL OTHER GPIO pins as they are now all possible outputs.

---
Tags: arduino-uno, digital, pull-up
---


# Question
Title: How can I use attached interrupt on my project?
Hi I have a coinslot project and connected with a fingerprint sensor it was stated in the ardiuno forum that it will work on pin 2 and 3 , but it is already used pins of the finger print sensor .

Coinslot signal is in pin 9 and the in2,3 is for the rx and tx of the fingerprint sensor.

# Answer
> 3 votes
If you can't rearrange the pins like Majenko suggests in the their comment, something you can do is is use pin change interrupts rather than the regular "external" interrupts. On the UNO, these are available on all of the "digital" capable pins, which also includes most of the "analog" pins if you have an SMT UNO, or all of them if you have a DIP model.

NiceHood's PinChangeInterrupt library is modeled after the regular `attachInterrupt` function, so it should be familiar looking to you. It's in the library manager; you don't need to get it from github.

NOTE: The O.P. opened a another question which seems to be this same thing, only with different context and specific code. There I've given **more details on what's outlined above but in relation to that that specific code in an answer there**.

---
Tags: arduino-uno
---


# Question
Title: Automate capturing photograph on ESP32-CAM
I want to capture photographs from the ESP32 camera, but not doing it manually. Specifically, when a signal is sent from a sensor, I want ESP32 to understand that, and start taking photographs **automatically** for some seconds. The main problem, is the automation. I have searched on the web a lot, but can't find any answers. I am not expecting answers with code -since this is difficult- rather than some sites that provide solution to my problem. Thank you.

# Answer
> 2 votes
Please have a look https://github.com/Yurik72/ESPHap/tree/master/examples/ESPHAPCamera The project has different things, but definetelly doing what you asked, captures photo by external event, command...

---
Tags: esp32
---


# Question
Title: Decode rf remote signals with ESP32 or node MCU?
I'm trying to decide my rf remote signals using ESP32 or node MCU. I have tried with Arduino and was successful but for some reason it is not working on either ESP32 or node MCU even using the same GPIO2 pin can anyone please tell me why both the boards are not able to decode the signal. I'm using the rc-switch library to decode and a 433Mhz transmitter reciever combo from amazon

RCSwitch mySwitch = RCSwitch();

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
}

void loop() {
  if (mySwitch.available()) {
    output(mySwitch.getReceivedValue(), mySwitch.getReceivedBitlength(), mySwitch.getReceivedDelay(), mySwitch.getReceivedRawdata(),mySwitch.getReceivedProtocol());
    mySwitch.resetAvailable();
  }
}```

# Answer
For ESP32, you should provide real GPIO number. For instance: mySwitch.enableReceive(13);

And without deep explanation, believe that it properly works with GPIO 13 and 27.
Details you can find by google...
> 1 votes

---
Tags: nodemcu, esp32, wireless, rf, signal-processing
---


# Question
Title: Is there a way to make the RESET pin work in the inverse?
Is there a way for me to have this work the opposite way?

I have one cable with an alligator clip hooked up to the reset pin and another hooked up to ground.

When I clip them both together, the board resets.

However, I would like for this to work in the opposite way such that they’re already clipped together and when you detach the cables, the board resets.

# Answer
My personal preference would be to attach a NOT gate to the RESET pin. This can be constructed very simply from a single NPN transistor (or N-channel MOSFET) and a resistor.

simulate this circuit – Schematic created using CircuitLab

With the wire disconnected R1 turns on Q1 which pulls the RESET pin LOW. With the wire connected Q1 is turned off, allowing RESET to be pulled back up by the pullup resistor that's built into the Arduino.

This method also won't interfere with the programming reset action of the Arduino.
> 4 votes

# Answer
The easiest way to do that would be to use an external pulldown resistor (a resistor from the reset pin to ground) and connect to Vcc (5V on the Nano) via your alligator cables.

As long as the alligator cables are connected, the reset pin is held HIGH through them. When you disconnect them, the pulldown resistor pulls the reset pin to LOW. That holds the Nano in reset until you again connect the alligator clips.

If you want the Nano to reset and then directly work again without the alligator clips reconnected, it gets more difficult. One way I can think of is building a monostable vibrator circuit, which gets in the excited state, when your alligator clips are disconnected, resets the Arduino and then goes back into the stable stable, letting the Arduino execute its code. Though that is more an electrical question, than an Arduino one.
> 1 votes

---
Tags: arduino-nano, reset
---


title: 2 way switch with Arduino?

text:
# Question
Title: 2 way switch with Arduino?
Hey I'm working on a home automation system where I can replace one of my 2 way switches to an Arduino Or node MCU controlled one but I want to avoid normal relays because as of what I know they can be unreliable and tend to fail. So is there any way I can replace my switch with an Arduino controlled switch and also I cannot use solid state relay as it has only two terminals and it cannot replace my two way switch.

# Answer
Like Gil said, it sounds like what you are calling a two-way switch is actually a three-way switch. These are typically wired like this (but not always, make sure to double check!):

To replace one of the two switches with a relay, you can simply connect a SPDT relay with the load/hot wire (depending on which side you're adding the relay from) to the common contact, and then the two traveler wires to the normally open and normally closed contacts. This effectively takes your existing wiring and directly swaps in a relay -- after all, the relay is literally a switch, just electrically activated instead of manually.

I can't speak to the reliability or lack thereof of a specific model of relay, but a normal power relay is more than adequate for home automation in almost all cases; you don't need anything too fancy. Yes, there will be a mechanical point of failure, but they are typically rated for 100,000+ actuations minimum on a decent relay (like this one from SparkFun, for example) which will take quite some time to reach. Avoid the super cheap relays both for safety and reliability, and you should be fine.
> 1 votes

# Answer
I have not had good luck with these relays, the modules themselves are OK I just solder in a new relay. Try looking for: "solid state 3 way switch" I found this on my first try. DPST 1NO 1NC 8Amp Power Relay Module. It was labeled "OONO". Consider what happens when the power fails in just the controls, light circuit or both. What will you have then, and then when the power comes back on. I use larger relays and have not have any failures, they are rated at 20A 277V with 24VDC coile.
> 0 votes

---
Tags: arduino-uno, nodemcu, relay, switch, home-automation
---


# Question
Title: does EEPROM reset itself when a new code is uploaded?
I have a Nodemcu with which i'm doing a project. So whenever there is a power loss i want values of some of the variables to not be reset, because of that im trying to store the values in EEPROM of the nodemcu. But the problem is i want to know if the EEPROM will get reset when a new code is uploaded and also since the nodemcu stores wifi credentials in the EEPROM i dont want to accedentally select an EEPROM address in which the wifi credentials are stored and cause a problem. Can anyone tell me the safe EEPROM addresses to use and also if EEPROM will get rest if a new code is uploaded?

# Answer
> 1 votes
The esp family chips do not have EEPROM. Instead they just dedicate a small section of flash to pretend to be EEPROM.

That flash section, depending on the core version, is either a dedicated EEPROM partition, or a dedicated key in the nvram partition. Either way it's separate to the wi-fi credentials, which are stored in their own key in the nvram partition.

EEPROM can be erased when you upload code if the partition layout changes. It's less likely to be erased if it's a newer version of the core where it's stored in the nvram.

For safety, don't change the partition size, and ideally use ArduinoOTA which will never change the partitions or erase the nvram.

---
Tags: power, nodemcu, eeprom, variables, system-design
---


title: I2C pull up resistors and an I2C MUX

text:
# Question
Title: I2C pull up resistors and an I2C MUX
I have a rig with 5 light sensors on an I2C mux and I am wondering if I need only 1 pull-up resister set for the whole bus or one on each branch from the mux?

Or should I remove all the pull-ups from the branches and leave the one on the mux?

My issue is that the Arduino softlocks after 5-60 min of running, and it always softlocks on a read lux call.

# Answer
> 2 votes
From what I can tell, the I2C bus multiplexer itself receives and re-transmits on what amounts to a completely separate bus. So, each bus would need its own pull-up resistors. That said, the board you've linked that breaks out the multiplexer chip has pull-up resistors on each bus that it's providing:

The breakout also has pull-ups on the bus going to the multiplexor itself:

Beyond that, the ambient light sensor breakout seems to provide its own 4.7K pull-ups. AVR-based Arduinos (and probably others) also enable their own, admittedly weak, pull-ups in the guts of the wire library.

It seems you should not necessarily need to add any additional pull-up resistors of your own to what is already on the buses.

---

With regard to the O.P. comment given below concerned about too many pull-up resistors.

At some point probably below (perhaps far below) 500 ohms some devices may have trouble sinking enough current to create a LOW. The AVR wouldn't have a problem with 500 ohms for example.

The ATMega328P datasheet (along with most other AVR datasheets) will tell you that the internal pullup value is between 20K-50K. If you're concerned about too-many-parallel-resistors/too-many-current-paths/too-little-total-resistence, you can take the 20K figure along with multiplexer breakout's 4.7K figure, to calculate `pow(1 / 20e3 + 1 / 4.7e3, -1)`, for about 3.8K, which should be fine. If you do the same calculation on the multiplexor's individual bus resistor 4.7k and the ambient light sensor breakout's own 4.7k resistor, you get 2.35 k (half), which is also probably fine. If anything both of these total figures can be made smaller (by adding yet *another* parallel resistor) for longer buses and at higher frequencies. If you're worried about these figures you can lower the I2C clock rate. You can also examine the edges of your signal with a scope. Also if you really want to dig into this stuff, you read in the official I2C manual. But, really I think what you have is probably fine.

---
Tags: i2c, wires, pull-up
---


# Question
Title: Getting all data of my JSON object from Serial.read() at once
I'm new to Arduino and I'm building a project that fetches data from a website (using ESP8266) and then transfers them to my `Arduino UNO` via serial port.

Data coming from ESP8266 every 20s - `[{"x": 0,"y": 0,"rgb": [255, 200, 174]},{"x": 1,"y": 0,"rgb": [255, 200, 174]},{"x": 2,"y": 0,"rgb": [255, 200, 174]}]`

But when I print the data like this

```

void loop() {

  if (Serial.available()) {
    Serial.write(Serial.read()); // This line prints only one character out of whole string

    data =  Serial.read(); // so this doesn't work

    DeserializationError error = deserializeJson(response, data);
    if (error) {
      Serial.print(F("deserializeJson() failed: "));
      Serial.println(error.f_str());
      return;
    }
    for (JsonObject elem : response.as<JsonArray>()) {
      int x = elem["x"]; // 2, 2, 2
      int y = elem["y"]; // 2, 2, 2
      JsonArray rgb = elem["rgb"];

      int rgb_0 = rgb[0]; // 255, 255, 255
      int rgb_1 = rgb[1]; // 255, 255, 255
      int rgb_2 = rgb[2]; // 255, 255, 255
      //Serial.print(x);
    }
  }
  delay(1000);   //then it waits 1 second and goes from the start
}

```

How can I make it to get the whole string and save it into a variable?

Thanks, much for answering.

# Answer
I was going to put this as a comment, but maybe it belongs as an answer:

For what it's worth, ArduinoJSON seems to be able to deserialize directly from a stream, i.e. `Serial`, which may obviate the question *as asked*. Presumably it knows where to stop deserializing, because it knows when it has received an entire JSON object; being a proper JSON parser, it can probably work this out better than you can without, you know, writing a JSON parser.

The following was just thrown together, now the author is here you should probably just follow their direction, but here's the code anyway:

```
#include <ArduinoJson.h>

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
  Serial.setTimeout(30000);
}

void print_transmission_counter( {
    static unsigned long received_object_counter;
    Serial.println(F("\n\n\n\n"));
    for (int i = 0; i < 30; ++i) {
        Serial.write('-');
    }
    Serial.write('[');
    Serial.print(received_object_counter++);
    Serial.println(']');
}

void loop() {
    static StaticJsonDocument<256> json_doc;
    static bool led_state;

    print_transmission_counter();

    const auto deser_err = deserializeJson(json_doc, Serial);
    if (deser_err) {
        Serial.print(F("Failed to deserialize, reason: \""));
        Serial.print(deser_err.c_str());
        Serial.println('"');
    } else  {
        Serial.print(F("Recevied valid json document with "));
        Serial.print(json_doc.size());
        Serial.println(F(" elements."));
        Serial.println(F("Pretty printed back at you:"));
        serializeJsonPretty(json_doc, Serial);
        Serial.println();
    }

    // Just give some visual indication that the loop is progressing
    led_state = !led_state;
    digitalWrite(LED_BUILTIN, led_state);
}

//  vim:sw=2:ts=2:et:nowrap:ft=cpp:

```
> 6 votes

---
Tags: arduino-uno, serial, json
---


title: Arduino on/off PWM

text:
# Question
Title: Arduino on/off PWM
When I turn on DC motor with a button I get a a fixed PWM value that goes into a loop till button state changes.

What should I change that I could change X value with potentiometer in a loop?

```
int X = A0;
int SW = 2;
int Xval=5;
int SWval;
int buttonNew;
int buttonOld = 1;
int buttonState= 1;
int engine = 6;

void setup() { // This executes once
  Serial.begin(9600);
  pinMode(X, INPUT);
  pinMode(SW, INPUT_PULLUP);
}

void loop() { // This loops continuously
  Xval = analogRead(X);
  buttonNew = digitalRead(SW);

  if (buttonOld == 0 && buttonNew == 1) {
    if (buttonState == 0) {
      analogWrite(engine, Xval);
      buttonState = 1;
    }
    else {
      digitalWrite(engine, LOW);
      buttonState = 0;
    }
  }

  buttonOld = buttonNew;
  delay(1);
  Serial.print("button");
  Serial.print(SWval);
  Serial.print("          X=");
  Serial.println(Xval);
}

```

# Answer
Move the analogWrite out of the button-state-change code, and it will update the PWM continually, instead of only when the button is pressed.

See the code below.

I also change the variable name `buttonState` to `motorState`, as it indicates the state of the motor (On/Off). And I inverted it, so `1` means the motor is ON.

The other thing I did was to increase the delay to 10ms, so you don't get any issues with switch-bounce.

```
int X = A0;
int SW = 2;
int Xval=5;
int SWval;
int buttonNew;
int buttonOld = 1;
int motorState= 0;//indicates whether the motor is on/off
int engine = 6;

void setup() { // This executes once
  Serial.begin(9600);
  pinMode(X, INPUT);
  pinMode(SW, INPUT_PULLUP);
}

void loop() { // This loops continuously
  buttonNew = digitalRead(SW);
  if (buttonOld == 0 && buttonNew == 1) {
    if (motorState == 0) {
      motorState = 1;
    }
    else {
      motorState = 0;
    }
  }
  buttonOld = buttonNew;

  if (motorState == 1) {
    Xval = analogRead(X);
    analogWrite(engine, Xval);
  }
  else {
    digitalWrite(engine, LOW);
  }

  delay(10);
  Serial.print("button");
  Serial.print(SWval);
  Serial.print("          X=");
  Serial.println(Xval);
}

```
> 1 votes

---
Tags: pwm
---


# Question
Title: Connecting LEDs and push buttons 12 feet away from Arduino UNO
I have a PCB (let's call it remote PCB) on which I have 4 LEDs and 4 buttons mounted. The remote PCB is far away from my desk (about 12 feet away). The LEDs are used to indicate the status and the buttons are for various state inputs.

All of them are connected to UNO directly.

1. I am planning to use a 10 pin IDC connector and IDC ribbon cable for the same.
2. THe LEDs' current is about 2 mA each (white LEDs)
3. The push buttons will make a ground connection when pressed, else the internal pull-up of the UNO will keep the GPIO at a high level.
4. I have put a capacitor of 10 nF across the switch to address denounce.
5. I have a series resistor of 1-kilo ohm for all four Switches on the remote PCB

I would like to know if this is okay? Will there be any problem due to the length. The LEDs are for indication and won't blink faster than 200 ms at any point in time. They will be used to indicate status which is very slow signals. Thanks in Advance!

# Answer
That is a big no-no. You are adding extremely long antennas to the Arduino asking for problems. At a minimum on the inputs add a 10K series resistor at the Arduino pins. My preference would be to put the capacitors at the arduino pins to help decouple noise etc as well as the pull up resistors on the wire side of the 10K resistors. Use a buffer of some type for the LEDs, a transistor would work. This may work but for how long and how many processors can you destroy over time.
> 1 votes

---
Tags: arduino-uno, led, wires, switch
---


# Question
Title: How to get current WiFi signal strength?
I have a LCD display where in I'm displaying a WiFi signal logo. I want to reduce the number of bars on the logo, indicating that the signal strength is dropping. I got the reducing bars on the LCD completed, I still have to find out the actual signal strength.

How do I find the signal strength of the connected network with ESP8266 based NodeMCU?

# Answer
> 7 votes
You use `WiFi.RSSI()`:

> # RSSI
>
> Return the signal strength of Wi-Fi network, that is formally called Received Signal Strength Indication (RSSI).
>
> ```
> WiFi.RSSI()
>
> ```
>
> Signal strength value is provided in dBm. The type of returned value is int32\_t.
>
> Example code:
>
> ```
> Serial.printf("RSSI: %d dBm\n", WiFi.RSSI());
>
> ```
>
> Example output:
>
> ```
> RSSI: -68 dBm
>
> ```

---
Tags: wifi, nodemcu
---


# Question
Title: Atmega328p with arduino without the board
Perhaps this is a beginners question and I am not sure. I currently have a custom made circuit with an atmega328p chip connected to an mpu6050. However, when I program in Arduino I am not sure what to do? I can't pick a "board" as the atmega328p doesn't belong to a board? (from what I'm aware at least)

How in Arduino do I choose to program for my atmega328p chip? Without having to pick a board such as Arduino Uno etc. As I don't have any board for this. Or does the atmega328p chip always belong to a certain board?

I have a fully working circuit with a cyrstal (16MHz), battery sources, atmega328p etc. But I don't know how to program it with Arduino? I can program it in C, but would like to use Arduino due to certain libraries.

# Answer
> 0 votes
The board option is actually selecting a variant out of the installed cores (which provide the basic Arduino framework for a group of boards/chips). Each core can support multiple variants/boards/chips and can give each of them individual lists of options. There certainly also is a core, which supports the Atmega328p with all needed config options (like the frequency setting). You just need to install it from the boards manager.

Though, since you use a 16MHz crystal just like the Uno/Nano, you could just select the Uno or Nano as board. Neither the Arduino IDE, nor the Atmega328p can know, that the Atmega is actually a standalone one and not mounted on an Arduino board. So you can just use that board when you keep the config options inherent to an Arduino Uno/Nano (frequency setting and pin mapping mainly).

---
Tags: programming, atmega328, atmel
---


title: Serial.println won't format DEC

text:
# Question
Title: Serial.println won't format DEC
This is weirding me out. So I wrote to the EEPROM and I would like to read from the address and format it in Base 10, err... Decimal. The normal number thingy that's not ASCII. But it keeps returning ASCII values when I write:

`Serial.println(EEPROM.read(address), DEC)`.

Wait for the weird part, when I format in other bases like, say BIN, or OCT, it outputs in the correct base. Please help. Here's the full snippet of the tiny program.

```
#include <EEPROM.h>
int addr = 0;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available() > 0){
    int rc = Serial.read();
    EEPROM.write(addr, rc);
    Serial.println(EEPROM.read(addr), DEC);
  }

}

```

# Answer
> 1 votes
I finally figured it out. Apparently, when I call Serial.read() and assign it to "int rc", It sort of converts the actual ASCII values into integer. So reading the number 3 from the Serial monitor and assigning it to rc stores 51 in rc. So the trick I found to that was to use

```
int rc = Serial.read()-'0'

```

That way, I am storing 51-48 which is, 3 (Since 48 is the ASCII value for 0).

Thanks.

---
Tags: arduino-uno, serial, eeprom
---


# Question
Title: Repeatedly checking multiple "if" statements
This code is part of a long code for a robot that is both obstacle-avoiding and remote control. I am trying to get the code to check both "if" statements when the code number FF807F is received from an IR remote. When the code number is received the program checks both "if" statements and carries out the one that is true. I want the program, once it has finished carrying out the true "if statement, to check both "if" statements again.

```
void loop () {
if (My_Decoder.value==0xFF807F){
 if (cm<6)
 {
  motor_stop();
  digitalWrite(backlights, HIGH);
  delay(2000);
  motor_backward();
  digitalWrite(backlights, HIGH);
  Serial.println("backward");
  delay(2000);
  motor_stop();
  digitalWrite(backlights, HIGH);
  delay(900);
  motor_right();
  digitalWrite(backlights, LOW);
  Serial.println("right");
  delay(1000);
}
if (cm>6)
 {
  motor_forward();
  digitalWrite(backlights, LOW);
  Serial.println("forward");
}
}
}

```

# Answer
I am going to assume you don't want to include `cm == 6` which is why you have both cases. I would consider using a while loop instead of a singular 'if' statement in order to continuously check if those buttons are being pressed or not (`while (cm<6){do this stuff}`). Otherwise, it will check once and never check again.

Instead it will jump down to the next 'if' statement, it will fail and then jump to the top of the loop where it will check for the code 0xFF807F. Let me know how it goes!
> 2 votes

# Answer
Your are missing the case when "cm == 6".

You don't need to do two "if"; one "if-else" is enough because is either one or the other.

You don't have/need to check twice; "cm" doesn't change inside the "if". But i you want, use functions:

```
void loop () {
  if (My_Decoder.value == 0xFF807F) {
    doSomething();
    doSomething();
  }
}

void doSomething() {
  if (cm < 6) {
    motor_stop();
    digitalWrite(backlights, HIGH);
    // ...
    delay(1000);
  } else {
    motor_forward();
    digitalWrite(backlights, LOW);
    Serial.println("forward");
  }
}

```
> 1 votes

# Answer
```
if (My_Decoder.value == 0xFF807F) {
if (cm<6)

```

Are you wanting both "ifs" to occur? Maybe a bitwise operator like logical AND (`&`)?
> 1 votes

# Answer
This looks like a good use for a State Machine.

It would look something like this:

```
typedef enum State
{
  STATE_IDLE,
  STATE_THIS,
  STATE_THAT,
  STATE_OTHER
} State;

State state;

const int IR_BUTTON_1    = 0xFF807F;
const int IR_BUTTON_2    = 0x112233;
const int IR_BUTTON_3    = 0X445566;
const int IR_BUTTON_STOP = 0x778899;

void setup()
{
  Serial.begin(115200);
  Serial.println(F("setup()"));
  state = STATE_IDLE;
}

void loop()
{
  Serial.println(F("loop()"));

  switch(my_decoder.value)
  {
    case IR_BUTTON_1:
      state = STATE_THIS;
      Serial.println(F("Entered STATE_THIS"));
      break;
    case IR_BUTTON_2:
      state = STATE_THAT;
      Serial.println(F("Entered STATE_THAT"));
      break;
    case IR_BUTTON_3:
      state = STATE_OTHER;
      Serial.println(F("Entered STATE_OTHER"));
      break;
    case IR_BUTTON_STOP:
      state = STATE_IDLE;
      Serial.println(F("Entered STATE_IDLE"));
      break;
  }

  switch(state)
  {
    case STATE_THIS:
      DoThis();
      break;
    case STATE_THAT:
      DoThat();
      break;
    case STATE_OTHER:
      DoOther();
      break;
  }
}

void DoThis()
{
  Serial.println(F("DoThis()"));
}

void DoThat()
{
  Serial.println(F("DoThat()"));
}

void DoOther()
{
  Serial.println(F("DoOther()"));
}

```

This locks the state machine into an active state as per the OP's comment:

> I want it to repeat the "void doSomething();" function until another button is pressed.

However, as Dave Newton pointed out in the comments, locking a machine into a particular active state can be dangerous, so I've edited the code to add a STOP button to transition back to the IDLE state. But this still relies on the operator pressing the STOP button to return to idle; there is no automatic return to idle which could be a hazard depending on the application.
> 0 votes

---
Tags: arduino-uno, arduino-ide
---


# Question
Title: Pro Micro board not responding to anything
I just got a couple of Arduino Pro Micros for a custom keyboard build. Before testing them with the Arduino IDE, I tried to test them with qmk by shorting `RST` to `GND` to try and flash it. After a few seconds of holding `RST`, I got a single blink and nothing else, and qmk didn't seem to have detected the reset.

I've tried setting "Board" to "Arduino Micro" and "Arduino Pro or Pro Mini". I'm on Arch Linux and no matter which USB port is plugged in, the IDE only shows `/dev/ttyS0`). I tried uploading the "Blink" example, as well as "Burn Bootloader", but only got `programmer is not responding` like so:

```
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         Using Port                    : /dev/ttyS0
         Using Programmer              : arduino
         Overriding Baud Rate          : 19200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

```

# Answer
It turns out I had to use the port `ttyACM0` (and not `ttyS0`) which wasn't found at the time. The port was there the next day and I have no idea why it wasn't there before.

Also, I thought I had to press and hold `RST` for a couple of seconds to reset the Pro Micro, but I actually have to press it twice in a row.

I've managed to flash the firmware for my keyboard by double-pressing `RST`.
> 1 votes

---
Tags: arduino-pro-micro
---


# Question
Title: Updating mysql data using SIM900 and Arduino
Thanks in advance for your kind support. I am not an expert but have little understanding of concepts and trying to integrate various things to get some useful projects for my purpose. I want to update the database (MySQL) on shared hosting using the SIM900A module and Arduino nano board. With help of examples shared on this platform and my understanding, I achieved a significant part of the same. The following is the approach I have adopted and the current status:

I have put a PHP code on the server (shared hosting) to update the database once it received the GET request I have also uploaded the code in the Arduino with proper connections for sending requests to the server.

Problems I am facing: I am not able to update the data on my specific database, through the Arduino sent request. the same code is working with Thingspeak, My code is also working otherwise, as I have tested through web form request and URL request. I am not sure where is the problem. I am also not getting any errors. The response to the AT request is "OK" only Though I can update the Thingspeak channel, only till the command lesser than 61 characters, which are sent after the AT+CIPSEND command. There is no error, even if the request size increases, but data updated only till 61 characters (including \x1A character) "I am wondering, is this the limit, that cannot be increased or there is some possibility to increase it." I understand that the problem appears to be in approach and not in code, as the code is working in itself. However, please let me know, which code I need to share, as it is a multifile code on the web-editor

# Answer
I have faced a similar issue. It happened due to an SSL issue. You can find all info about it here - https://stackoverflow.com/questions/62950561/sim800l-gsm-module-working-with-http-and-shows-error-with-https-why
> 1 votes

---
Tags: serial, arduino-nano, gsm
---