title: Robot car not working

text:
# Question
Title: Robot car not working
My robot car won’t respond to my command. The code below worked before however, this time there is no response. I’ve tried experimenting with the code in the first while loop. I’ve tried different code from other projects similar to this. I’ve played with the schematics however, nothing seems to work.

This is my code:

```
#include <SoftwareSerial.h> // TX RX software library for bluetooth
#include <Servo.h> // servo library
Servo myservo1, myservo2, myservo3; // servo name
int bluetoothTx = 10; // bluetooth tx to 10 pin
int bluetoothRx = 11; // bluetooth rx to 11 pin
int motorOne = 4;
int motorOne2 = 5;
int motorTwo = 6;
int motorTwo2 = 7;
int enA = 3;
int enB = 2;
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

//initial motors pin

char command;
char Value;

void setup()
{
  myservo1.attach(2); // attach servo signal wire to pin 9
  myservo2.attach(8);
  myservo3.attach(12);

  //Setup usb serial connection to computer
  Serial.begin(9600);
  //Setup Bluetooth serial connection to android
  bluetooth.begin(9600);
}
void loop()
{
  while (bluetooth.available() > 2) {
    Value = bluetooth.read();
    Serial.println(Value);
  }

  if ( Value == 'F') {
    // Robo Pet Run Forward
    digitalWrite(enA, 255);
    digitalWrite(enB, 255);
    digitalWrite(motorOne, HIGH);
    digitalWrite(motorOne2, LOW);
    digitalWrite(motorTwo, HIGH);
    digitalWrite(motorTwo2, LOW);
  } else if (Value == 'B') {
    //Robo Pet Run Backward
    digitalWrite(enA, 255);
    digitalWrite(enB, 255);
    digitalWrite(motorOne, LOW);
    digitalWrite(motorOne2, HIGH);
    digitalWrite(motorTwo, LOW);
    digitalWrite(motorTwo2, HIGH);
  } else if (Value == 'L') {
    //Robo Pet Turn Left
    digitalWrite(enA, 255);

    digitalWrite(motorOne, LOW);
    digitalWrite(motorOne2, LOW);
    digitalWrite(motorTwo, HIGH);
    digitalWrite(motorTwo2, LOW);
  } else if (Value == 'R') {
    //Robo Pet Turn Right

    digitalWrite(enB, 255);
    digitalWrite(motorOne, HIGH);
    digitalWrite(motorOne2, LOW);
    digitalWrite(motorTwo, LOW);
    digitalWrite(motorTwo2, LOW);
  } else if (Value == 'S') {
    //Robo Pet Stop
    digitalWrite(motorOne, LOW);
    digitalWrite(motorOne2, LOW);
    digitalWrite(motorTwo, LOW);
    digitalWrite(motorTwo2, LOW);
  }

  //Read from bluetooth and write to usb serial
  if(bluetooth.available()>= 2 )
  {
    unsigned int servopos = bluetooth.read();
    unsigned int servopos1 = bluetooth.read();
    unsigned int realservo = (servopos1 *256) + servopos;
    Serial.println(realservo);
    if (realservo >= 1000 && realservo <1180) {
      int servo1 = realservo;
      servo1 = map(servo1, 1000, 1180, 0, 180);
      myservo1.write(servo1);
      Serial.println("Servo 1 ON");
      delay(10);
    }
    if (realservo >= 2000 && realservo <2180) {
      int servo2 = realservo;
      servo2 = map(servo2, 2000, 2180, 0, 180);
      myservo2.write(servo2);
      Serial.println("Servo 2 ON");
      delay(10);
    }
    if (realservo >= 3000 && realservo <3180) {
      int servo3 = realservo;
      servo3 = map(servo3, 3000, 3180, 0, 180);
      myservo3.write(servo3);
      Serial.println("Servo 3 ON");
      delay(10);
    }

  }
}

```

I’m using this app: https://play.google.com/store/apps/details?id=com.giumig.apps.bluetoothserialmonitor&hl=en&gl=US

And here are the schematics:

# Answer
> 0 votes
@timemage

Your answer was part of the solution!

Thank you very much! In the first while loop I switched it from `bluetooth.available > 2` to `bluetooth.available > 0` and then switched the signs of the TX and RX. Now the robot car is responding and running. However it won't turn left even though both motors work fine.

# Answer
> 1 votes
In short, among whatever other problems you might have, **you've wired your TX and RX connections backwards according to your diagram and code. Swap them either in hardware or in software.**

---

According to the documentation:

```
SoftwareSerial var_name(rxPin, txPin)

```

| SS Operation |
| --- |
| RX |
| TX |

You've constructed your `SoftwareSerial` object as:

```
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

```

| SS Operation | Pin Variable |
| --- | --- |
| RX | `bluetoothTx` |
| TX | `bluetoothRx` |

Defined your pin variables to these pins:

```
int bluetoothTx = 10; // bluetooth tx to 10 pin
int bluetoothRx = 11; // bluetooth rx to 11 pin

```

| SS Operation | Pin Variable | Arduino Pin |
| --- | --- | --- |
| RX | `bluetoothTx` | 10 |
| TX | `bluetoothRx` | 11 |

Connected them as:

| SS Operation | Pin Variable | Arduino Pin | BT Operation |
| --- | --- | --- | --- |
| RX | `bluetoothTx` | 10 | RX |
| TX | `bluetoothRx` | 11 | TX |

**So, you have them backwards. Connecting their RX (inputs) which is is harmless but not helpful and connecting their TX (outputs) which *may* damage something.**

In case this isn't clear, the RX and TX on the HC-05 are labeled from its perspective and not from the perspective of the Arduino. Except for some things like an old external modem, RX and TX on device are nearly always labeled from that device's perspective.

---

A variable name like `bluetoothTx` can be confusing if you're not sure which thing is doing the transmitting. Is this the pin number *for transmitting* to Bluetooth or the pin that will be connected to the Bluetooth transmitter (in other words, *for receiving*)?

In some cases I just describe the situation in the variable name:

```
static const int PIN_SOFTSERIAL_RX_TO_BLUETOOTH_TX = 11;
static const int PIN_SOFTSERIAL_TX_TO_BLUETOOTH_RX = 10;
/// ...
SoftwareSerial bluetooth(
  PIN_SOFTSERIAL_RX_TO_BLUETOOTH_TX,
  PIN_SOFTSERIAL_TX_TO_BLUETOOTH_RX
);

```

I dunno that I'd go with a name *quite* that long, but you get the idea.

I'm swapping them in software here, leaving your physical connections as they were in the diagram mostly because I don't feel like redrawing your diagram. Though, if it were my project I would swap the wires (and defined pin numbers above), because the convention is to have SoftwareSerial receive on 10 just like hardware receives on pin 0 and to have SoftwareSerial transmit on 11 just like hardware transmits on pin 1; in order words, keeping the relative order of the pin numbers.

So this is what you have with the above code:

| SS Operation | Pin Variable | Arduino Pin | BT Operation |
| --- | --- | --- | --- |
| RX | `PIN_SOFTSERIAL_RX_TO_BLUETOOTH_TX` | 11 | TX |
| TX | `PIN_SOFTSERIAL_TX_TO_BLUETOOTH_RX` | 10 | RX |

Transmitters connected to receivers. If you get confused build your own table and make sure your variable names make sense.

This has nothing to do with our question really, but: Most Arduino users, new ones anyway, are better off with an Arduino that has connectivity that displaces the need for SoftwareSerial. A minimal change from the Nano for what you're doing is a Micro or Pro Micro board. That board has native USB support which it uses to send "Serial" to the computer. That leaves the one actual hardware serial peripheral on the (Pro) Micro available for you to to connect to HC-05 (or whatever). There are a pile of options, including ones that just do Bluetooth also (without need of HC-05). Anyway, there are lots of ways to not use SoftwareSerial.

---
Tags: arduino-nano, bluetooth, android
---


title: Proper Micro SD card schematic

text:
# Question
Title: Proper Micro SD card schematic
I am using a micro sd card shield with an arduino zero, and I am not sure I am using a proper circuit with it. This is the circuit I am using right now:

That is all it is there, just a capacitor for the power and a pullup resistor for the chipselect. The tags just go to the processor.

I have seen a lot of schematics out there with resistors in series to the processor, some times with pull up resistors, some times with pulldown resistors...

I'm not sure the pullup resistor I am using is a good idea, and I am unsure about the value.

To me something like this makes more sense:

Can someone teach me a proper circuit for this? what is best and why?

Right now I am not very happy with the performance of the micro SD card socket. That's why I want to improve it.

EDIT: Turns out I didnt really understand very well the second schematic, it was just voltage dividers to lower the 5v os arduino uno to 3V. But what about the pullup resistor of the MISO?

# Answer
> 4 votes
As per the SD card specification:

> When an SD card is operating in SPI mode or 1-bit SD mode, the CMD and DATA (DAT0 - DAT3) lines of the SD bus must be pulled up by 10 kOhm resistors. Slaves should also have pull-ups on all above-mentioned lines (regardless of whether these lines are connected to the host) in order to prevent SD cards from entering a wrong state.

Basically you need to ensure that "everything is off" until the Arduino actively drives the SD card. Without them the SD card's inputs will be floating and doing anything they like until the Arduino starts communicating.

Resistors in-line with the signals are there really just to increase the impedance and prevent damage when hot-swapping a card.

If you have a 5V Arduino you will require logic level translation. This is a *separate* thing to the resistors. While resistors are OK for UART or simple IO logic level translation they are *not* suitable for use with an SD card. This is because the clock frequencies involved are too high and the resistors will corrupt the signal (through low pass filtering). Instead you require an active logic level translation system, such as a dual voltage, or TTL input, buffer, or active MOSFET level shifters.

# Answer
> 2 votes
There's an excellent tutorial on Instructables I recommend one to read. here's the link https://www.instructables.com/Select-SD-Interface-for-ESP32/

# Answer
> 1 votes
There are a couple of "do and don't" when designing an SPI interface.

**Do add pull-up resistors on SS or set SS HIGH for multiple-slave system**

SPI is a bus system, means that your device might not be the only one using the interface. When designing an SPI interface, you therefore has to consider the scenario where multiple SPI devices are used, and especially when some of the slaves are not coded by your system.

Without a pullup resistor, the SS line might be neither LOW nor HIGH, this might caused some of the devices on the bus to “hear” the communication on its MISO that was not intend for the device. This might explained why some of the Arduino shields or breakout boards with SPI works when used alone, but fail when used together with other SPI boards, causing by some of those boards lack of pullup resistor or the user didn't pull the SS lines in the system HIGH at the `setup()` before calling the `SPI.begin()`!

**Do ensure MISO can be tri-state in multiple-slave system**

Most SPI chips will be at tri-state on their MISO pin (but there are some chips out there requires extra external tri-state buffer chip) when their chip select signal is HIGH. Tri-stage means that it is neither HIGH nor LOW (i.e. floated) and effectively disconnect. However, A SPI device without tri-state MISO could caused potential problem on a SPI bus where multiple SPI devices are connected. If the MISO is unable to be at tri-state, it will be either HIGH or LOW, this will affect other devices connected on the same bus in receiving data.

With this in mind, it is not a good idea to add a pull-up resistor on MISO line.

---
Tags: sd, arduino-zero
---


# Question
Title: What happen with my code? My sensor module LED2 Always ON
I got this code from robojax.com i have follow all the step but when i try to clap its not turn off or turn on but when i blowing on the sound sensor it reacts and makes the light turn on

```
int soundInPin = 2;// connect output to Sound module DO
int relayPin = 8;// Connected to relay or buzzer (or LED)
int extra5V = 12;// define a pin for extra extra 5V

// do not change values bellow
int val = 0; // sound value from pin 2
int relayON = 0;//light status
int heard = 0;//sound heard status

void setup() {

//Robojax Arduino Step By Step Course http://robojax.com/L/?id=338
  Serial.begin(9600);
  pinMode(soundInPin, INPUT_PULLUP);
  pinMode(relayPin, OUTPUT);
  pinMode(extra5V,OUTPUT);// set extra5V as output
  digitalWrite(extra5V,HIGH);// turn the extra5V pin HIGH to get 5V

}

void loop() {
//Robojax Arduino Step By Step Course http://robojax.com/L/?id=338
  val = digitalRead(soundInPin);// read the sound pin

  if(val == HIGH && relayON == LOW){

    heard = 1-heard;// toggle the value of "heard" from HIGH to LOW or from LOW to HIGH
    delay(100);
  }
//Robojax Arduino Step By Step Course http://robojax.com/L/?id=338
  relayON = val;// save the value of pin 2

      if(heard == HIGH){
        Serial.println("Light ON");
        digitalWrite(relayPin, LOW); // turn relay ON

      }else{
        Serial.println("Light OFF");
        digitalWrite(relayPin, HIGH);// turn relay OFF

      }

//Robojax Arduino Step By Step Course http://robojax.com/L/?id=338
  delay(100);
}

```

# Answer
This is not an answer, so I will delete it after you read it.

Since you are a beginner, here is a comment on programming style.

Your code feels very cluttered and overwhelming because the comments are made a part of the program lines.

There is a difference in readability between these two lines.

`digitalWrite(extra5V,HIGH);// turn the extra5V pin HIGH to get 5V`

`digitalWrite(extra5V,HIGH); // turn the extra5V pin HIGH to get 5V`

The comments are there for future, like next year, to remind you what the program does.

Also the following two lines are on the same indentation level

```
  relayON = val;     // save the value of pin 2

      if(heard == HIGH){

```

and should be

```
  relayON = val;     // save the value of pin 2

  if(heard == HIGH){

```

With some formatting changes, your code could look something like this.

```
int soundInPin =  2;                       // connect output to Sound module DO
int relayPin   =  8;                       // Connected to relay or buzzer (or LED)
int extra5V    = 12;                       // define a pin for extra extra 5V

// do not change values below

int val        =  0;                       // sound value from pin 2
int relayON    =  0;                       // light status
int heard      =  0;                       // sound heard status

void setup() {                             // Robojax Arduino Step By Step Course http://robojax.com/L/?id=338

  Serial.begin(9600);

  pinMode(soundInPin, INPUT_PULLUP);
  pinMode(relayPin,   OUTPUT);
  pinMode(extra5V,    OUTPUT);             // set extra5V as output

  digitalWrite(extra5V,HIGH);              // turn the extra5V pin HIGH to get 5V

}

void loop() {                              // Robojax Arduino Step By Step Course http://robojax.com/L/?id=338

  val = digitalRead(soundInPin);           // read the sound pin

  if (val == HIGH && relayON == LOW) {

    heard = 1-heard;                       // toggle the value of "heard" from HIGH to LOW or from LOW to HIGH
    delay(100);

  }                                        // Robojax Arduino Step By Step Course http://robojax.com/L/?id=338

  relayON = val;                           // save the value of pin 2

  if (heard == HIGH) {

    Serial.println("Light ON");
    digitalWrite(relayPin, LOW);           // turn relay ON

  } else {

    Serial.println("Light OFF");
    digitalWrite(relayPin, HIGH);          // turn relay OFF

  }
                                           // Robojax Arduino Step By Step Course http://robojax.com/L/?id=338
  delay(100);
}

```
> 1 votes

---
Tags: sensors
---


# Question
Title: When Writing Library, return String or return char *
I am trying to write my own Arduino library and I would like to make it useful not just for ESP32/ESP8266 boards but also with Arduino boards.

I have created my header file like this

> test.cpp

```
#ifndef TEST
#define TEST
#include "Arduino.h"

#define MAX_STRING_LEN 50

class MyClass{
    private:

    public:
        String getString();
        char * getCharPointer();
        char * getAnotherCharPointer();
};

#endif

```

and my

> test.cpp

```
#include "test.h"

static char buffer[MAX_STRING_LEN+1];

String MyClass::getString(){
    // Sample REST API call
    String testString = String("{\"test:\" \"hello String json\"}");

    return testString;
}

char * MyClass::getCharPointer(){
    // Sample REST API call
    const char * sample_json = "{\"test:\" \"hello Char Pointer json\"}";
    strcpy(buffer, sample_json);
    return buffer;
}

char * MyClass::getAnotherCharPointer(){
    // Sample REST API call
    const char * sample_json = "{\"test:\" \"hello Another Char Pointer json\"}";
    strcpy(buffer, sample_json);
    return buffer;
}

```

My test file main.cpp

> main.cpp

```
#include <Arduino.h>
#include "test.h"

MyClass myClass;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  Serial.println(myClass.getString());
  Serial.println(myClass.getCharPointer());
  Serial.println(myClass.getAnotherCharPointer());
}

void loop() {
  // put your main code here, to run repeatedly:
}

```

Result is ok

```
{"test:" "hello String json"}
{"test:" "hello Char Pointer json"}
{"test:" "hello Another Char Pointer json"}

```

I have these doubts that I would like to ask for suggestions.

1. Is returning the String class in Header files, not a good idea? For ESP32/ESP8266 they are okay as they have big memory but for Arduino Uno boards I see a lot of discussions about not using String because it is bad and causes memory fragmentation etc.
2. Is returning char * the safest way to make it compatible and useful to all MCU boards?
3. Next question in char pointer, I often see this pattern done when returning char pointers like in this Time.cpp wherein a static buffer is used and defined at the implementation file (**test.cpp**) and all functions(getCharPointer, getAnotherCharPointer) that needs to return a char pointer just manipulates the static char buffer by using strcpy. Is this the proper way to go in Arduino programming?

Can somebody please clear my doubts? Thank you.

# Answer
> 1 votes
> \[The OP asks:\] For ESP32/ESP8266 they are okay as they have big memory but for Arduino Uno boards I see a lot of discussions about not using String because it is bad and causes memory fragmentation etc.

On Unos and other boards with very low memory, fragmentation won't take very long to happen. On boards with larger memories, it will merely *take longer!* but it will happen; it's just a difference of when. (And for completeness, I should say that allocating a few objects, *once*, and within the device's available free memory, won't cause fragmentation, any more than static allocation would).

> So why is allocation/deallocation used at all \[I ask, rhetorically...\]?

On systems running a full OS, driven by ourselves with a keyboard and mouse, most application programs are transient - they start up, do a job, and exit; even longer running ones like office applications are fairly speed-limited by us slow humans. And if a program crashes, we're still sitting there to re-run it, and no external device gets left hanging for hours or days, maybe destroying itself (by overheating, perhaps), maybe injuring or killing a patient (in the case of a medical device), injuring or killing many people (in case of a vehicle's engine- or flight controls).

Otherwise, run-time memory allocation is a convenience for the programmer.

> So what to do in an embedded system, instead \[asks I\]?

I use two techniques to get around the crash-proneness of the compiler-libraries' allocator/deallocators:

1. When I write a library, I design it to expect an `(object *)` from the caller, as you anticipated in your 'doubt #3'. All the library has to do is put its result there; the memory will already have been allocated. *The library doesn't need to know or care **how** it was allocated.* Does this sound like I'm avoiding solving the problem and leaving memory issues for some else to deal with? Yes, indeed, and it is deliberate! The user of my library - you, (or me, some other day), the application writer/system architect - is the best one to anticipate their particular system's memory needs, and to decide how best to meet them.
Writing my library this way lets the library-user decide whether a static buffer, a local one, or a dynamic allocation is the best fit for their application.
2. I write my own memory management (probably at the application level rather than in the library). This almost always takes the form of an array of fixed-length buffers. No matter how much memory the caller asks for, as long as it is less than that fixed size, and one is available, then the call succeeds and a buffer will be returned; otherwise, the call fails. The caller doesn't know, or need to know, that the buffer returned to them might be larger than they requested.
Why is this technique any better? `malloc()`/`free()` and `new()`/`delete()` break up free memory into ever smaller pieces, as they are requested. *A fixed-size-buffer allocater does not break up memory.*

A system using these techniques together avoids memory fragmentation. The only way such a system can fail (due to memory allocation) is to not have enough in the first place, and the only fixes are 1) for the programmer to assign more memory for fixed-size buffers; or, if the board doesn't have enough more, then 2) build the system with a host board that has enough memory.

# Answer
> 0 votes
> I often see this pattern done when returning char pointers like in this Time.cpp wherein a static buffer is used and defined at the implementation file (test.cpp) and all functions(getCharPointer, getAnotherCharPointer) that needs to return a char pointer just manipulates the static char buffer by using strcpy. Is this the proper way to go in Arduino programming?

Arduino programming is C++ programming. You can return a pointer to a static buffer, of course. But the user of your function needs to know that if they call the function a second time the data will be overwritten. So, they would need to `strcpy` (that is, copy) the data before it is overwritten.

Personally I would stay away from the String class, unless it is being used only occasionally. It is fine with strings that are always the same size, but if they are not, memory fragmentation will be an issue.

---
Tags: c-string
---


# Question
Title: DHT11 stops working when power comes from a power supply board
I had a mini project with a DHT11, a temperature and humidity sensor, working perfectly on my Arduino UNO clone. Then, I bought a power supply board, that can feed the sensor with the 5V it requires, but for some reason, it does not work. Powering the sensor with the Arduino makes it get the correct values, powering it with the board makes it to stop working at all.

I have used a multimeter for checking the volts and amps. The readings on the sensor are the same with the Arduino and the board, 5V, but the amps are not. It seems that the sensor only uses power for an instant, while "sensing". Using Arduino, a 1.62mA current flows to the sensor and then drops to 0, but using the board it never gets higher than 0.001mA.

I repeated the test with different wires, protoboards and even power supply boards. I have three of them, all working apparently ok and reading the same on the multimeter. The board have the jumpers in the correct position: 5V.

I am just an amateur learning how electronics works, and I do not understand what is happening here. Some ideas?

Working:

Not working:

I don't think the problem is in the code, but just in case...

```
#include "DHTStable.h"

DHTStable DHT;

#define DHT11_PIN 5

void setup() {
    Serial.begin(115200);
    Serial.println(__FILE__);
    Serial.print("LIBRARY VERSION: ");
    Serial.println(DHTSTABLE_LIB_VERSION);
    Serial.println();
    Serial.println("Type,\tstatus,\tHumidity (%),\tTemperature (C)");
}

void loop() {

    // READ DATA
    Serial.print("DHT11, \t");
    int chk = DHT.read11(DHT11_PIN);

    switch (chk)
    {
        case DHTLIB_OK:
            Serial.print("OK,\t");
            break;
        case DHTLIB_ERROR_CHECKSUM:
            Serial.print("Checksum error,\t");
            break;
        case DHTLIB_ERROR_TIMEOUT:
            Serial.print("Time out error,\t");
            break;
        default:
            Serial.print("Unknown error,\t");
            break;
    }

    // DISPLAY DATA
    Serial.print(DHT.getHumidity(), 1);
    Serial.print(",\t");
    Serial.println(DHT.getTemperature(), 1);

    delay(2000);
}

```

# Answer
> 0 votes
In your question in the image below your grounds are not connected. The solution to your problem is to connect the ground (and only the ground, not the +5V) of your external power supply to the ground of the Arduino and the DHT11 will probably work again.

**A bit of background**

Sensors needs to be connected to the same ground as the Arduino. This is true in general with all parts of an electronic circuit. Ground functions as a fixed, common, reference voltage by which other signals (such as the digital data that's exchanged between the DHT11 sensor and the Arduino) are measured.

By connecting grounds, you make sure that a "high" that is output by the DHT11 is read as a "high" by Arduino and vice versa. When grounds are not connected, voltages between two parts of the circuit would "float" relative to each other and they would not be able to communicate. This link explains a bit more.

---
Tags: arduino-uno, power, dht11
---


# Question
Title: Why wont my custom Arduino-Micro-based board receive power via USB?
UPDATE: I believe I have mostly solved the power issues, but now have USB connectivity issues described in EDIT 3 at the bottom.

I designed and printed a PCB for my MIDI controller project with a modified Arduino Micro microcontroller built in. I swapped out the USB Micro for a USB-C type port (just using the 2.0 protocol), but when I plug it in, after programming the bootloader to the ATMEGA32U4 via "Arduino as ISP" with an Uno as ISP to the ICSP of my board, my board seems to get no power from the USB bus (the power LED doesn't light up, nor is it recognized as a USB device), but it does get power over the ICSP and I got a success message after programming it with the Uno.

I have tried many USB cables, including USB-C ones I know to be 2.0 compatible and USB Micro cables (which have been tested with regular Arduino Micros) with micro-to-C adapters, but still get nothing. My PCB has full parity with my SCH file, and I tested it on multiple of these boards that I got printed, so I am pretty sure I must have messed something up in the schematic or in component selection (not all the exact components from the official Arduino Micro schematic were available at JLCPCB where I had mine printed so I made some substitutions).

Can anyone help me figure out what the issue might be?

EDIT 1: So I found out that the power is coming in through the USB, its reading 5V at the USB pins, 5V on either side of the fuse F1 and the VUSB pin of the T1 FDN340P/PMV48XP, but 0V at both the VIN and +5V pins of the same T1, so that seems to be the problem component? I'm using a PMV48XP in that position, not sure if I messed that up somehow? I'm a bit out of my depth here I think

I've uploaded the schematic and the component list below:

Components:

```
| Designator                                             | Value                   | Component                |
|:--------------------------------------------------------|:-------------------------|:--------------------------|
| C_ARD_1, C_ARD_2, C_ARD_6, C_ARD_9, C_ARD_10, C_ARD_11 | 100n                    | CL05B104KO5NNNC          |
| C_ARD_3, C_ARD_14                                      | 22u                     | RVT22UF16V67RV0017       |
| C_ARD_4, C_ARD_5, C_ARD_7                              | 1uF                     | CL05A105KA5NQNC          |
| C_ARD_12, C_ARD_13                                     | 22pF                    | 0402CG220J500NT          |
| D_ARD_2                                                | CD1206-S01575           | CDSU4148-HF              |
| F1                                                     | MF-MSMF050-2 500mA      | MF-MSMF050-2             |
| J3                                                     | USB_C_Receptacle_USB2.0 | KH-TYPE-C-16P            |
| L1                                                     | green                   | 19-217/GHC-YR1S2/3T      |
| L2                                                     | MH2029-300Y             | BLM21PG300SN1D           |
| ON1                                                    | blue                    | 19-217/BHC-ZL1M2RY/3T    |
| R_ARD_1, R_ARD_2, R_ARD_4, R_ARD_9                     | 10K                     | 0402WGF1002TCE           |
| R_ARD_5, R_ARD_6, R_ARD_7, R_ARD_8                     | 1K                      | 0402WGF1001TCE           |
| R_ARD_10, R_ARD_11                                     | 5.1k                    | 0402WGF5101TCE           |
| RP3                                                    | 22R                     | 4D03WGJ0220T5E           |
| RX1, TX1                                               | yellow                  | 19-213/Y2C-CQ2R2L/3T(CY) |
| T1                                                     | FDN340P/PMV48XP         | PMV48XP                  |
| T2                                                     | PMV48XP                 | PMV48XP                  |
| U1                                                     | ATMEGA32U4-XUMU         | ATMEGA32U4-MU            |
| U2                                                     | NCP1117-5               | NCP1117ST50T3G           |
| U4                                                     | LP2985-33DBVR           | LP2985-33DBVR            |
| Y3                                                     | 16MHz KX-7              | 3225-16.00-10-10-10/A    |
| Z1, Z2                                                 | CG0603MLC-05E           | EZJZ0V500AA              |

```

EDIT 2: I think I found the problem. It looks like something got messed up when I was choosing the footprints of the MOSFET transistors T1 and T2. Here is a screenshot from the datasheet of the PMV48XP datasheet showing the pinning info:  and now here is a screenshot of the relevant part of my PCB file:  So according to my schematic (again, based on the official Arduino Micro SCH, so I'm assuming its correct?) T1 Gate should be VIN, T1 Source should be +5V, T1 Drain should be VUSB. On my PCB T1 Gate is actually VUSB, T1 Source is +5V, T1 Drain is actually VIN. So it looks like the Gate and Drain pins got swapped between my SCH and my PCB. Same story for T2. Can anyone with more knowledge confirm that the connections outlined in the schematic are correct? And whether that would explain the problems I've described?

EDIT 3: I have de-soldered T1 and T2, which were in indeed incorrectly wired. I have shorted the contacts between VUSB and +5V on the footprint of T1 and the board is getting power as it is supposed to.

Now I have a new issue which is that after I have programmed the board via ICSP (using the Arduino as ISP method, burning the Arduino Micro bootloader to it), when I plug the board into my computer (again, testing with a variety of cables and ports), my computer won't recognize it as a USB device. I'm not sure if this is a related problem to my previous one (and maybe I should make a new post if not?) or where I am going wrong now.

# Answer
I think you need to understand a little bit of how the T1 and T2 functions in order to troubleshoot. The purpose of T1 is when power is supplied via VBUS, and when Vin is not presented (i.e. at 0v), the VUSB is directly supplied as the 5V(bypassing the NCP1117 regulator). However, when you power via Vin and it is at least higher than 5V(likely at 7V), it will turn off the T1 and cut off the VUSB supply, and T2 is on, Vin is apply as the input to the NCP1117.

So with this in mind, if you connect your board via VBUS but can't get 5V, then you either has a malfunction T1 or you had connect T1 drain and source wrongly. However, if you supply your board via Vin, and don't get the 5V, there could be that your Vin is not high enough to turn on the T2, or your had wrong connection on T2.
> 1 votes

---
Tags: usb, arduino-micro
---


# Question
Title: #define from main (.ino) not considered by comiler in own libaries
I have got the problem, that my #define from main (.ino) is not considered by the comiler in my own libaries. This #define MQTT\_MODULE is only considered in the main (.ino) programm, but not in MyRemoteLib.cpp This example works normally, if I compile it with gcc.

Code in my Test.ino :

```
#define         MQTT_MODULE             1
#include        "MyRemoteLib.h"
loop() {
  my_test() ;
}

```

Code in MyRemoteLib.h

```
#define     MYREMOTELIB_H
#define     MY_TEST         1
#if         MQTT_MODULE
  #define       MQTT_MOD_R              1
#endif

```

Code in MyRemoteLib.cpp :

```
#include        "MyRemoteLib.h"
void my_test() {
  #if   MQTT_MOD_R
      test.... > nothing -> ignored by compiler
  #endif
  #if   MQTT_MODULE
      test.... > nothing -> ignored by compiler
  #endif
  #if   MYTEST
      test.... > error-> not ignored by compiler
  #endif
}

```

# Answer
This is the expected behavior. The library and the main program are two different compilation units: there are processed by the compiler separately.

In the main program, the inclusion of the header file yields this:

```
#define         MQTT_MODULE             1
// Included from MyRemoteLib.h:
#define     MYREMOTELIB_H
#define     MY_TEST         1
#if         MQTT_MODULE
  #define       MQTT_MOD_R              1
#endif
// end of included code
loop() {
  my_test() ;
}

```

The remaining preprocessor code has no effect at all.

In the library, the same inclusion yields this:

```
// Included from MyRemoteLib.h:
#define     MYREMOTELIB_H
#define     MY_TEST         1
#if         MQTT_MODULE
  #define       MQTT_MOD_R              1
#endif
// end of included code
void my_test() {
  #if   MQTT_MOD_R
      test.... > nothing -> ignored by compiler
  #endif
  #if   MQTT_MODULE
      test.... > nothing -> ignored by compiler
  #endif
  #if   MYTEST
      test.... > error-> not ignored by compiler
  #endif
}

```

The conditional compilation gives an empty `my_test()` (that is, unless by `MYTEST` you actually mean `MY_TEST`).

I do not know what you are trying to achieve, but you may look at ways to put the code to be conditionally compiled in the header itself. You may try using inline functions, or maybe templates.

**Edit**: about removing code using conditional compilation: this is not always as useful as it may sound, for two reasons.

1. By default, the Arduino IDE compiles your code with the options `-ffunction-sections` and `-fdata-sections`, and links it with `-Wl,--gc-sections`. This means that any function or method that is never used, or any global variable that is never referenced, is not included in the final executable.
2. The code is also compiled with `-flto`, which enables link-time (full program) optimizations. This means that code that depends on a condition that is always false (the conditional expression can be resolved as a compile-time constant) is also removed from the final executable.
> 2 votes

---
Tags: library, c-preprocessor
---


# Question
Title: Controlling the 5V pin on the Arduino nano 33 BLE
Following the guidance on this post I have enabled the 5V pin. That same post suggests that I control that pin with D12, though I find it weird since there is already a D12 pin. When I try and run some code the D12 pin is performing exactly as I expect, but the 5V pin is doing nothing.

Looking through the tech specs it says "**the 5V pin does NOT supply voltage but is rather connected, through a jumper, to the USB power input.**" which I find odd, since if its connected to the power input, should it not be supplying voltage?

Could someone clarify if its possible to use the 5V pin like a digital pin, and if so how?

# Answer
> 0 votes
> Following the guidance on this post I have enabled the 5V pin. That same post suggests that I control that pin with D12, though I find it weird since there is already a D12 pin. When I try and run some code the D12 pin is performing exactly as I expect, but the 5V pin is doing nothing.

5 V pin is the the 12th pin of the PCB

> Looking through the tech specs it says "the 5V pin does NOT supply voltage but is rather connected, through a jumper, to the USB power input." which I find odd, since if its connected to the power input, should it not be supplying voltage?

it says that the 5V pin is connected to the USB power input through a jumper and the jumper is not connected from factory

---
Tags: arduino-nano-ble
---


# Question
Title: Do I need to connect a capacitor to AREF if using internal reference? _BV(REFS0)
This is from the Atmega328p datasheet. But I see no mention of it in practical examples. So when I'm setting up the timer for ADC with:

```
ADMUX = _BV(REFS0);

```

Should I add the cap? Or might it be already there on the arduino's hardware? Also what value is advised? 100nF? Thanks in advance!

# Answer
> 1 votes
According to the datasheet:

> The voltage reference may be externally decoupled at the AREF pin by a capacitor for better noise performance.

So you *can* but you don't *have to*. It all depends on how good you want your ADC results to be. 99% of the time it's pointless since what you're reading isn't that accurate, but if you want to add a capacitor anyway then sure, go right ahead.

What value capacitor? Well that very much depends on what kind of noise you want to achieve more immunity from. The lower the value the higher the frequency it will help protect you from. You may want to combine multiple capacitors in parallel if you're in a very noisy environment, such as 1nF and 100nF.

---
Tags: arduino-uno, arduino-nano
---


# Question
Title: ESP32 - error when using `LITTLEFS.h` after core updated to 2.0.4
After updating ESP32 to core version 2.0.4 (file in Arduino IDE preferences was replaced to`https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json` to upgrade), I get the following error:

```
/Users/guydvir/Dropbox/Arduino/libraries/LittleFS_esp32/src/LITTLEFS.cpp: In member function 'virtual bool LITTLEFSImpl::exists(const char*)':
/Users/guydvir/Dropbox/Arduino/libraries/LittleFS_esp32/src/LITTLEFS.cpp:44:28: error: no matching function for call to 'LITTLEFSImpl::open(const char*&, const char [2])'
     File f = open(path, "r");
                            ^
In file included from /Users/guydvir/Dropbox/Arduino/libraries/LittleFS_esp32/src/LITTLEFS.cpp:17:
/Users/guydvir/Library/Arduino15/packages/esp32/hardware/esp32/2.0.4/libraries/FS/src/vfs_api.h:38:17: note: candidate: 'virtual fs::FileImplPtr VFSImpl::open(const char*, const char*, bool)'
     FileImplPtr open(const char* path, const char* mode, const bool create) override;
                 ^~~~

```

I minimized code to headers only ( and empty `setup` and `loop`:

#include "FS.h" //#include "LITTLEFS.h" // \<----- commenting out stops the error message #include \<time.h\> #include \<WiFi.h\>

What may be the error and how to fix it ?

# Answer
As you experienced, the Lorol's LittleFS\_esp32 library was merged into ESP32 core from v1.0.6 and creates compile error to some old codes.

The difference is you have to use `#include <LittleFS.h>` instead of `#include <LITTLEFS.h>` for new cores (v1.0.6, v2.0.0+)

Check and modify the following snippet (used widely in my ESP\_WiFiManager library ) for your purpose

```
// Check cores/esp32/esp_arduino_version.h and cores/esp32/core_version.h
//#if ( ESP_ARDUINO_VERSION >= ESP_ARDUINO_VERSION_VAL(2, 0, 0) )  //(ESP_ARDUINO_VERSION_MAJOR >= 2)
#if ( defined(ESP_ARDUINO_VERSION_MAJOR) && (ESP_ARDUINO_VERSION_MAJOR >= 2) )
  #if (_WIFIMGR_LOGLEVEL_ > 3)
    #warning Using ESP32 Core 1.0.6 or 2.0.0+
  #endif

  // The library has been merged into esp32 core from release 1.0.6
  #include <LittleFS.h>       // https://github.com/espressif/arduino-esp32/tree/master/libraries/LittleFS

  FS* filesystem =      &LittleFS;
  #define FileFS        LittleFS
  #define FS_Name       "LittleFS"
#else
  #if (_WIFIMGR_LOGLEVEL_ > 3)
    #warning Using ESP32 Core 1.0.5-. You must install LITTLEFS library
  #endif

  // The library has been merged into esp32 core from release 1.0.6
  #include <LITTLEFS.h>       // https://github.com/lorol/LITTLEFS

  FS* filesystem =      &LITTLEFS;
  #define FileFS        LITTLEFS
  #define FS_Name       "LittleFS"
#endif

```
> 2 votes

# Answer
As Juraj commented - no need for `LittleFS_esp32` library, after upgrade to esp32 Arduino 2.0.4
> 0 votes

---
Tags: esp32, spiffs, littlefs
---


title: Can't upload sketch after overheating

text:
# Question
Title: Can't upload sketch after overheating
I'm using an Arduino nano, after an unfortunate event, The mega chip heat up and when I tried touching it, it burned my finger. After that, I connected to my laptop's USB port and the computer recognized it. But after I hit the upload button, the RX light flash 3 times and stop, no Loader light and it just stop there, and the IDE says this:

```
Arduino: 1.8.19 (Windows 10), Board: "Arduino Nano, ATmega328P (Old Bootloader)"

Sketch uses 2806 bytes (9%) of program storage space. Maximum is 30720 bytes.

variables use 44 bytes (2%) of dynamic memory, leaving 2004 bytes for local variables.
Maximum is 2048 bytes.

An error occurred while uploading the sketch

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x84

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x84

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

Any advice?

# Answer
Not sure what you did but you probably either overvoltage it or connected it backwards. The odds are extremely high you fried the mega chip. Good news, it is not a total waste, you learned something not to do. It is still good for practicing troubleshooting, if you find what failed great or if you cannot fix it, you will have learned something useful. Atthis point use it for practicing SMD soldering. In the end remove the parts and use the PCB for a template. The recommended solution is to purchase two more, that way if one fails the wate time will be shorter.
> 0 votes

---
Tags: arduino-ide, arduino-nano, uploading
---


title: Question about Buttons and INPUT_PULLUP

text:
# Question
Title: Question about Buttons and INPUT_PULLUP
I am ok as a developer but have very little experience if it comes to electronics/hardware. I am always too cautious and have the fear that I could wreck something with the wrong wiring. This question may sound silly to you, but I couldn't find the answer anywhere. It's probably very easy to answer.

I'd like to integrate a Push Button into my Arduino Uno Setup. The only other connections are 3 wires leading to an WS2811b Strip, standard setup. From what I have found out online, I should basically connect Digital Pin 2 (or any other) to one side/connector of the Button and GND to the other side, no Resistor, and then set the Pin Mode to INPUT\_PULLUP:

```
pinMode(BUTTON_PIN, INPUT_PULLUP);

```

This makes sense. But all tutorials I'v seen use these small black Push Buttons looking like the Reset Switch. I needed something bigger, so I bought these: https://de.aliexpress.com/item/4001095221773.html

Now the question: Should I connect these Buttons to my Arduino in the same way? Or could it be that there is some difference from one type of Push Button to the other that I have not thought about (that could probably ruin things)?

Thanks a lot!

# Answer
Yes, just connect them in the same way.

It doesn't matter what type of button you use. You could even use a wire and let it touch ground when you want a "press". That also would work correctly. The only requirement is, that the part has to make a direct connection between the digital input pin and ground when pressed and it has to release that connection when no longer pressed.
> 2 votes

# Answer
You can connect them with no external pull up resistors. If those switch wires are more than a few inches long or you are in an electrical noisy environment I would suggest an external pull up as well as the wires will act as an antenna. The internal pull ups are week so electrical noise can easily overpower them. The buttons you selected will probably oxidize over time and fail as the oxide is an insulator. To prevent that use pull up resistors that will force at least 1mA through the contacts (old school). We use to be sure we had some current through the switch when it was not a dry contact switch (those were expensive). Rule of thumb was at least 1mA more was good. This also helped reduce noise in the switch lines. Long term this is much more effective then sealing the switch.
> 1 votes

---
Tags: button
---


# Question
Title: Arduino: How to get the board type in code
I want to write a sketch that can be compiled on different Arduino boards. I want to display on the PC which board is currently connected.

This means that the user connects the PC via USB cable to the Arduino/Teensy board in which runs my sketch and my sketch tells the PC via Serial which board is connected. On the PC runs my C# application which receives this data and displays it.

Therefore I need the board that has been selected when the sketch has been compiled:

I found the code on https://github.com/backupbrain/ArduinoBoardManager but it does not give correct results (apart from the fact that several boards are missing).

Here a snippet from the code:

```
static const uint8_t BOARD_MICRO= 0x04;

....
#elif defined(__AVR_Atmega32U4__) // Yun 16Mhz, Micro, Leonardo, Esplora
  static const uint8_t BOARD = 0x04;
  static const uint8_t NUM_BITS = 8;
  static const uint16_t CPU = __AVR_Atmega32U4__;
  static const unsigned long SRAM_SIZE = 2500;
  static const unsigned long EEPROM_SIZE = 1000;
  static const unsigned long FLASH_SIZE = 32000;
#elif defined(.....

```

So this code gives the same result (BOARD = 0x04 = Micro) for Yun 16MHz, Micro, Leonardo y Esplora.

Is there any way to get in my C code exactly the string that the user has selecetd in the menu of the Arduino compiler?

# Answer
> 21 votes
Thanks to the help of Charlie Hanson and jantje I found the universal solution!

Because it is a pity that every Arduino programmer has to go through the same pain to figure out how to get the board name, I will offer my code to the public so everybody can just copy and paste it.

Here it is:

```
#if defined(TEENSYDUINO)

    //  --------------- Teensy -----------------

    #if defined(__AVR_ATmega32U4__)
        #define BOARD "Teensy 2.0"
    #elif defined(__AVR_AT90USB1286__)
        #define BOARD "Teensy++ 2.0"
    #elif defined(__MK20DX128__)
        #define BOARD "Teensy 3.0"
    #elif defined(__MK20DX256__)
        #define BOARD "Teensy 3.2" // and Teensy 3.1 (obsolete)
    #elif defined(__MKL26Z64__)
        #define BOARD "Teensy LC"
    #elif defined(__MK64FX512__)
        #define BOARD "Teensy 3.5"
    #elif defined(__MK66FX1M0__)
        #define BOARD "Teensy 3.6"
    #elif defined(__IMXRT1062__) && defined(ARDUINO_TEENSY40)
        #define BOARD "Teensy 4.0"
    #elif defined(__IMXRT1062__) && defined(ARDUINO_TEENSY41)
        #define BOARD "Teensy 4.1"
    #else
       #error "Unknown board"
    #endif

#else // --------------- Arduino ------------------

    #if   defined(ARDUINO_AVR_ADK)
        #define BOARD "Mega Adk"
    #elif defined(ARDUINO_AVR_BT)    // Bluetooth
        #define BOARD "Bt"
    #elif defined(ARDUINO_AVR_DUEMILANOVE)
        #define BOARD "Duemilanove"
    #elif defined(ARDUINO_AVR_ESPLORA)
        #define BOARD "Esplora"
    #elif defined(ARDUINO_AVR_ETHERNET)
        #define BOARD "Ethernet"
    #elif defined(ARDUINO_AVR_FIO)
        #define BOARD "Fio"
    #elif defined(ARDUINO_AVR_GEMMA)
        #define BOARD "Gemma"
    #elif defined(ARDUINO_AVR_LEONARDO)
        #define BOARD "Leonardo"
    #elif defined(ARDUINO_AVR_LILYPAD)
        #define BOARD "Lilypad"
    #elif defined(ARDUINO_AVR_LILYPAD_USB)
        #define BOARD "Lilypad Usb"
    #elif defined(ARDUINO_AVR_MEGA)
        #define BOARD "Mega"
    #elif defined(ARDUINO_AVR_MEGA2560)
        #define BOARD "Mega 2560"
    #elif defined(ARDUINO_AVR_MICRO)
        #define BOARD "Micro"
    #elif defined(ARDUINO_AVR_MINI)
        #define BOARD "Mini"
    #elif defined(ARDUINO_AVR_NANO)
        #define BOARD "Nano"
    #elif defined(ARDUINO_AVR_NG)
        #define BOARD "NG"
    #elif defined(ARDUINO_AVR_PRO)
        #define BOARD "Pro"
    #elif defined(ARDUINO_AVR_ROBOT_CONTROL)
        #define BOARD "Robot Ctrl"
    #elif defined(ARDUINO_AVR_ROBOT_MOTOR)
        #define BOARD "Robot Motor"
    #elif defined(ARDUINO_AVR_UNO)
        #define BOARD "Uno"
    #elif defined(ARDUINO_AVR_YUN)
        #define BOARD "Yun"

    // These boards must be installed separately:
    #elif defined(ARDUINO_SAM_DUE)
        #define BOARD "Due"
    #elif defined(ARDUINO_SAMD_ZERO)
        #define BOARD "Zero"
    #elif defined(ARDUINO_ARC32_TOOLS)
        #define BOARD "101"
    #else
       #error "Unknown board"
    #endif

#endif

```

You can even put this code into a new header file and #include it into your project.

P.D. If you want to know additionaly to the board also the CPU model, search for the file avr\_cpunames.h

# Answer
> 4 votes
note this is a windows mod something similar must exist on linux.

The first is quick and easy. Simply modify the platform.txt files you are using as described nelow. The draw back of this is that you will need to change platform.txt files with each release.

add -DBOARD=\\"${build.board}\\" to the recipe. This will allow for

```
   const char boardName[]=BOARD;

```

Which gives you the string "ARDUINO\_AVR\_LEONARDO" (for the leonardo) in boardName.

The second way is to switch to a better IDE (like already proposed by others). As the creator of the arduino eclipse plugin I would advice to use the arduino eclipse plugin. In the arduino eclipse plugin you do this as follows: Right click on the project-\>properties-\>arduino-\>tab "compile options" put

```
-DBOARD=\"${A.BUILD.BOARD}\"

```

in the append to C and C++ field.

This will make the code above to compile

## Adendum

I wasn't aware you wanted the "nice name". I'm not sure this can be fixed in the platform.txt in arduino IDE. In the arduino eclipse plugin change the fixe above in

```
-DBOARD=\"${A.NAME}\"

```

to get the nice name (for the leonardo "Arduino Leonardo") in the define Board.

# Answer
> 2 votes
The original answer is out of date as new boards have been added. The basic test is correct, but it's not clear where the list of boards come from.

If you locate the `boards.txt` file and look through it (eg. `~\Library\Arduino\hardware\arduino\avr\boards.txt` on a Mac), each board will have an entry along the lines of `<BOARD>.build.board=<NAME>`, so for example, the MKR1000 would have a line:

`mkr1000.build.board=SAMD_MKR1000`

The corresponding #define can be generated by prefixing the `<NAME>` with `ARDUINO_` so in this example, the following code will error for an MKR1000 board...

`#if defined(ARDUINO_SAMD_MKR1000)
 #error`

# Answer
> 1 votes
I asked a related question a while ago.

An internal \*.h file exists which is created by the IDE, and holds in it the type of board that has been selected. The list of possible options is given in the linked question, but only for AVR boards. I believe the non-AVR list is much shorter.

It is simply a matter of adding some conditional statements to send the PC the correct information. A simple example:

```
//...within your code, perhaps during setup()...
#ifdef ARDUINO_AVR_UNO
    serial.println("UNO");
#endif
#ifdef ARDUINO_AVR_LEONARDO
    serial.println("LEONARDO");
#endif
// etc...

```

If you need to refer to the board type more than once in the sketch, use the following format:

```
//...BEFORE setup(), or otherwise in the global namespace...
#ifdef ARDUINO_AVR_UNO
    #define __BOARD_TYPE "UNO"
#endif
#ifdef ARDUINO_AVR_LEONARDO
    #define __BOARD_TYPE "LEONARDO"
#endif
// etc...

// within your code, wherever necessary:
serial.println(__BOARD_TYPE);

```

The latter is much tidier, even if you only need `__BOARD_TYPE` once, as it removes the cumbersome `#ifdef` chunk from your functions.

You will, of course, have to write one for each board that you expect your end-user could have, and you will possibly need to update this list as new models appear.

# Answer
> 1 votes
For Adafruit boards, specifically a Feather M4, the following worked for me.

```
#ifdef _VARIANT_FEATHER_M4_
serial.println("Feather M4");
#endif

```

# Answer
> 0 votes
The exact names in the menu come from boards.txt file in your Arduino IDE (Arduino\hardware\arduino\avr\boards.txt). I think you would have to parse the file by yourself and find the detected board there.

---
Tags: c
---


# Question
Title: Do these bit settings all mean the same?
```
ADMUX  = ADMUX | _BV(REFS);  // uncompounded bitwise OR
ADMUX |= _BV(REFS0);         // #define _BV(bit) (1 << (bit))
ADMUX |= bit(REFS0);         // #define bit(b) (1UL << (b))
bitSet(ADMUX, REFS0);        // #define bitSet(value, bit) ((value) |= (1UL << (bit)))
sbi(ADMUX, REFS0);           // deprecated assembly?
ADMUX |= (1 << REFS0);       // shift operator
ADMUX |= (1 << 7);           // bit 7 is named REFS0
ADMUX |= 0b10000000;         // bin
ADMUX |= 0x80;               // hex
ADMUX |= 128;                // dec

```

\*under normal 8 bit Arduino circumstances?

# Answer
> 2 votes
You already got an answer in the comments but, just to make double sure, I tried compiling all these statements for an Uno, and they got all translated into the *exact same machine code*. Well, almost: I had to do some minor adjustments, which I believe are unrelated to the essence of your question. Just for completeness, I changed the following:

1. I replaced REFS0 by REFS1: on an Uno, REFS0 is bit 6, and REFS1 is bit 7.
2. I replaced REFS by REFS1, as the former is not defined.
3. I #included `<compat/deprecated.h>`, otherwise I get the error “'`sbi`' was not declared in this scope”.

---
Tags: arduino-uno, arduino-nano, bit
---


# Question
Title: Compile Error Getting when i try to read firebase data using esp32 in Arduino IDE
I am trying to read the firebase data using esp32, when i try to read firebase data statically(string literal) no error is coming.

```
String board=Firebase.getString(fbdo, F("Device/board")) ? String(fbdo.to()).c_str() : fbdo.errorReason().c_str(); //getting data successfully

```

But when i try to read data dynamically using String object, i am getting compile error for given code

```
String string2 = "Device/board";
String board1=Firebase.get(fbdo, F(string2)) ? String(fbdo.to()).c_str() :
    fbdo.errorReason().c_str();

ERROR : #define F(string_literal) (FPSTR(PSTR(string_literal)))

```

How to solve this problem?

# Answer
The macro `F()` can only be used with string literals, not with variables.

A simple solution should be (I cannot test) to provide `string2` directly. (I hope that `Firebase.get()` is overloaded.) Try this:

```
String board1 = Firebase.get(fbdo, string2) ? String(fbdo.to()).c_str() : fbdo.errorReason().c_str();

```

To save precious RAM, you might consider to use another data type for `string2`. To get a similar result, you could try:

```
const __FlashStringHelper *string2 = F("Device/board");
String board1 = Firebase.get(fbdo, string2) ? String(fbdo.to()).c_str() : fbdo.errorReason().c_str();

```

---

To gain some more insight, you might like to read this guide on PROGMEM.
> 0 votes

---
Tags: arduino-uno, esp32
---


# Question
Title: How to correctly set PWM to control servo angle in AVR?
I've stumbled upon timer configuration to handle my sg-90 servo and my Arduino UNO.

**What I did:**

1. *Set the prescaler to 64 and mode to fast PWM of 16-bit timer.*
2. *The frequency is 50hz so the ICR1 is set to 4999.*
3. *And now I don't know what to do next to set the values of OCR1A without guessing them.*

From my understanding: **If the period is now set to 20ms then for sg-90 servo:**

From documentation: http://www.ee.ic.ac.uk/pcheung/teaching/DE1\_EE/stores/sg90\_datasheet.pdf

* Angle 0 should be 1ms (1/20 = 0.05), so OCR1A = 4999 * 0.05 ~= 250
* Angle 90 should be 1.5ms (1.5/20 = 0.075), so OCR1A = 4999 * 0.075 ~= 375
* Angle 180 should be 2ms (2/20 = 0.1) so OCR1A = 4999 * 0.1 ~= 500

**But it doesn't work like that.** I've figured out that values are 125, 370, 615 - I've found these numbers in the internet (not in English language) but that guy didn't explain how he got them.

Could someone explain it to me where these numbers come from or where my calculations are incorrect.

It's not a problem with servo because with Arduino servo library everything works fine.

**Solution:**

**The document I've attached is incorrect the pulse range of miliseconds is not 1-2ms but 0.5-2.5ms and everything fits correctly.**

Below is my current code:

```
#define F_CPU 16000000UL

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdbool.h>

#define PRESCALER_64 (1 << CS11) | (1 << CS10)
#define FAST_PWM_A (1 << WGM11)
#define FAST_PWM_B (1 << WGM13) | (1 << WGM12)

int main(){

    TCCR1A = FAST_PWM_A | (1 << COM1A1);
    TCCR1B = FAST_PWM_B | PRESCALER_64;
    ICR1 = (F_CPU / 64 / 50) - 1;

    DDRB |= (1 << PB1);

    while(true){
        OCR1A = 125;
        _delay_ms(2000);
         OCR1A = 370;
        _delay_ms(2000);
        OCR1A = 615;
        _delay_ms(2000);
    }

}

```

# Answer
> 0 votes
OK, I figured it out.

The document I've attached is incorrect, the pulse range of milliseconds is not 1-2ms but 0.5-2.5ms and everything fits correctly.

---
Tags: servo, pwm, avr
---


title: Unable to terminate "void loop"

text:
# Question
Title: Unable to terminate "void loop"
I have loaded an example sketch that came with the installation of the Arduino software onto my Uno.

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

void loop() {

  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
}

```

From this time TX light is continuously on. It's remaining on even after resetting it. How do I end `void loop` so that TX light goes off.

# Answer
The implied question is how to turn off the Tx LED, which has already been answered and is probably the answer you're looking for. But the question you asked is how to end the `loop()` function. Not to be pedantic but to clarify the use of `loop`, the simple answer is, "you can't". `loop()` is called from a forever loop in the C/C++ main program, function `main()`, so returning from it, either with a `return` statement or by reaching the final close `}` causes `loop()` to be called again. This is intentional as the `main()` function in an embedded system is never supposed to return, thus it must keep re-running the application program.

Update (since this question just reappeared on the front page, I'll add the following to my answer):

`loop()` reads and prints continuously. If you had wanted that code to be executed only once, you could put in `setup()` and leave `loop()` empty. Then the sketch would initialize the serial output, read an analog value, print it - once - followed by entering the empty `loop()` and remaining there until power-down.

A way to execute the loop function once is to write an infinite loop at the end of it, so `loop()` would never return and thus never be re-executed:

```
void loop() {

  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);

  while(1)
     ;
}

```
> 8 votes

# Answer
The TX LED is on, because this sketch is periodically printing the value of the analog pin 0 onto the serial port. The LED seems to be constantly on, because the delay between two `Serial.println()` calls is only approx. 1 ms.

If you replace the 1 with 1000 for example, the TX LED should flash once per second. Start the serial monitor in your Arduino IDE too see the transmitted analog values. Delete the `Serial.` calls to remove the serial port functionality altogether.

You might want to read the documentation of the loop() and the delay() functions.
> 6 votes

# Answer
Seeing as questions about turning off the LED, and the nature of exiting `loop` have been answered, I'll also answer the question they both seem to lead to:

If the overall intention is to "turn off" the MCU, outside of turning off the power supply, it can be put into sleep mode.

Depending on how you configure the MCU before entering sleep mode, it can even be allowed to wake up on further USART communication.
> 2 votes

# Answer
Don't write code in the loop() that should be executed only a few times. Or use a counter. Or an external button. For the permanent light, increase the delay between calls.
> 2 votes

# Answer
If your question is how to terminate the execution of your void loop code at some interval, I can mention 4 solutions:

1.If you want the Void loop() to execute only once (or a set number of times using for loop), you can use "exit(O);" at the end of the Void loop. i.e.

```
Void loop(){
         //code
         exit(0);
         }

```

Disclaimer: This one might not work for all Arduino boards, but it works fine with my Arduino UNO.

2.Another way would be to keep the "Void loop()" empty and put all of your code in the Void setup function.

3. use a void loop at the end of the Void loop. E.g.

void loop(){ //code while(1){ //infinite loop } }

The arduino will remain in the infinite loop and won't be able to rerun the Void loop.

4. Create your own function and call it from the "Void Setup()" E.g.

```
 Void setup(){
  myfunc();   //calling your function
 }
  Void myfunc(){
//The code for the function you want to repeat only a set number of times
 }
 Void loop(){
 }

```

Hope someone finds it helpful.
> -1 votes

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


title: CRC8 code not working properly

text:
# Question
Title: CRC8 code not working properly
I need to send a string followed by its CRC8, 0x31 polynomial (= X^8 + X^5 + X^4 + 1), I've coded this successfully after some troubles, but it doesn't seem to work properly when I check the results. I used some online CRC calulators so check if my results are fine, but I don't get the same results, no matter what I try.

In fact, differents CRC calculators are not giving me the same results, which troubles me... Here are my trials on online CRC calculators, always using : CRC8, polynomial 0x31, data = TEMPS; (beginning of my string)

On http://www.sunshine2k.de/coding/javascript/crc/crc\_js.html :

On https://www.lddgo.net/en/encrypt/crc :

On http://zorc.breitbandkatze.de/crc.html :

It doesn't seem normal to get different results when the entry parameters are the same, it confuses me a lot. Am I missing something ?

No matter what I try, I don't get any of these results with my own code. Here is my code about CRC calculation, using RobTillaart's CRC library (https://github.com/RobTillaart/CRC):

```
   String crcData = "TEMPS;";
  int crcDataLength = crcData.length();
  char arrayForCrc[crcDataLength+1];
  crcData.toCharArray(arrayForCrc, crcDataLength+1);

  crcTrame = CRC8(0x31,0,0,false,false);
  crcTrame.add((uint8_t *)arrayForCrc, crcDataLength+1);
  String stringCrcNoHex = String(crcTrame.getCRC());
  String stringCrc = String(crcTrame.getCRC(), HEX);

```

The hex result of this code sample is 0xBA (186 decimal) I verified every input parameters with gets and prints, they're all correct :

arrayForCrc = "TEMPS;" polynomial = 0x31 StartXOR = 0 EndXOR=0 ReverseIn=false ReverseOut=false

Help would be greatly appreciated as I'm stuck and don't know what to try anymore. Thank you :)

# Answer
> 2 votes
> The hex result of this code sample is 0xBA (186 decimal)

Not so far as I can tell; it's 0xB5, which is expected for a simple reason that you'll see. And when modified slightly it matches the 0x49 value. I'm inclined to trust that your code is correct, so far as you've shown it, but your report of what's doing is not correct.

> I verified every input parameters with gets and prints, they're all correct

Well, no. As I mentioned in a comments on the question, I get the expected 0x49 on the first site you mentioned with the correct settings. I'm not sure why you're showing 0x6E. But guess what happen if I hit enter after "TEMPS;"? 0x6E. The newline character matters. Also, I *do* get a 0xBA if I use the correct input but fail to set CRC8 to custom and change 0x07 to a 0x31 in the polynomial. So, maybe that's how you found that value.

If you switch to bytes mode the site expects a sequence of character code values and ignores whitespace (apart from treating it as a delimiter). You can put 0x54 0x45 0x4d 0x50 0x53 into it in bytes mode to see 0x49 result also. You can then add 0x0D (newline) to see it to result in a 0x6E from before.

Regarding the middle site, the settings *aren't* correct (the *reverse* setting is on for input and output) and I don't see how to make them correct; they don't seem to have a custom option. However, you can turn on the reflect options on the first site to get the same result as in the 2nd site in order to convince yourself that is what is going on. The third site's output is correct for what you've put into it. It just doesn't match what you're code is actually doing.

**Your basic problem is the `+1` in this line:**

```
crcTrame.add((uint8_t *)arrayForCrc, crcDataLength+1);

```

You've included the null terminator in the calculation. This is 7 bytes: 'T', 'E', 'M', 'P', 'S', ';', '\0'. These websites just aren't doing that; they are not automatically adding a null terminator at the end of whatever you type in string mode. Alternately, if you *wanted* the null terminator in the CRC calculation, your code is fine, but you're going to need to switch to HEX input mode on the website and enter a 0x00 into it after the hex values for the other characters in *TEMPS;* so as to match. And it will match, I've tested this. You can also: put the first site into bytes mode and put "0x54 0x45 0x4d 0x50 0x53 0x3b **0x00**" into it and you will see it now produces a 0xB5, like your current code.

Otherwise, you just need to **not** enter the null terminator into the calculation:

```
crcTrame.add((uint8_t *)arrayForCrc, crcDataLength);

```

This will result in `0x49` coming out of `crcTrame.getCRC()` instead of `0xB5`:

```
#include "CRC8.h"

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

void loop() {
  String crcData = "TEMPS;";
  int crcDataLength = crcData.length();
  char arrayForCrc[crcDataLength+1];
  crcData.toCharArray(arrayForCrc, crcDataLength+1);

  auto crcTrame = CRC8(0x31,0,0,false,false);
  crcTrame.add((uint8_t *)arrayForCrc, crcDataLength);
  String stringCrcNoHex = String(crcTrame.getCRC());
  String stringCrc = String(crcTrame.getCRC(), HEX);

  Serial.println(stringCrc);
}

```

If you also want to sanity check what happened with the 0x6E output earlier, you can then change `crcData` to `String crcData = "TEMPS;\n"` (adding the newline) and watch it start printing 6E.

---

There's a `.getBytes()` function in String that is pretty much what you have without needin the cast:

```
crcTrame.getBytes(arrayForCrc, crcDataLength);

```

I'm not sure if you have a good reason for "TEMPS;" to begin life in a `String` or then to have to get it into an character array. If you're only doing this so you can then call `crcTrame.add()`, well, you needn't:

```
#include "CRC8.h"

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

void loop() {
  String crcData = "TEMPS;";
  int crcDataLength = crcData.length();

  auto crcTrame = CRC8(0x31,0,0,false,false);
  crcTrame.add(
    (const uint8_t *)crcData.c_str(),
    crcData.length() // <- Does not count null terminator.
  );
  String stringCrcNoHex = String(crcTrame.getCRC());
  String stringCrc = String(crcTrame.getCRC(), HEX);

  Serial.println(stringCrc);
}

```

Note: I'm only creating `stringCrc` to mirror what you were doing. Here, it could just as easily be `Serial.println(crcTrame.getCRC(), HEX);` and potentially in whatever context you're doing it in. The cast can also be done in a more C++ approved (though uglier way with `crcTrame.add(reinterpret_cast<const uint8_t *>(crcData.c_str()), crcData.length());`

Any sequence of any number of `add()` calls that delivers the same data in the same order into calculation will yield the same CRC. There's also an overload of `add()` that takes an individual character without needing to involve a pointer at all. So your data doesn't need to come from a `String`, nor be a null-terminated string, or character array, nor fit entirely in memory.

---
Tags: serial, programming, arduino-ide, c++, bluetooth
---


# Question
Title: PIR sensor is already high, even though it is not detecting any person
I made codes like this through tinkercad.

```
const int temperature = A0;

int pir = 7;

void setup()
{
  pinMode(pir, INPUT);

  Serial.begin(115200);
}

void loop()
{
  int pir_state = digitalRead(pir);

  int value_temp = analogRead(temperature);
  float volt = (value_temp * 5.0) / 1024.0;
  float tempC = (volt - 0.5)*100;

  if (tempC >= 22 && pir_state == 1)
  {
    Serial.print(tempC);
    Serial.println("C");
  }

  delay(1000);
}

```

And following picture is the picture of a circuit I made.

I simulated this circuit. Originally pir\_state is gonna be zero when PIR sensor is not detecting any person or object, but pir\_state is always high irrespective of detecting. I thought the value of pir went wrong, so I read pir out. Then, I found it out that pir's value is always 7 regardless of detecting.

I know this isn't a big deal to you guys, but actually I'm noob so I can't figure it out what's wrong. Please, could you help finding what's happening to this and tell me what is the problem?

Here, this is a link of the circuit I make. https://www.tinkercad.com/things/luV81NLkWKo-engineering-designcapstone-design/editel?sharecode=qsYWcgpijodDbgIpsfluJ3yUJwuN-70doPT62QNTv1Q

# Answer
Update:

@jsotola commented that Tinkercad does have some capability simulate to the PIR's behavior. So my next step would be to temporarily replace the `if(){ ...` }' block in your loop() function with a few statements that print your inputs and calculated values once per second and run that while I tweaked the simulated PIR device and the thermo-sensor (if the simulation lets you do that).

The terminal output values should lead you to what ever isn't working the way you expected it to.

You are running your program in simulation, but the PIR sensor is an active device that responds to external physical inputs (changes in infrared illumination on it) modified by sensitivity settings on the device. It's hard to simulate a device's active environment. Unless the simulation offers you a way to simulate that, too, there really isn't a way to simulate the its inputs to your program, so a constant output (as seen by your simulated code) makes sense.

Without the simulator letting you pre-program the PIR's physical environment, the only way to see a its active behavior is to use a *real* PIR, and monitor it's real output while you change its actual environment - such as waving your hand in front of it - and watch response with an Arduino, an LED (and resistor) to ground, or a DVM.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How to improve button turn on/off experience
I have simple circuit turning lights on and off on button click. It is working quite fine but there is a small issue with button click itself, it is not fully reliable. Turning lights on is pretty fine but turning them off is tricky. Basically clicking once almost never works. I need to click in the right moment to turn them off or better keep pressing the button until right moment. If I hold too long it also doesn't work or work wrongly. Here is the loop code:

```
void loop() {
    int buttonState = digitalRead(BUTTON_PIN);
    if (buttonState == 1) active = not active;

    if (active) {

       ... led setup

      FastLED.show();
      FastLED.delay(1000 / UPDATES_PER_SECOND);
    } else {
      fill_solid( leds, NUM_LEDS, CRGB::Black);
      FastLED.show();
//      FastLED.clear();
    }
}

```

What do I need to do to make it working as expected which is:

* single click turn light on
* another click or hold for a while turns light off for good and they stay off until next click

# Answer
I think that you have a couple of things going on here. Debouncing has already been mentioned and I don’t want to discount that at all – there is a ton of information on that subject.

In your case, I think it would be helpful for you to consider 1) how you are defining a button press and 2) how much processing you are doing when you are not checking for a button press.

To demonstrate, I used this simple set up with a switch:

Then I modified an example from the FastLED library to simply toggle one LED (from a 12 LED, generic, neopixel ring \[no clock\] and ran it on an UNO (I know you are using a nano, but I think it should still work) using this code.

```
#include <FastLED.h>

#define NUM_LEDS 1

int LEDon = 0;
#define DATA_PIN 6

int switchPin = 8;

CRGB leds[NUM_LEDS];

void setup() {
  // ## Clockless types ##
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);  // GRB ordering is assumed
  pinMode(switchPin, INPUT);
  // start with LED off (not strictly needed)
  leds[0] = CRGB::Black;
  FastLED.show();
}

void loop() {
  if ( digitalRead(switchPin) == HIGH) { // switch is pressed
    if (LEDon == 0) {
      LEDon = 1;
      leds[0] = CRGB::Red;
      FastLED.show();
    }
    else {
      LEDon = 0;
      leds[0] = CRGB::Black;
      FastLED.show();
    }
    while (digitalRead(switchPin) == HIGH); // wait until switch is released
  }
}

```

I don’t have much experience with this library (it does appear to be very powerful) and don’t know if you can read the state (on/off/color/intensity) of the LEDS – so I just kludged a variable (LEDon) for the example. It works fine. No missed presses and you have to release the button before you can press it again.

Note that I am doing only the minimum amount needed in between looking for a button press.

Libraries are great, but you need to understand a good deal about using them. I think that you are doing time-consuming processing that is causing you to miss presses, which is why you say “*I need to click in the right moment to turn them off or better keep pressing the button until right moment*”.

I also think that you are ill-defining a press. In the code, I am specifically looking for the button to be released. Because some time is spent processing after the button press is detected, I don’t have to explicitly debounce the switch – for this example. That does not mean that you can always get away with that.

Think about how functionally vague your definition of a press is, *• single click turn light on • another click or hold for a while turns light off for good and they stay off until next click*

I would respectfully recommend that you:

Learn as much as you can about the library. Take a look, for example, at this discussion FastLED.delay() https://github.com/FastLED/FastLED/issues/1206

Do as much as you possibly can in setup().

Do as little as you need to in-between checking for a press (or think about using interrupt).

Hope it helps.
> 0 votes

---
Tags: arduino-nano
---


# Question
Title: Why wont my custom Arduino-Micro-based board connect over USB?
I designed and printed a PCB for my MIDI controller project with a modified Arduino Micro microcontroller essentially built into the design. I swapped out the USB Micro for a USB-C type port (just using the 2.0 protocol). Although I can program the board via ICSP, including getting it to run my Arduino sketches (which I have tested by having it light up the LEDs in a certain pattern, which works as expected), and the fact that it receives power via USB, the problem is that I cannot get the device to connect to my PC over USB - it is not recognized as a USB device, and cannot seem to send or receive data over USB. I'm not sure if I've done something wrong in the design or if I am simply missing something, but could use some advice, as in order to function as intended, the board will need to be able to communicate over USB.

I have tested with various USB-A to USB-C cables and USB-A to Micro cables (tested with other Arduinos) and a Micro to USB-C adapter.

As per various instructions I found online, I connected pull-down resistors of 5.1k Ohms to CC1 and CC2, left SBU1 and SBU2 unconnected as I was planning to use 2.0 protocols to keep things simple (as a related question, can these actually be used to make use of 3.0+ protocols in a design like this with an ATMEGA32U4? Would this be considered better practice in this case and potentially bypass the error?), and wired up D- and D+ as shown in the schematic below; with a EZJZ0V500AA Varistor between each and GND and running through a 4D03WGJ0220T5E Resistor network (which I don't know much about, including whether this type of component has any polarity? I simply tried to follow how the same sort of component was used in the official Arduino Micro schematics) and finally into pins 3 and 4 of the ATMEGA32U4.

This is the original schematic of the board as it was assembled, but as a result of some power issues with this same board which I have since sorted out with help in a separate post Why wont my custom Arduino-Micro-based board receive power via USB?, I had to bypass the 5V regulator and just use VUSB as +5V, so I will put the updated schematic reflecting these changes below the original (I wouldn't think it would affect this issue, but I'm not that experienced and want to err on the side of providing as many details as possible)

Original Schematic:

Revised Schematic:

Components:

```
| Designator                                             | Value                   | Component                |
|:--------------------------------------------------------|:-------------------------|:--------------------------|
| C_ARD_1, C_ARD_2, C_ARD_6, C_ARD_9, C_ARD_10, C_ARD_11 | 100n                    | CL05B104KO5NNNC          |
| C_ARD_3, C_ARD_14                                      | 22u                     | RVT22UF16V67RV0017       |
| C_ARD_4, C_ARD_5, C_ARD_7                              | 1uF                     | CL05A105KA5NQNC          |
| C_ARD_12, C_ARD_13                                     | 22pF                    | 0402CG220J500NT          |
| D_ARD_2                                                | CD1206-S01575           | CDSU4148-HF              |
| F1                                                     | MF-MSMF050-2 500mA      | MF-MSMF050-2             |
| J3                                                     | USB_C_Receptacle_USB2.0 | KH-TYPE-C-16P            |
| L1                                                     | green                   | 19-217/GHC-YR1S2/3T      |
| L2                                                     | MH2029-300Y             | BLM21PG300SN1D           |
| ON1                                                    | blue                    | 19-217/BHC-ZL1M2RY/3T    |
| R_ARD_1, R_ARD_2, R_ARD_4, R_ARD_9                     | 10K                     | 0402WGF1002TCE           |
| R_ARD_5, R_ARD_6, R_ARD_7, R_ARD_8                     | 1K                      | 0402WGF1001TCE           |
| R_ARD_10, R_ARD_11                                     | 5.1k                    | 0402WGF5101TCE           |
| RP3                                                    | 22R                     | 4D03WGJ0220T5E           |
| RX1, TX1                                               | yellow                  | 19-213/Y2C-CQ2R2L/3T(CY) |
| T1                                                     | FDN340P/PMV48XP         | PMV48XP                  |
| T2                                                     | PMV48XP                 | PMV48XP                  |
| U1                                                     | ATMEGA32U4-XUMU         | ATMEGA32U4-MU            |
| U2                                                     | NCP1117-5               | NCP1117ST50T3G           |
| U4                                                     | LP2985-33DBVR           | LP2985-33DBVR            |
| Y3                                                     | 16MHz KX-7              | 3225-16.00-10-10-10/A    |
| Z1, Z2                                                 | CG0603MLC-05E           | EZJZ0V500AA              |

```

# Answer
Well I finally found the source of the problem, many thanks to everyone here who helped me narrow things down and kept pointing me in the right direction. After figuring out that D+ and D- were getting pulled appropriately by the chip I decided to desolder the USB port on the board, cut a USB-A 2.0 cable and solder the leads directly to the board and, suddenly, it worked. After this I realized the problem must have been with the USB port on the board and upon comparing the datasheet to my pcb file, I realized that the footprint I used and the one in the datasheet had the pins laid out in a different order.

I feel a bit embarrassed for taking up people's time on such a stupid error I made (and admittedly didn't even provide enough information for anyone to be able to figure out for me, despite all of your patience and helpful advice), but at the same time I am both relieved I figured out the problem and grateful for all the help I got on this post, I'm not sure how long it would have taken me to figure out without your suggestions. I learned a lot about the layout of arduino boards, the purposes of various components in said boards, the importance of double checking footprints, and about better practices for asking for assistance.

As a note on "post etiquette" or whatever you would call it, since everyone provided assistance in comments, I didn't see a way to close the post without answering my own question (I am new to posting here), so I hope that is an acceptable way to do so.
> 3 votes

---
Tags: usb, arduino-micro
---


# Question
Title: ESP8266 unresolved mDNS host in .local domain
I am trying to implement a mDNS for esp8266 in Arduino IDE following this guide.

https://tttapa.github.io/ESP8266/Chap08%20-%20mDNS.html

I cannot get the esp8266.local name to work - when i ping it it returns an error unresolved host and putting it in a browser also does not resolve...

The IP address does resolve though. Any advice would be greatly appreciated. I am using Mac OS High Sierra and have seen that many people have experienced this problem on both windows and mac but there does not seem to be a solution yet.

Any ideas?

Thanks x

# Answer
> 2 votes
There is a known bug in the example code you are using. The author has been notified on github but has apparently chosen to not update their published code.

You need to add the following line to the loop() { } ; section of the code : **MDNS.update();**

```
 void loop() {
    MDNS.update();
 }

```

Once you do that. it should start working. And without that there is not way to get it working.

Adding this comment for anyone following and searching for a solution to this same problem.

---
Tags: esp8266
---


title: Permission denied on upload w/ IDE 2

text:
# Question
Title: Permission denied on upload w/ IDE 2
Dealing with this very common issue on IDE v2.0.0., but not sure why.

I should be fine group-wise:

```
adm tty dialout cdrom sudo dip plugdev lpadmin lxd sambashare docker

```

I've also seen numerous suggestions to change the device's permissions directly via `chmod a+rw /dev/<device>`. This is terrible advice, but nothing is working so far, so I tried it anyway. It also doesn't work, as at some point during the upload process, the device is removed and recreated, resetting the permissions.

edit: I've also ensured that ModemManager is not running, and has been purged from the system.

Running the IDE as root always fails, including when the `--no-sandbox` argument is passed.

I'm using the AppImage download on Ubuntu 22.04, but I tried the zip download, with the same results.

edit: Previously in this spot was a note about this problem not occurring on IDE v. 1.8. That wasn't actually the case - I was just testing with a board that doesn't remove and re-create the device on upload. Using a board where that does occur (Arduino Micro in this case), the error occurs in 1.8 as well.

Using `avrdude` directly (as my normal user account) also works just fine.

Additional observation - when the device is recreated by the OS after plugging the Arduino board in, it's first created with `crw------- 1 root root` permissions, and remains in that state for a very short period of time before switching to `crw-rw----+ 1 root dialout` permissions, at which point uploads work as expected.

# Answer
> 2 votes
After a long debugging session in chat, we've determined that a udev entry installed by the `apt` package laptop-mode-tools takes a long time to run, leading to the permissions not settling on the USB device until after the IDE has attempted to upload.

This problem happens even when laptop-mode isn't enabled because you're e.g. using AC. You don't need to be actually using a laptop for this problem to occur, as laptop-mode-tools is a generic power-saving package that can be installed anywhere.

The udev rule in question is `ACTION=="add", SUBSYSTEM=="usb", RUN+="lmt-udev force"` in the file `/lib/udev/rules.d/99-laptop-mode.rules`.

Commenting out that udev rule, or changing `force` to `auto` resolves the problem for me (without needing to restart udev, or anything else).

Larger hammers that can be used to resolve this include setting `ENABLE_LAPTOP_MODE_TOOLS` to `0` in `/etc/laptop-mode/laptop-mode.conf`, or simply removing `laptop-mode-tools` from the system entirely.

@timemage gets the credit for this fix.

---
Tags: uploading, ide
---


# Question
Title: How to read and Serial.print the contents (current values) of an 8-bit register?
Currently I'm using:

```
  ADMUX = 0b01100000; //example
  for (int i = 7; i >= 0; i--) {
    Serial.print(bitRead(ADMUX, i));
  }

```

This correctly prints:

```
  01100000

```

But is there a simpler way?

Before coming up with above for loop I tried using just:

```
Serial.println(ADMUX);       //converts to integers: 96
Serial.println(ADMUX, BIN);  //leaves out leading zeros: 1100000
Serial.write(ADMUX);         //converts to ASCII char: `

```

Anything else I don't know of?

# Answer
Another option:

```
#include <LibPrintf.h>
printf("%.8b", ADMUX); //prints: 0110000

```

The LibPrintf.h library is standard included on ESP boards. %b stands for binary. .8 for 8 decimal places, which adds leading zero's to all truncated (binary) numbers.

It becomes \*simpler if you wanted to print the variable name along with it like:

```
printf("ADMUX: %.8b", ADMUX);

```

Results in:

```
ADMUX: 01100000

```

\*Simpler in the way it now only occupies a single line of code.
> 1 votes

---
Tags: arduino-uno, arduino-nano, print, registers
---


title: Odd characters in serial monitor

text:
# Question
Title: Odd characters in serial monitor
I have been recently working on a website that takes input from the arduino ie- temperature and humidity. But there is a fatal problem that I've encountered, the serial monitor spews out some garbage with some actual readings. Is there a way to eliminate this?

```
 ╰─λ cat /dev/ttyACM0
T0°C
Humidity: 39.00%
00%
Temperature: 32.70°C
Humidity: 39.00%
Temperature: 32.70°C
Humidity: 39.00%
Temperature: 32.70°C
Humidity: 39.00%
00%
Temperature: 32.70°C
Humidity: 39.00%
Temperature: 32.70°C
Humidity: 39.00%
Temperature: 32.70°C
Humidity: 39.00%
idit9.00Tempure:70°Humi: 39
emperatu32.7
Huty: 0%
idit9.00Tempure:70°umidity.00%Tratu32.7
idit9.00Tempture.70�Humi: 39
empere: 0°Cmidi39.0
atur°C
Hum9.00

```

code-

```
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>

#define DHTPIN 4

#define DHTTYPE    DHT11
DHT_Unified dht(DHTPIN, DHTTYPE);

uint32_t delayMS;

void setup() {
  Serial.begin(9600);
  sensor_t sensor;
  dht.begin();
  delayMS = sensor.min_delay / 1000;
}

void loop() {
  delay(delayMS);
  sensors_event_t event;
  dht.temperature().getEvent(&event);
  if (isnan(event.temperature)) {
    Serial.println(F("Error reading temperature!"));
  }
  else {
    Serial.print(F("Temperature: "));
    Serial.print(event.temperature);
    Serial.println(F("°C"));
  }
  dht.humidity().getEvent(&event);
  if (isnan(event.relative_humidity)) {
    Serial.println(F("Error reading humidity!"));
  }
  else {
    Serial.print(F("Humidity: "));
    Serial.print(event.relative_humidity);
    Serial.println(F("%"));
  }
}

```

board - Arduino Uno (R3)

# Answer
> 0 votes
As has been noted in the comments, you are trying to read the sensor at a rate that is too fast.

Try changing this line:

```
delayMS = sensor.min_delay / 1000;

```

to:

```
delayMS = sensor.min_delay = 1000;

```

or:

```
delayMS = sensor.min_delay = 3000;

```

This will read the sensor at a slower rate and should give you clean output.

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


# Question
Title: Opening a program in administrator with Arduino (DigiSpark/DigiSparkKeyboard)
I am quite new to Arduino and DigiSparkKeyboard so I don't know much about them. I am trying to get by DigiSpark to open CMD in administrator mode but it just doesn't work. I know that I need to get it to press control, shift and enter at the same time in order for it to run as administrator but it doesn't work. At the moment my code looks like:

```
#include "DigiKeyboard.h"
#define MOD_SHIFT_LEFT      (1<<1)  //00000010
#define MOD_GUI_LEFT        (1<<3)  //00001000
#define MOD_CONTROL_LEFT    1
#define KEY_ENTER   40
#define KEY_C       6
#define KEY_M       16
#define KEY_D       7
void setup() {
  // put your setup code here, to run once:
  DigiKeyboard.update();
  DigiKeyboard.sendKeyStroke(0);
  DigiKeyboard.sendKeyStroke(0, MOD_GUI_LEFT);
  DigiKeyboard.delay(1000);
  DigiKeyboard.sendKeyStroke(KEY_C);
  DigiKeyboard.sendKeyStroke(KEY_M);
  DigiKeyboard.sendKeyStroke(KEY_D);
  DigiKeyboard.delay(1000);
  DigiKeyboard.sendKeyStroke(MOD_CONTROL_LEFT + MOD_SHIFT_LEFT + KEY_ENTER);
}

void loop() {
  // put your main code here, to run repeatedly:

}

```

# Answer
> 1 votes
Looking at the code, the first argument should be the key, and the second the modifiers. So `DigiKeyboard.sendKeyStroke(MOD_CONTROL_LEFT + MOD_SHIFT_LEFT + KEY_ENTER);` should become:

```
DigiKeyboard.sendKeyStroke(KEY_ENTER, MOD_CONTROL_LEFT + MOD_SHIFT_LEFT);`

```

# Answer
> 1 votes
You can use this code :

Explanation of the code

Opens the side menu, then searches for CMD, then right-click on it to open it as administrator A window will appear Open as administrator Yes or No It will go to the Yes button

```
  DigiKeyboard.sendKeyStroke(0, MOD_GUI_LEFT);
  DigiKeyboard.delay(1500);
  DigiKeyboard.print("c;d");
  DigiKeyboard.delay(1500);
  DigiKeyboard.sendKeyStroke(KEY_ENTER, MOD_CONTROL_LEFT | MOD_SHIFT_LEFT);
  DigiKeyboard.delay(1000);
  DigiKeyboard.sendKeyStroke(0);
  DigiKeyboard.sendKeyStroke(KEY_ARROW_LEFT);
  DigiKeyboard.delay(500);
  DigiKeyboard.sendKeyStroke(KEY_ENTER);

```

# Answer
> -1 votes
Please use DigiKeyboard.print(cmd);

---
Tags: digispark
---


# Question
Title: Why does "Get Board Info" not work, but I can still program my Arduino Nano?
Dear Stack Exchangers,

I have been working with Arduinos for probably 10 years, and as a habit the first thing I do when I connect a device to the USB port is run the "Tools \> Get Board Info" in the Arduino IDE just to make sure I've got the correct port selected, USB cable is good, etc.

Well tonight when I connected a Nano, the "Get Board Info" didn't work at all. So after spending hours rebooting, trying different cables, etc. I eventually just tried uploading a sketch, and that worked fine! But the "Get Board Info" still does not work.

Anybody have any ideas what is going on? Thanks!

Sincerely, Ramblin' Wreck

# Answer
The classic Arduino Nano uses an FTDI chip as USB to TTL Serial adapter. Many Nano (and Uno and Mega) clones use the CH340 as USB adapter. These USB chips present themselves with id set by the USB chip manufacturer. This doesn't provide a way to identify the specific board.

Original Uno and Mega Rev 3 and some clones use ATmega16u2 as USB adapter with a firmware by Arduino. Arduino sets the USB id in the firmware so it can identify as specific board type. (People reported Mega clones which presented itself as Uno).

The boards with MCU with native USB like Leonardo, Micro and ARM boards (Zero, MKR, Nano IoT, Nano BLE) provide the USB id set in boards.txt so they can be identified too.
> 2 votes

---
Tags: arduino-nano
---


# Question
Title: I need help with code for my automated garbage bin compressor
Here is my problem, I'm working on an automated garbage bin compressor. When the garbage is near the sensor, the compressor mechanism will trigger. I'm using Arduino Uno as the controller, a 12v AC window motor, an L298N motor driver, a 12v AC battery, an ultrasonic sensor, and 2 led indicators. The flow chart is as follows the sensor will detect if there is garbage in the garbage bin, if there is no garbage then the motor will not spin. If there is garbage then the motor will start spinning for 20-30 seconds and after the motor stops spinning then it will stop for 5 seconds before returning to its original position. There are 2 LED indicators, the green indicator will indicate if the motor doesn't spin and the red LED will indicate if the motor is in use. So far I'm able to program the motor to spin in 1 direction without a command to stop.

```
const int trigpin = 11;
const int echopin = 10;
int enA = 4;
int SPEED = 250;
int motordirection1 = 3;
int motordirection2 = 2;
int duration = 0;
int distance = 0;

void setup(){
  pinMode (trigpin, OUTPUT);
  pinMode (echopin, OUTPUT);
  pinMode (enA, OUTPUT);
  pinMode (motordirection1, OUTPUT);
  pinMode (motordirection2, OUTPUT);
  pinMode (trigpin, OUTPUT);
  pinMode (echopin, INPUT);

}

void loop(){
  digitalWrite (trigpin, LOW);
  delayMicroseconds (2);
  digitalWrite (trigpin, HIGH);
  delayMicroseconds (10);
  digitalWrite (trigpin, LOW);

  duration = pulseIn (echopin, HIGH);
  distance = duration*0.034/2;

  if (distance < 1){
  digitalWrite (enA, 0);
  digitalWrite (motordirection1, LOW);
  digitalWrite (motordirection2, LOW);
  }
  else if (distance > 2 && distance <25){
  digitalWrite (enA, SPEED);
  digitalWrite (motordirection1, HIGH);
  delay (10);
  digitalWrite (motordirection2, LOW);
  delay (50);
  digitalWrite (motordirection1, LOW);
  digitalWrite (motordirection2, LOW);
  }
  else if (distance > 15){
  digitalWrite (enA, SPEED);
  digitalWrite (motordirection1, LOW);
  delay (10);
  digitalWrite (motordirection2, HIGH);
  delay (50);
  digitalWrite (motordirection1, LOW);
  digitalWrite (motordirection2, LOW);
  }
}

```

Here is the program that I have. I'm not sure if it's good or not.

EDIT: I made the adjustment in the code and it works but now the problem is the motor only moves in 1 direction when the sensor detects something but after it's out of range the motor doesn't spin back.

# Answer
You wrote:

> The flow chart is as follows \[...\]

Rather than a flow chart, you should think of your system as a finite state machine, and draw its state diagram. Superficially, a state diagram may look like a flow chart, but it has some specific properties:

* Within the states represented in the diagram, the machine does nothing but wait for some event to happen.
* Events trigger transitions between states.
* Whatever actions the machine may perform can only happen on state transitions.

Here is a state diagram that may represent your system:

In this diagram, the actions are implicit (because I am lazy), but you may want to write them down explicitly. For example, on the transition IDLE → MOVING\_FORWARD the motor should be started, and on the next transition (MOVING\_FORWARD → WAITING) it should be stopped.

Note also that this only represents *my understanding* of your specifications. You will probably have to amend it in order for it to reflect what you really want to do.

Once you have the state diagram, the next step is... to debug it! It is essential that you do this debugging *before* you start to write any line of code. At this stage I can already spot a couple of issues:

* One transition is conditioned on the “compressor” reaching its home position. This means that you will need some means to detect this event, like an endstop.
* After compressing some garbage... there is still garbage in the bin. Then, after the transition MOVING\_BACK → IDLE, garbage will be detected, the system will immediately transition to MOVING\_FORWARD, and it will get stuck in an endless loop.

Once you are done debugging the state diagram, **and only then**, can you start writing the code. I suggest you follow the steps of Majenko's tutorial on finite state machines: translating the diagram to code should be quite straight forward.
> 2 votes

---
Tags: arduino-uno
---