body:
[![Here is the wiring ][1]][1]
  [1]: https://i.stack.imgur.com/sBk8J.jpg

The image is as clear as I can make it.

Here are the basics of my problem. My program is meant to make 6 red LED lights in sequence fade in and out, toggle 5 white LED's on and off with a button, and make a servo rotate from 90 to 15 degrees on a button press, and revert to 0 degrees when the button is no longer pressed.

All of my code has compiled correctly, the LED's do what they are supposed to do, but the servo is acting strange. At first, it would move fine but then after a few button presses it would kind of spaz out and glitch back to place instead of smoothly move, which will not work for my purposes. After even more time, the servo stopped working at all. I looked around and found some answers saying to route it through an alternative power source, but I did that with the power module that came with my kit and it still refuses to move. I swapped it out with a different servo and that one won't work either, which makes me wonder if my wiring is incorrect - and yet the motor is on and makes vibrations, instead of moving, so I know power is getting through. In addition, the onboard LED's on the mega2560 are turning on and off in response to my button, so I know that's wired in correctly as well! So why won't the servo move, and why won't it respond to my button presses?

Basically, using a 3.3V - 5.0 volt Elegoo power module, how do I correctly wire the servo to only draw power from the 9v battery I attach to said module? I've seen people saying something about putting the grounds of the board and the module together but I don't know how to do that and I'm getting frustrated looking all over the internet trying to find out how so I figured I would just ask a question.

Wiring details:

The 5 white LED's are in parallel, and the red LED's are in series; they are all powered by the arduino's 5V power source, and wired into the arduino GND pin.
Servo is connected by to pin 10, and the ground and power are both routed through the 5V power module which is attached to a 9V battery. The light on the module is on, and I have used the included jumpers to make sure I'm using the 5V source and not the 3.3V one.

Here is my code:

```// Servo
#include <Servo.h>
Servo servo1;
//------------------------
// White LED's:
int wL1 = 3;
int wL2 = 4;
int wL3 = 5;
int wL4 = 6;
int wL5 = 7;
//------------------------
// Red LED's:
int rL1 = 8;
//------------------------
// Buttons:
int wLbutton = 2;
int wLreading;
int wL1state = HIGH;
int wL2state = HIGH;
int wL3state = HIGH;
int wL4state = HIGH;
int wL5state = HIGH;
int wLprevious = LOW;

int servoButton = 1;
int servoState = false;
int servoReading;
int servoPrevious = LOW;
//--------------------------
// Fading:
int brightness = 0;
int fade = 1;
//--------------------------
// Delays:
long time = 0;
long time2 = 0;
long debounce = 100;

unsigned long previousMillis = 0;
const long interval = 1000;
//--------------------------

// Setup ======================================================================================================================================

void setup()
{
  pinMode(wL1,OUTPUT);          // White LED's
  pinMode(wL2,OUTPUT);
  pinMode(wL3,OUTPUT);
  pinMode(wL4,OUTPUT);
  pinMode(wL5,OUTPUT);

  pinMode(rL1,OUTPUT);          // Red LED's

  pinMode(wLbutton, INPUT);     // Buttons
  pinMode(servoButton, INPUT);

  servo1.attach(10);
  servo1.write(90);             // Servo

  if (wL1state = HIGH)
{
  wL1state = LOW;                                                              // Set the state of the all White LED buttons to low at the beginning of the circuit (this doesnt run after the first time).
  wL2state = LOW;
  wL3state = LOW;
  wL4state = LOW;
  wL5state = LOW;
}
}

// Loop =========================================================================================================================================

void loop() {

// White LED Button -----------------------------------------------------------------------------------------------------------------------------

wLreading = digitalRead(wLbutton);                                             // Read the state of the White LED Button

if (wLreading == HIGH && wLprevious == LOW && millis() - time > debounce)      // If the button is different state from last reading and ignores noise
{
  if (wL1state == HIGH)                                                        // If the current button state of the White LED button is high
  {
  wL1state = LOW;                                                              // Set the state of the all White LED buttons to low
  wL2state = LOW;
  wL3state = LOW;
  wL4state = LOW;
  wL5state = LOW;
  }
  else {
    wL1state = HIGH;                                                           // Otherwise, set the state of the White LED button to high
  }
  time = millis();                                                             // Set the last time the button was pressed to the current time
}

digitalWrite(wL1,wL1state);
digitalWrite(wL2,wL1state);
digitalWrite(wL3,wL1state);
digitalWrite(wL4,wL1state);
digitalWrite(wL5,wL1state);

wLprevious = wLreading;                                                        // Set the previous reading of the White LED button to current reading

// Servo Button ----------------------------------------------------------------------------------------------------------------------------------

servoState = digitalRead(servoButton);

if (servoState == HIGH)
  {
    servo1.write(75);
  }
  else
  {
    servo1.write(0);
  }

// Red LED'S breathing ----------------------------------------------------------------------------------------------------------------------------

 analogWrite(rL1,brightness);                                                 // Write the set brightness to the red LED
 brightness = brightness + fade;                                              // Set new brightness to brightness value + fade value

 if (brightness <= 0 || brightness >=255)                                     // If brightness is less than 0 or more than 255
  {
  fade = -fade;                                                               // Negate the fade value, reversing the direction of the fade
  }
  delay(10);                                                                  // Wait a short delay to see the fade
}```

title: Servo motor troubles

Answers: 1

body:
> I've seen people saying something about putting the grounds of the board and the module together

Yes, I believe this is what you need to do.
>Servo is connected by to pin 10, and the ground and power are both routed through the 5V power module which is attached to a 9V battery.

From what I understand, you are wiring like this

Servo 5V - 5V Power module

Servo GND - GND Power module

Servo Signal - pin 10 Arduino

If so, you need to  make a Y-connection like this:

Servo GND - Power module GND - Arduino GND (these 3 pins should be connected together)


body: I am working in a Modbus project where I have to read modbus Holding and Input registers using ESP8266, I am using ModbusMaster232 library. I returns a response buffer array of uint16_t. I need to convert the uint16_t to double precision float. A quick test in ESP8266 shows double datatype in ESP8266 stores 8 bytes.Does anybody know how to convert four uint16_t to double in Arduino. If so please share your knowledge.

title: How to convert four uint16_t to double float IEEE754?

Answers: 1

body:
Here's a code fragment for converting a uint16_t. Expand this to work with your array of ints from the library.
Remember that on Arduino, - Uno and Mega, at least - doubles are implemented as floats. You won't get the precision you might be expecting.

    double xAsDouble;    // ** only float precision despite 'double' declaration
    uint16_t xAsInt;

    xDouble = xInt;      // the compiler knows how to make this conversion.

Update: After re-reading your question, I realize you're using an ESP8266. My comments about Uno's float precision may not apply.

Update 2: After some discussion, I've learned that the Modbus return is not 4 integers, but a double being passed as 4 words, which need to be reassembled to recreate the original double. The solution will depend on the order in which the words comprising the original double are sent.

Update 3: I suggested the OP try using this general scheme:

    // A union lets you look at memory as either (in this case) 4 ints or 1 double
    union {
       uint16_t data_out[4];
       double x;
    } buffer;

    // Assign the data from modbus using the 'int' way of viewing menmory.
    // Note I might have the ordering wrong but this is the idea:
    buffer.data_out[i] = data_in[i];

Then reading 'buffer.x' would get the 4 words of memory as a double.

... After trying both orderings, the OP reports he is obtaining the expected result,


body:
I don't know if someone has already worked with the MLX90129. Right now, I'm trying to establish the SPI protocol between MLX90129 and an Arduino. I'm using the example that it is showed in the datasheet respecting the SPI protocol where I send a write command, the address targeted, and the 2-byte data to write and then wait the required time for data writing.

So, I'm sending 0xABCD (hexadecimal) to the slave(MLX90129), and then it is supposed to read in the same wrote address and getting back 0xABCD. It happens that I don't get the desired 0xABCD on the MISO line, and all I get is 0xFF. Here's the code:

```
#include <avr/io.h>
#include <util/delay.h>
/*-------- SPI -------------
SS => PB2 => OUTPUT
MOSI => PB3 => OUTPUT
MISO => PB4 => INPUT
SCK => PB5 => OUTPUT
---------------------------- */
#define PORTSPI PORTB
#define SS      PB2
#define MOSI    PB3
#define MISO    PB4
#define SCK     PB5

#define SS_H   PORTB=(1<<SS) // SS line with high level output
#define SS_L   PORTB=(0<<SS) // SS line with low level output

#define DDR_SPI    DDRB // set the pins of PORTB as Input or Output
#define DD_SS      DDB2 // set the pin PB2 as Input or Output
#define DD_MOSI    DDB3 // set the pin PB3 as Input or Output
#define DD_MISO    DDB4 // set the pin PB4 as Input or Output
#define DD_SCK     DDB5 // set the pin PB5 as Input or Output

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

}

void loop() {
  SS_H;
  SPI_MLX90129_write(); // write 0xABCD in EERPOM #11
  SPI_MLX90129_update();// update register file
  SPI_MLX90129_read(); // read in Register #11
  Serial.println("-");
}
/*--------------------SPI_MasterInit---------------------*/
void SPI_MasterInit(void)
{

/* Set SS, MOSI and SCK output, MISO input */
DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK)|(1<<DD_SS);
/* Enable SPI, Master, set clock rate fck/16 = 1MHz */
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
//SPSR = (0<<SPI2X);
}
/*-------------------------------------------------------*/

/*-------------------SPI_MasterTransmit------------------*/
char SPI_MasterTransmit(char cData)
{
/* Start transmission */
SPDR = cData;
/* Wait for transmission complete */
while(!(SPSR & (1<<SPIF)));
/* Return Data Register */
Serial.println(SPDR, HEX);
return SPDR;
}
/*-------------------------------------------------------*/

/*-------------------SPI_MLX90129_write------------------*/
void SPI_MLX90129_write(void)
{

char write_command;
char address;
char data_MSB;
char data_LSB;
// Write EEPROM at address 0x11 with data 0xABCD
write_command=0x0E;
address=0x11;
data_MSB=0xAB;
data_LSB=0xCD;
SS_L; // SS low selects the slave for the communication
//_delay_us(0.6);
//_delay_us(1500); // delay only when MLX90129 is in sleep mode
SPI_MasterTransmit(write_command);
SPI_MasterTransmit(address);
SPI_MasterTransmit(data_MSB);
SPI_MasterTransmit(data_LSB);
//_delay_us(0.5);
SS_H; //SS high deselects the slave and end the communication
_delay_ms(17); // delay to write EEPROM
//_delay_ms(11); // delay to write EELAtch
//_delay_us(0.5);
}
/*-------------------------------------------------------*/

/*-------------------SPI_MLX90129_read-------------------*/
void SPI_MLX90129_read(void)
{
char read_command;
char address;
char data_MSB;
char data_LSB;
// Read Register at address 0x11
read_command=0x0F;
address=0x11;
data_MSB=0xFF;
data_LSB=0xFF;
SS_L; // SS low selects the slave for the communication
//_delay_us(1500); // delay only when MLX90129 is in sleep mode
// send read command and targeted address
SPI_MasterTransmit(read_command);
SPI_MasterTransmit(address);
//_delay_us(50); // delay to read EEPROM
_delay_us(2); // delay to read Register file
//_delay_us(2); // delay to read EELAtch
//_delay_us(430); // minimum delay to read ADC output
// send 0x00 (or other random data) to generate SPI clock
// and get the slave answer
data_MSB=SPI_MasterTransmit(0x00);
data_LSB=SPI_MasterTransmit(0x00);
SS_H; // SS high deselects the slave and end the communication
Serial.println(data_MSB, HEX);
Serial.println(data_LSB, HEX);
}
/*-------------------------------------------------------*/

/*------------------SPI_MLX90129_update------------------*/
void SPI_MLX90129_update(void)
{
char update_command;
// Update command =0x1C
update_command=0x1C;
SS_L; // SS low selects the slave for the communication
//_delay_us(0.6);
// send the update command
SPI_MasterTransmit(update_command);
SS_H; // SS high deselects the slave and end the communication
_delay_us(1500); // delay for the update of the registers
}
/*-------------------------------------------------------*/
```
I'm reading the value from the serial monitor, and I get slightly different values when I change the baud rate. Can that be the problem? Should I use a display to see the data coming out from the MISO line? Can the MLX90129 be damaged? I don't think the problem is the code because that code is made available by the chip producers.

MLX90129's SPI lines only support 3.3V, and as I was using an Arduino with an operating voltage of 5V, I thought that was the problem. But I also tested with an Arduino DUE, which has an operating voltage of 3.3V, and I wasn't successful. I can't figure out where the problem is.

title: MLX90129 - SPI protocol

Answers: 0


body:
I want to use L298N bridge to power up and control simple smart lock. It requires 12V power supply, so I've used L298N bridge to power this smart lock.

I removed jumper from enA pin and connected enA 12V to Arduino Nano D8 pin.

I sent value 255 through this pin but smart lock did nothing. Any suggestions?

I'm using BLE controller to send turn on/off signal from Android App (but its not relevant in this case, because **analogWrite** is called).

Lock:
https://www.aliexpress.com/item/32949292074.html

Here is code:

    #define enA 8

    void setup() {
      pinMode(enA, OUTPUT);
    }

    void loop() {
     String msg = bluetooth.read(); //using BLE controller to get message from Android app.

     if(msg == "ON"){
       analogWrite(enA, 255);
     } else if(msg == "OFF"){
       analogWrite(enA, 0);
     }

    }

Here is setup:

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

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

title: Using L298N bridge to control smart lock

Answers: 1

body:
You really don't want an L239D to control that lock. It's overkill.  The L239D is a H-bridge that is designed to drive loads in two different polarities (forward / backwards on a motor for example).

That lock is merely a spring-loaded solenoid. You give it power and it pulls the lock back. You remove power and the spring closes it again.

All you need is a simple transistor circuit just like you'd use for a relay.

----

Since you insist on using an L239D, here's a schematic for you:

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

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

<!-- End schematic -->


body:
I'm in need of a motor or continuous servo to power a winch. The motor must be continuous* and reversible, but it does not need to be fast, precise, nor bear a load when powered off. It just needs to overcome ~50 Newton of friction force (to winch open my bedroom curtains laterally).

(* it needs to, given a discrete drum (maybe max 4cm diamater), winch about 1m)

I am using a [MEGA2560 R3][1] which has a 5V port. I've tried using a 12V DC stepper motor ([24BYJ48][2]) with a standard ULN2003 controller, with a winch drum of ~2cm diameter, but it could not overcome the friction. I didn't spare much thought for the parameters of the arduino `Stepper` instance though; I just used a configuration which worked for winching lighter loads.

I'm a rookie, but I'm assuming my board cannot sufficiently power the motor(s) (I have 3), and possibly that they themselves are too weak. Hence I'm looking for a stronger motor and controller, controllable by my arduino, but which has a direct power supply (from mains). So:

- have I got this all wrong? Is it possible to arrange my 12V stepper motors to exert 50 Newton of tension, using the 5V supply from MEGA?

- is there a shield for my MEGA which can enable these motors to function in parallel?

- otherwise, is there a strong *continuous* servo with an external power supply that would work here?

  [1]: https://store.arduino.cc/arduino-mega-2560-rev3
  [2]: https://www.amazon.co.uk/gp/product/B07QYLVK9F/ref=ppx_yo_dt_b_asin_title_o03_s03?ie=UTF8&psc=1

title: Motor for a winch (with controller and external power supply)

Answers: 2

body:
"Is it possible to arrange my 12V stepper motors to exert 50 Newton of tension, using the 5V supply from MEGA?"

Huh? Do you mean can you power a 12V stepper directly from the 5V supply on an Arduino? How would that work? You need an external power supply and a motor controller that converts the 5V control signals from the Arduino to 12V. The answer is "absolutely not." Motors draw way, way too much current to be powered from an Arduino logic pin, and all but the smallest motor will draw too much current for the 5V supply line. Plus you said you were using a 12V motor. You can't run a 12V motor on 5V.

A stepper seems like the wrong tool for this job. You should be able to use a high torque 12V DC motor and an H-bridge motor controller. An H-bridge will let you run the motor forwards or backwards.

You'll probably need a motor with a gearbox, since you likely want a fairly slow turning shaft. How many newton-meters/second do you need?

body:
> Is it possible to arrange my 12V stepper motors to exert 50 Newton of tension, using the 5V supply from MEGA?

No, you should never ever power a motor through an Arduino. It can only provide a limited amount of current, before it gets fried. You need to provide the motor driver with voltage directly from your power source. You haven't stated, what you are using as a power supply. I assume, you are just using an USB port of a PC. That is also a no-go, since it will only provide 500mA at max (that's even less, than the Arduino can bear). You should power your motor with a power supply of 12V, since it is rated for that voltage. You can buy a simple wallwart for that.

Also, currently you are providing the 12V motor with only 5V, so it cannot give you it's full power. Use a power supply with the correct voltage and more than enough current capability. Though you should keep an eye on the current ratings of the ULN2003. The datasheet is not really clear, if that chip supports 12V supply voltage. Some variants like the ULN2004 seem to support it, but I'm not sure about the ULN2003. If it is not rated for 12V, you can destroy the chip that way.

We cannot know, if the motor with it's driver will be able to rotate the winch, since the seller does not name the torque of the motor. You could try to contact the seller and ask directly about this. More specialized sites, where you can buy motors, will tell you exactly, what the torque of the motor is, that you are buying. Buying a cheap part at Amazon is somewhat the lightweight variant of buying it directly from china: The documentation is a bit better, but still not great. Without documentation or information from the seller, you are stuck with just buying and trying.

> is there a shield for my MEGA which can enable these motors to
> function in parallel?

It isn't clear, what you mean by that. You can control as many motors simultaneously, as you have pins and as you have enough computation time (meaning not too much steps per second or other stuff going on in the program). As mentioned above the power has to be supplied to the drivers from outside of the Arduino, so that does not apply here.

> otherwise, is there a strong continuous servo with an external power supply that would work here?

Power supply and motors are 2 different parts, that aren't usually sold together. Also you should start with the motor: Look for a motor, that can provide the torque, that you need. Then look for a driver circuit, that can provide the functionality, is rated for the same voltage as the motor and can provide enough current for the motor (the max. motor current is also information, that a good seller will provide). Then look for a fitting power supply. Unless you are buying some kind of kit, you need to choose these parts yourself. (We don't do product recommendations here)

---

A possibility, that you might not have though about: You could buy a normal DC motor, which provides enough torque. As speed is not your biggest concern, you could buy a geared DC motor, which can be rather strong. For a driver you would need to buy or build a H-bridge controller (which is essentially just 4 transistors put together). Be sure to use a MOSFET based driver, if you want to buy a driver chip. The standard L298n is pretty lossy.

---

It seems, that you generally don't know, how to build such a project. So here are some notes, that might help you with that:

- **Connecting everything together:** In most cases (and especially when handling high current motors) you cannot get around soldering. You can buy a perfboard (cheap PCB material, with some pads already connected for ease of use), put the parts onto it and solder everything to the perfboard. Using shields as no-solder solution can only work, when you find a fitting shield and fitting motor for your requirements. That can be a far fetch. So if you want to get into electronics and Arduino, you probably should get yourself a soldering iron (there are also many tutorials about using it on the web).

- **Connecting the power supply:** When buying a walwart power supply, it will normally come with a cable attached to it. At the end of this cable may be a connector. You have 2 options: Cut the connector and solder the wires in the cable directly to your perfboard, or buy the counter part of the connector, which you then can solder to your perfboard. Depends on if you want to disconnect the power supply from the circuit or not.

As I'm suggesting here to invest in this a bit, I want to also sketch an alternative, if you just want to get it work and don't experiment (this site is full of makers, you do this for fun, but that does not have to apply to everyone):

You may be able to use a shield to do, what you want to. This might cost a more, than putting the parts together yourself, but it will safe you the investment in tools, which you might not need in future. As above you need to choose the parts fitting your requirements. Decide on the type of motors, that you want to use (if money is not such a deal, you can nearly use any motor with enough power, stepper motor, DC motor, ...). Look for a shield, that can provide the needed current and voltage to the motor.

Every motor shield has a terminal for connecting the external power supply for the motors. On good shields this is a screw terminal, so you would simply strip the cable of the power supply and put the wires of it into the screw terminal.


body:
I don't have much experience with electronics (I'm ok with programming). I have some Brickstuff lights in a Lego set. The lights are powered by 3 AA batteries. The Brickstuff documentation says that I should not connect then directly to an Arduino, as the current exceeds the Arduino limit. I want to use an Arduino to power the lights and activate them with a button, but I want to use the same power supply to feed the Arduino and the lights.

Any suggestions about what components I should use, and how to connect them? Thanks.

title: Controlling Brickstuff with Arduino

Answers: 1

body:
Transistor is likely what you want for simplicity.

Be sure to add up all your amperage requirements and then add some extra when selecting a supply.  Having too little available will make your circuit misbehave while having a supply capable of giving you more doesn't hurt.

For voltage 3×1.5V = 4.5V if the batteries are in series.  Arduino runs on 5V (USB).  I suspect you'll probably be using a 5V supply.  Both circuits have a little margin, lights usually more so.


body:
We know that, we need calibration factors (scale factors) to read current sensor data (ACS758) to arduino. I am also using voltage reader using voltage divider circuit for my project. I need to build 5 such boards and need to change calibration factor in main program everytime due to tolerance of componenets. Currently for one of my board reference_factor is 0.81 and this will change due to resistor tolerance for other boards.

Because of this issue I need to maintain 5 different codes for 5 different boards. These sensor values controls on and off of certain relays. (Not shown in the code).

can I load this referrence_factor externally through text file or as any other medium so that I need not change the code everytime.? I am using arduino Nano.

    int reference_Factor = 0.81;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
    }

    void loop() {
      // read the raw data coming in on analog pin 0:
      int lightLevel = analogRead(A0);
      // Convert the raw data value (0 - 1023) to voltage (0.0V - 5.0V):
      float voltage = lightLevel * reference_factor;
      // write the voltage value to the serial monitor:
      Serial.println(voltage);
    }

title: How to load scal factor external to the code?

Answers: 1

body:
As written in the comments you coulduse eepron, but in your scenario it has one big disadvantage: Everything has to be written at compile time (aka when you programm the Nano, you have also to fill the eeprom with the relevant values), so e.g. if you have a temperature depending factor you want to change while on the field...<br>
I would go for a SD-card reader:

  - Cheap to get (2$)
  - Easy to handle in code (read from a file is a standard function)
  - using a PC compatible file systen FAT enables reading/writing onto the SD card on a PC/other device without recompiling your code.
  - If you switch sensors for whatever reason, just write a new scale.txt file to the SD-card, insert and reboot the nano to get the new values
  - you could still use eeprom as a fallback scenario

As a tip (also mentioned in the comments by Delta_G) int for something like 0.01 is not what you want - define as float and watch out for the "conversion trap" when using with other variables not defined as float.


body:
I'm trying to program an Adafruit Trinket using avr-gcc et. al. with the Makefile from the [Bare-Arduino-Project](https://github.com/ladislas/Bare-Arduino-Project/) on macOS Catalina.

I can build projects for standard boards like the Uno, but not for the Trinket. Everything works as expected using the "official" Arduino IDE (1.18.10). In the Bare-Arduino-Project Makefile I'm specifying the Trinket as:

```
BOARD_TAG         = trinket5
BOARD_SUB         = attiny85
```

I get an error from avr-gcc that **mmcu** is not defined. I assume this is because the command line tools aren't finding the Adafruit equivalent of *boards.txt*. When I look in the Arduino IDE package I don't find the Adafruit boards in *boards.txt* or anything that looks like the definitions for the Adafruit boards (despite having added them in the IDE).

Any ideas about how to set up support for the Trinket (or other third party boards) when using command line tools?

title: Building projects on the command line using the Bare-Arduino-Project template

Answers: 1

body:
You  probably look at the wrong `boards.txt`:

    # Trinket 5V Configuration
    trinket5.name=Adafruit Trinket (ATtiny85 @ 16MHz)

this can be found in the `boards.txt` in the main directory

    C:\Users\YOUR_USER_NAME\AppData\Local\Arduino15\packages\arduino\hardware

in the sub directory

   \adafruit\avr

in the same main directory should  also be a folder named `1.8.2` (for ArduinioIDE 1.8.12) for the core files

if added via board-manager using this line in preferences/additional bord manager urls

    https://adafruit.github.io/arduino-board-index/package_adafruit_index.json

If you did a manual installation check with [this guide for pit traps](https://learn.adafruit.com/adafruit-arduino-ide-setup?view=all).<br>Details on using trinket with the [avrdude command line can be found here](https://learn.adafruit.com/introducing-trinket/programming-with-avrdude)


body:
I have been trying to rewrite an RFID tag so it is the same as my other one. I have code that will read both separately but I cannot find any already written for the MEGA2560 that will work for me. The code that works to read the RFID's is:

```
void setup()
{
  Serial.begin(9600);
  /* Enable the SPI interface */
  SPI.begin();
  /* Initialise the RFID reader */
  RC522.init();
}

void loop()
{
  /* Has a card been detected? */
  if (RC522.isCard())
  {
    /* If so then get its serial number */
    RC522.readCardSerial();
    Serial.println("Card detected:");
    for(int i=0;i<5;i++)
    {
    Serial.print(RC522.serNum[i],DEC);
    //Serial.print(RC522.serNum[i],HEX); //to print card detail in Hexa Decimal format
    }
    Serial.println();
    Serial.println();
  }
  delay(1000);
}
```

So I have been trying to mess around with code that was designed to clone the RFID that wasnt working for me before but I keep getting errors, mainly with double void looping etc. I have tried to fix the obvious issues. I am now getting an expected unqualified-id before 'if' but at this point I think I may just be making something that doesnt work. I would greatly appreciate it if someone could have a look at this and tell me where I am going wrong!
```
    /*
 * Copy the RFID card data into variables and then
 * scan the second empty card to copy all the data
 * ----------------------------------------------------------------------------
 * Example sketch/program which will try the most used default keys listed in
 * https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys to dump the
 * block 0 of a MIFARE RFID card using a RFID-RC522 reader.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 *
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

byte buffer[18];
byte block;
byte waarde[64][16];
MFRC522::StatusCode status;

MFRC522::MIFARE_Key key;

// Number of known default keys (hard-coded)
// NOTE: Synchronize the NR_KNOWN_KEYS define with the defaultKeys[] array
#define NR_KNOWN_KEYS   8
// Known keys, see: https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys
byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] =  {
    {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
    {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
    {0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
    {0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
    {0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
    {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
    {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}  // 00 00 00 00 00 00
};

char choice;
#include <SPI.h>
/* Include the RFID library */
#include <RFID.h>

/* Define the DIO used for the SDA (SS) and RST (reset) pins. */
#define SDA_DIO 9
#define RESET_DIO 8
/* Create an instance of the RFID library */
RFID RC522(SDA_DIO, RESET_DIO);

void setup()
{
  Serial.begin(9600);
  /* Enable the SPI interface */
  SPI.begin();
  /* Initialise the RFID reader */
  RC522.init();
}

  /* Has a card been detected? */
if (RC522.isCard())
  {
    /* If so then get its serial number */
    RC522.readCardSerial();
    Serial.println("Card detected:");
    for(int i=0;i<5;i++)
    {
    Serial.print(RC522.serNum[i],DEC);
    //Serial.print(RC522.serNum[i],HEX); //to print card detail in Hexa Decimal format
    }
    Serial.println();
    Serial.println();
  }
  delay(1000);
}

 //Via seriele monitor de bytes uitlezen in hexadecimaal

void dump_byte_array(byte *buffer, byte bufferSize) {
    for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
    }
}
//Via seriele monitor de bytes uitlezen in ASCI

void dump_byte_array1(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.write(buffer[i]);
  }
}

/*
 * Try using the PICC (the tag/card) with the given key to access block 0 to 63.
 * On success, it will show the key details, and dump the block data on Serial.
 *
 * @return true when the given key worked, false otherwise.
 */

bool try_key(MFRC522::MIFARE_Key *key)
{
    bool result = false;

    for(byte block = 0; block < 64; block++){

    // Serial.println(F("Authenticating using key A..."));
    status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK) {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return false;
    }

    // Read block
    byte byteCount = sizeof(buffer);
    status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
    if (status != MFRC522::STATUS_OK) {
        Serial.print(F("MIFARE_Read() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
    }
    else {
        // Successful read
        result = true;
        Serial.print(F("Success with key:"));
        dump_byte_array((*key).keyByte, MFRC522::MF_KEY_SIZE);
        Serial.println();

        // Dump block data
        Serial.print(F("Block ")); Serial.print(block); Serial.print(F(":"));
        dump_byte_array1(buffer, 16); //omzetten van hex naar ASCI
        Serial.println();

        for (int p = 0; p < 16; p++) //De 16 bits uit de block uitlezen
        {
          waarde [block][p] = buffer[p];
          Serial.print(waarde[block][p]);
          Serial.print(" ");
        }

        }
    }
    Serial.println();

    Serial.println("1.Read card \n2.Write to card \n3.Copy the data.");

    mfrc522.PICC_HaltA();       // Halt PICC
    mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD
    return result;

    start();
}

/*
 * Main loop.
 */
void loop() {
  start();

}

void start(){
  choice = Serial.read();

  if(choice == '1')
  {
    Serial.println("Read the card");
    keuze1();

    }
    else if(choice == '2')
    {
      Serial.println("See what is in the variables");
      keuze2();
    }
    else if(choice == '3')
    {
      Serial.println("Copying the data on to the new card");
      keuze3();
    }
}

void keuze2(){ //Test waardes in blokken

  for(block = 4; block <= 62; block++){
    if(block == 7 || block == 11 || block == 15 || block == 19 || block == 23 || block == 27 || block == 31 || block == 35 || block == 39 || block == 43 || block == 47 || block == 51 || block == 55 || block == 59){
      block ++;
    }

  Serial.print(F("Writing data into block "));
  Serial.print(block);
  Serial.println("\n");

    for(int j = 0; j < 16; j++){
      Serial.print(waarde[block][j]);
      Serial.print(" ");
    }
    Serial.println("\n");

  }

  Serial.println("1.Read card \n2.Write to card \n3.Copy the data.");
  start();
}

void keuze3(){ //Copy the data in the new card
Serial.println("Insert new card...");
  // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent())
        return;

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial())
        return;

    // Show some details of the PICC (that is: the tag/card)
    Serial.print(F("Card UID:"));
    dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
    Serial.println();
    Serial.print(F("PICC type: "));
    MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
    Serial.println(mfrc522.PICC_GetTypeName(piccType));

    // Try the known default keys
    /*MFRC522::MIFARE_Key key;
    for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
        // Copy the known key into the MIFARE_Key structure
        for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
            key.keyByte[i] = knownKeys[k][i];
        }
    }*/
    for (byte i = 0; i < 6; i++) {
        key.keyByte[i] = 0xFF;
    }

  for(int i = 4; i <= 62; i++){ //De blocken 4 tot 62 kopieren, behalve al deze onderstaande blocken (omdat deze de authenticatie blokken zijn)
    if(i == 7 || i == 11 || i == 15 || i == 19 || i == 23 || i == 27 || i == 31 || i == 35 || i == 39 || i == 43 || i == 47 || i == 51 || i == 55 || i == 59){
      i++;
    }
    block = i;

      // Authenticate using key A
    Serial.println(F("Authenticating using key A..."));
    status = (MFRC522::StatusCode) mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK) {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
    }

    // Authenticate using key B
    Serial.println(F("Authenticating again using key B..."));
    status = (MFRC522::StatusCode) mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_B, block, &key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK) {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
    }

    // Write data to the block
    Serial.print(F("Writing data into block "));
    Serial.print(block);
    Serial.println("\n");

    dump_byte_array(waarde[block], 16);

     status = (MFRC522::StatusCode) mfrc522.MIFARE_Write(block, waarde[block], 16);
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("MIFARE_Write() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
      }

     Serial.println("\n");

  }
  mfrc522.PICC_HaltA();       // Halt PICC
  mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD

  Serial.println("1.Read card \n2.Write to card \n3.Copy the data.");
  start();
}

void keuze1(){ //Read card
  Serial.println("Insert card...");
  // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent())
        return;

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial())
        return;

    // Show some details of the PICC (that is: the tag/card)
    Serial.print(F("Card UID:"));
    dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
    Serial.println();
    Serial.print(F("PICC type: "));
    MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
    Serial.println(mfrc522.PICC_GetTypeName(piccType));

    // Try the known default keys
    MFRC522::MIFARE_Key key;
    for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
        // Copy the known key into the MIFARE_Key structure
        for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
            key.keyByte[i] = knownKeys[k][i];
        }
        // Try the key
        if (try_key(&key)) {
            // Found and reported on the key and block,
            // no need to try other keys for this PICC
            break;
        }
    }
}
```

title: I am trying to rewrite an RFID with a MEGA2560 and a RFID-RC522

Answers: 0


body: I need to be able to create text files on my SD card that are with names longer than 8 characters (which is what the SD.h currently limits me to). A choice would be to move to the SDFat library but before considering that option, is there a way to just remove the limit on the SD.h (because my code already implements the good-old SD.h)? What would be the best way to go about this issue?

title: Is there a way to remove the 8.3 filename limitation on the SD.h library?

Answers: 1

body:
The 8.3 "limit" is not a "limit" that can be removed. It is how FAT filesystems work.  Longer filenames are a "fudge" extension overlaid on top of that fileststem structure. To be able to use them you would need to implement that extension.

Simpler to switch to a more modern implementation.  FatFS is your friend:

* LFN support, including UTF
* Faster device access
* More efficient
* Can handle more devices than just SD cards
* Can handle multiple devices at once

There is an implementation [here](https://github.com/gallegojm/Arduino-FatFs) though I don't know how good it is (I use it on chipKIT where it is bundled by default).

If you can't get FatFs then basically *anything* is better than the SD library to be brutally honest.


body:
Hi I was wondering if someone is able to help me! I am currently trying to get a strip of 10 neopixels to change colour. I want to be able to code a random neopixel in the strip to change to either red, blue, green and yellow consecutively after 2 seconds. I am relatively new to Arduino so I'm still learning. I have been using the code below and it does everything that I want it to but I would like to set the colour so they're not as randomised. I found this code online.

    #include <Adafruit_NeoPixel.h>

    #define PIN 6
    #define LED_COUNT 50
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(LED_COUNT, PIN, NEO_RGB + NEO_KHZ800);

    void setup() {
      strip.begin();
      strip.show(); // Initialize all pixels to 'off'
    }

    void loop()
    {
      randomPixelColor(100);

    }

    void randomPixelColor(int wait)
    {
      int i= random(strip.numPixels());

      uint32_t c = random(2147483647); // I have no idea what this crazy number does.
      strip.setPixelColor(i, c);
      strip.show();
      delay(1000);

    }    // end void randomPixelColor()

I don't even know if this is the right code to be using! Hopefully someone can help me cause I'm so confused.

title: Having trouble assigning colour to my neopixels

Answers: 1

body:
You already are choosing a random LED. Now you only need to define and use the colors, that you need. Define an array with the colors:

    #define COLOR_N 4
    uint32_t colors[COLOR_N] = {0x00FF0000, 0x000000FF, 0x0000FF00, 0x00FFFF00};

Also define a static or global variable to hold the current color:

    uint8_t current_color = 0;

Then use this array in `strip.setPixelColor()` with the `current_color` variable as index:

    strip.setPixelColor(i, colors[current_color]);

Now increment `current_color` for the next color. To go from yellow to red again, you can use the modulo operator `%`:

    current_color = (current_color + 1) % COLOR_N;

You can easily extend to more colors, by writing the new colors into the `colors` array and setting `COLOR_N` to the corresponding value.

---

**About the color values**: The neopixels use an RGB color model with 8 bit depth. That means, that each component (red, green and blue) occupies exactly 1 byte. Thus there are 256 steps for each component. To describe a full color, you need all three components, thus 3 bytes or 24 bits. The data type, that fits this `uint32_t` (unsigned integer with 32 bit), though the most significant byte is unused here (if you use an RGBW strip, this byte is the component for the white LEDs).

We can write the number, that is representing a full color, as a hexadecimal value. Each component occupies 2 hexadecimal digits:

    0x00RRGGBB

where `0x` is the prefix, which marks a hexadecimal number, and `RR`, `GG` and `BB` are the components red, green and blue of the color. So a full red is `0x00FF0000`, a full blue is `0x000000FF` (the leading zeros are not mandatory, but I think they help readability and comparability).

The color mixing works additive here, just like light does. All components mixed together at the same ratio gives you white, all components to zero means black. Thus you get yellow from mixing red and green the same ratio. So a full yellow is `0x00FFFF00`.


body:
I am new to Arduino programming and I would like to ask a question.

Firstly apologies if this has been answered before and I understand if it gets locked if this has been answered elsewhere.

I am trying to get three LED's (red, amber, green) to loop 5 times (in a do loop).

for this I have created a integer variable (x) and initialised the variable to 0.

I then increase x by 1 each time.

However I cannot get them to stop looping when x is greater than 5. The program does work as expected for everything else (green LED lit, wait 1 sec, Yellow LED lit, wait 1 sec, red LED lit and then loop).

       //set LED pins
    int greenPin = 13;
    int yellowPin = 12;
    int redPin = 11;

    void setup()
    {
      pinMode(greenPin, OUTPUT);      // sets the digital pin as output
      pinMode(yellowPin, OUTPUT);
      pinMode(redPin, OUTPUT);
    }

    void loop(){
    int x = 0;

     do {
      digitalWrite(greenPin, HIGH);   // sets the LED on
      delay(1000);                  // waits for a second
      digitalWrite(greenPin, LOW);
      digitalWrite(yellowPin, HIGH);    // sets the LED off
      delay(1000);
      digitalWrite(yellowPin, LOW);// waits for a second
      digitalWrite(redPin, HIGH);    // sets the LED off
      delay(1000);
      digitalWrite(redPin, LOW);
     }
       while(x<=5); {
        x = x + 1;
       }
    }

title: Do Loop query not stopping

Answers: 1

body:
Chrisl already gave the clue.

However, to add a comment with a code example I use the answer box.

In C you have more or less two kind of loops:

- for
- do / while

The first one is when you know beforehand how many iterations you have, the second when it depends on external input (e.g. when you expect a value acquired from within the loop).

In your case, you can better use the `for` loop, so you get:

    for (x = 0; x < 6; x++)
    {
       ...
    }

What this does i:

1. Initializes x to 0 (first part of the `for` statement)
2. It checks the condition `x < 5' (second part of the `for` statement). If false, it continues with the first statement after the `for` body (after the } bracket).
3. It runs the body of the loop (inside the brackets)
4. It increases x (third part of the `for` statement)
5. It continues with 2

Also it is quite common for the condition to include the start element of the ragne (x = 0), but exclude the end element of the range (x < 6), thus it runs the last time with x == 5.


body: This is a fundamental question - very new (1st post) and trying to learn.  I have a photocell connected in series with a 10kOhm resistor between 5v & Gnd (to make a voltage divider) and the divided voltage is connected to A1.  In my code, when I specify the datatype as uint8_t I get values around the 200 range, yet when I change the type to uint16_t the values change to 1000 range.  Where should I be looking to understand this behavior?

title: Data type explanation regarding analogRead of a photoresistor

Answers: 1

body:
You should keep it `uint16_t`.

See: [analogRead][1].

It shows the return value is a 10 bit number, which means a value of 0 to 1023.

If you use `uint8_t`, which is an 8 bit value, it only can store values from 0-255.
This means if the value is higher, the most significant bits are clipped/removed, and you only have the value module 256 left.

With a 16 bit value, you will have the left 6 bits unused, but this does not matter. It has the 10 bits you get from the `analogRead` function.
Example

Assume the value is 1000, which is in binary:

    11 1110 1000

Written in 16 bits (using uint16_t), move it to the right and prefix with zeros you get:

    0000 0011 1110 1000

However, if you try to store this in 8 bits (using uint8_t) you get:

    (removed) 1110 1000

Which is the value 232 instead of 1000.

Some guidelines:

- Always use a type that fits the value you want to store (in worst case).
- If you know for sure your value will be non-negative, use an unsigned type (e.g. `uint8_t`).
- If you want to preserve memory (or good practice) use a value that is not necessarily big (thus if you know a value will never be more than 1023 like in your case, don't use `uint32_t`).

  [1]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/


body:
I am using a server-client system where i send data from the server to the client to turn on a led (the onboard led). Led must be turned off using digital input (labeled 7 on the connector).
I use therefore a while loop that checks the value of the input (button press). As long as value is not equal to LOW the led remains on (i use also a second led on pin 13 as doublecheck). I assume that the while loop will be left once i press the button, unfortunately this doesn't happen. The result of the condition seems not updated (remains HIGH).
I measured the voltage on the input when pressing the button and it goes from 3.3V to 0.0V so hardware seems to be OK.
From my undestanding the while loop is always (before each loop) checking the condition ? why doesn't this happen here ? did i do something wrong ?
I must use a while because i never know in advance when the button will be pressed.

this my code :

    #include <SPI.h>
    #include <WiFiNINA.h>
    #include <utility/wifi_drv.h>
    #include "arduino_secrets.h"
    ///////please enter your sensitive data in the Secret tab/arduino_secrets.h
    char ssid[] = SECRET_SSID;        // your network SSID (name)
    char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)

    //int keyIndex = 0;            // your network key Index number (needed only for WEP)

    const int buttonPin = 7;     // the number of the pushbutton pin
    const int ledPin =  13;      // the number of the LED pin
    int buttonState;         // variable for reading the pushbutton status

    int status = WL_IDLE_STATUS;
    IPAddress ServerIP(192,168,0,157);
    WiFiClient client;

    int i;
    String response;

    void setup() {

      WiFiDrv::pinMode(25, OUTPUT); //GREEN
      WiFiDrv::pinMode(26, OUTPUT); //RED
      WiFiDrv::pinMode(27, OUTPUT); //BLUE

     pinMode(buttonPin, INPUT);
     pinMode(ledPin, OUTPUT);

      //Initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
       ; // wait for serial port to connect. Needed for native USB port only
      }
      // check for the WiFi module:
      if (WiFi.status() == WL_NO_MODULE) {
        Serial.println("Communication with WiFi module failed!");
        // don't continue
        while (true);
      }

      String fv = WiFi.firmwareVersion();
      if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
      Serial.println("Please upgrade the firmware");
      }

      // attempt to connect to Wifi network:
      while (status != WL_CONNECTED) {
        Serial.print("Attempting to connect to SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
        status = WiFi.begin(ssid, pass);
        // wait 10 seconds for connection:
        delay(10000);
      }

        // you're connected now, so print out the status:
      printWifiStatus();
    }

    void loop() {

    if (client.connect(ServerIP, 23)) {
      client.print("90");
      String response = client.readStringUntil('\n');

      Serial.println(response);

    if (response == "9") {
      buttonState = digitalRead(buttonPin);
     // Serial.println(buttonState);
      while (buttonState != LOW){
        // turn LED on:
        digitalWrite(ledPin, HIGH);
         WiFiDrv::digitalWrite(25, 255); // for full brightness
         Serial.println(buttonState);
      }
      digitalWrite(ledPin, LOW);
      WiFiDrv::digitalWrite(25, LOW); // for full brightness
            }
      }

      client.stop();
    }

    void printWifiStatus() {
      // print the SSID of the network you're attached to:
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());

      // print your board's IP address:
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
     Serial.println(ip);

      // print the received signal strength:
      long rssi = WiFi.RSSI();
      Serial.print("signal strength (RSSI):");
      Serial.print(rssi);
      Serial.println(" dBm");
    }

thanks a lot for helping me out !

title: Condition in a while loop not updated on my mkr1010

Answers: 1

body:
     while (buttonState != LOW){
        // turn LED on:
        digitalWrite(ledPin, HIGH);
         WiFiDrv::digitalWrite(25, 255); // for full brightness
         Serial.println(buttonState);
      }

You never update the value of buttonState in this while loop.  If buttonState is not LOW to get into the while loop, nothing inside the while loop will ever change it so every time it gets checked it will still not be LOW.  It's not going to surmise that you meant to read a pin just because you used that variable to read a pin once before.

But do you really need this while loop?  Couldn't you just write the led pin low when you first get a press and then write it high when it first gets released?  See the "State Change Example".  Let the loop function be the loop.  It will lead to better code.  You don't see this now because you are a novice, but you are about to paint yourself into a corner with this approach and you'll soon be rewriting the whole thing.  It's a trap that gets most new coders.  Better to get it right now.


body:
I have an Elegoo Mega2560 R3. On my Windows machine, it recognizes fine and loads exactly like a Mega2560. I have a System76 laptop running Pop_os!. When I attach the board, I cannot connect to the port in Arduino studio (reinstalled today with newest version).

When I check, I don't see the ttyACM1 device (ACM1 specifically because of items listed below).

`lsusb before plugging in`

Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 003: ID 5986:9102 Acer, Inc BisonCam,NB Pro
Bus 001 Device 002: ID 046d:c52b Logitech, Inc. Unifying Receiver
Bus 001 Device 004: ID 8087:0aaa Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

`lsusb after plugging in`

Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 003: ID 5986:9102 Acer, Inc BisonCam,NB Pro
Bus 001 Device 020: ID 2341:0010 Arduino SA Mega 2560 (CDC ACM)
Bus 001 Device 002: ID 046d:c52b Logitech, Inc. Unifying Receiver
Bus 001 Device 004: ID 8087:0aaa Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

`dmsg after plugging in`

[65178.203006] usb 1-6: new full-speed USB device number 19 using xhci_hcd
[65178.353353] usb 1-6: New USB device found, idVendor=2341, idProduct=0010, bcdDevice= 0.01
[65178.353359] usb 1-6: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[65178.353363] usb 1-6: Product: Arduino Mega 2560
[65178.353366] usb 1-6: Manufacturer: Arduino (www.arduino.cc)
[65178.353369] usb 1-6: SerialNumber: 7563331323335130F170
[65178.357650] cdc_acm 1-6:1.0: ttyACM1: USB ACM device

`ls /dev/tty*`

/dev/tty    /dev/tty23  /dev/tty39  /dev/tty54      /dev/ttyS10  /dev/ttyS26
/dev/tty0   /dev/tty24  /dev/tty4   /dev/tty55      /dev/ttyS11  /dev/ttyS27
/dev/tty1   /dev/tty25  /dev/tty40  /dev/tty56      /dev/ttyS12  /dev/ttyS28
/dev/tty10  /dev/tty26  /dev/tty41  /dev/tty57      /dev/ttyS13  /dev/ttyS29
/dev/tty11  /dev/tty27  /dev/tty42  /dev/tty58      /dev/ttyS14  /dev/ttyS3
/dev/tty12  /dev/tty28  /dev/tty43  /dev/tty59      /dev/ttyS15  /dev/ttyS30
/dev/tty13  /dev/tty29  /dev/tty44  /dev/tty6       /dev/ttyS16  /dev/ttyS31
/dev/tty14  /dev/tty3   /dev/tty45  /dev/tty60      /dev/ttyS17  /dev/ttyS4
/dev/tty15  /dev/tty30  /dev/tty46  /dev/tty61      /dev/ttyS18  /dev/ttyS5
/dev/tty16  /dev/tty31  /dev/tty47  /dev/tty62      /dev/ttyS19  /dev/ttyS6
/dev/tty17  /dev/tty32  /dev/tty48  /dev/tty63      /dev/ttyS2   /dev/ttyS7
/dev/tty18  /dev/tty33  /dev/tty49  /dev/tty7       /dev/ttyS20  /dev/ttyS8
/dev/tty19  /dev/tty34  /dev/tty5   /dev/tty8       /dev/ttyS21  /dev/ttyS9
/dev/tty2   /dev/tty35  /dev/tty50  /dev/tty9       /dev/ttyS22
/dev/tty20  /dev/tty36  /dev/tty51  /dev/ttyprintk  /dev/ttyS23
/dev/tty21  /dev/tty37  /dev/tty52  /dev/ttyS0      /dev/ttyS24
/dev/tty22  /dev/tty38  /dev/tty53  /dev/ttyS1      /dev/ttyS25

title: Linux not recoginizing Arduino Mega2560 Clone

Answers: 1

body:
Running avrdude as root works. <br>
Adding permissions to ttyACM0/ttyACM1 for everybody also works. Execute

     sudo chmod 777 /dev/ttyACM0
     sudo chmod 777 /dev/ttyACM1

and after that you should be able to compile and upload the code to the arduino
The only issue with this is that you have to run that line everytime you connect the Arduino to the USB because ttyACM0/ttyACM1 is recreated. So as pointed in the comment
if thats the case than you add dialout group to your user, log out, then log in again, you should have access to the Arduino serial.

     sudo usermod -a -G dialout yourUserName


body: I'm new to arduino and have bought a L293D motor driver shield which have no heads on the pins. I looked at the pinout and it seems that shield does not use any of the pins "by default". So will it work properly if I connect it like it isn't a shield(without mounting), because I need to use other pins and it would be nice if I don't need to solder them. I know it's some basic stuff but I want to avoid messing up at the very beginning if I don't have to. Thanks.

title: Will L293D arduino shield lose functionality if I connect it with jumpers instead of mounting on arduino?

Answers: 0


body:
**update:**
I uninstalled the portable package of Arduino IDE, completely, and installed the IDE using `sudo apt install arduino`. yes, I verified that my Nano was plugged in, the status on the bottom right says `Arduino Nano w/ ATmega328 on COM1`, but sadly the IDE won't explain to me _why_ the `Tools > Serial Port` section is still unavailable.

Also, the online version doesn't recognize the board even though it's plugged in and configured in the settings to look for a "Nano". I also used a reliable USB Hub I use for my drawing tablet, because that was one of the remedies to troubleshoot the lack of connection, and because the Hub seems to do a lot of good things around here.

**end of update**

I received an Arduino Nano as a gift a couple months ago and had to place it on a shelf as a mere dust collector, because it was not as easy as I thought it would be to get it working.
I plugged the Nano into my computer with a cable, and attempted to load an example "blink" program and it gives errors saying "no device connected" in the errors.

It does light up and flash, so I know it is receiving power, so how do I specify where the Nano is?
I am familiar with the /dev category and how to use code in Linux, but I don't know how to communicate with the Arduino, as in, know which block device the Nano is in /dev

now that Thomas has brought to my attention the "port" setting in the drop down menus, I just realized that the port is greyed out. that could be a good detail in troubleshooting this issue.

title: how do i connect my Arduino Nano to my Linux Laptop

Answers: 3

body:
In the [Arduino IDE][1], the mcu will show up in `Tools > Port`.
Your Arduino Nano will probably be visible at `/dev/ttyUSB0` or `/dev/ttyUSB1` following whatever is already plugged on USB. Make sure to select it.

Select `Nano` in `Tools > Board`.

Last step is  `Verify/Compile` your code (^R), then `Upload` (^U).

This [link][2] sounds to be a good read to start.

  [1]: https://www.arduino.cc/en/guide/linux
  [2]: https://www.arduino.cc/en/Guide/Environment

body:
I have to sadly conclude that this issue posted was for nothing. the board I was using most likely has an underlying defect (of all odds, the 45 boards my teacher was using, he gives me 1 defect board? believable.) rendering the board inoperable. I plugged the board into an entirely different laptop, downloaded and installed a full IDE for it, ran it normally, ran it in Administrator, downloaded and installed the plugin, ran the Online IDE to test that... same **exact** issues: greyed out serial port settings, and no device detected upon plugging in.

again, I apologize for this being a waste of time. I wished this was not the case and that I could make some pretty cool stuff during this quarantine mess.

I salute to all you programmers out there.... and wish you all good luck in your own endeavors in Arduino.

body: If you have managed your Linux security well, a normal user may not have access to the port where Arduino is plugged into. If so, try from terminal with "sudo arduino". (At least works for me)


body:
I have a function `SetTFgr(float T, int FGr)` to set the time and filtergrade of my LED enlarger.

It works without a problem and changes the values of `T` or `Fgr` according to the buttons I press. Both `T` and `FGr` are global variables.

Now I want to use the same funtion with different variables.
When I call the function with `SetTFgr(TExp[i], FGrExp[i])` I would expect the function to work with the values of `TExp[i]` or `FGrExp[i]` and increase/decrease these values. It does not, it appears to use the value of `T` or `Fgr` instead.

How can I get what I am after?

title: Using different variables in a function

Answers: 2

body: Parameters of functions in C++ are by value. So `T` in your function is not the variable you use to call the function. It only has the same value. Use `float& T` to pass the reference to the variable.

body:
To be clear, you want to read the values of buttons (meaning unspecified) and use those values to set a float and an int variable. Further, you want to write a function that takes a couple of parameters that specify where you want to store those button values?

That is an unusual way to use function parameters. Usually function parameters specify an input value, and then you use that value to do something. Instead, you want to have the inputs be globally available readings (button values) and have the function parameters specify where to store those values.

C and C++ function parameters are usually passed "by value". That means that what gets sent to the function is a value, not a pointer to the variable that contains that variable. Thus the called function can't change the original variable.

If you want to pass a pointer to the variable, you have to use the `&` "address of" operator to pass the variable "by reference".

Your function might look like this using C++ pass by reference syntax:

    void SetTFgr(float &T, int &FGr) {
        float input_T = //figure out button value for T
        T = input_T;
        int input_FGr = //figure out button value for Far
        FGr = input_FGr;
    }

Then you'd invoke it like this:

    SeTFgr(T, FGr);

You could also accomplish the same thing using C pointer syntax.


body:
I've been trying to build a tilt compensated compass for an autonomous Arduino car I'm building. I'm having issues with the consistency of my data.

This is the code I'm using.

    #include <Wire.h>
    #include <I2Cdev.h>
    #include <MPU6050_6Axis_MotionApps_V6_12.h>
    #define Magnetometer_addr 0x1E
    MPU6050 mpu;

    bool dmpReady = false;
    uint8_t mpuIntStatus;
    uint8_t devStatus;
    uint16_t packetSize;
    uint16_t fifoCount;
    uint8_t fifoBuffer[64];
    float prevoius_corrected_reading,corrected_reading;

    Quaternion q;
    VectorFloat gravity;
    float ypr[3];

    bool mpuInterrupt = false;

    float Xerror = 0.01;
    float Yerror = -0.385;
    float Zerror = -0.17;

    int X0, X1, Z0, Z1,Y0, Y1;
    float X, Y, Z;
    float compass_heading;

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

      Wire.beginTransmission(Magnetometer_addr);
      Wire.write(0x01);
      Wire.write(0x00);
      Wire.endTransmission();

      Wire.beginTransmission(Magnetometer_addr);
      Wire.write(0x02);
      Wire.write(0x00);
      Wire.endTransmission();

      mpu.initialize();
      //Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
      devStatus = mpu.dmpInitialize();

        mpu.setXGyroOffset(51);
        mpu.setYGyroOffset(8);
        mpu.setZGyroOffset(21);
        mpu.setXAccelOffset(1150);
        mpu.setYAccelOffset(-50);
        mpu.setZAccelOffset(1060);

        if (devStatus == 0) {

            mpu.CalibrateAccel(6);
            mpu.CalibrateGyro(6);
            //Serial.println();
            mpu.PrintActiveOffsets();
            mpu.setDMPEnabled(true);
            dmpReady = true;
            packetSize = mpu.dmpGetFIFOPacketSize();
        } else {
            //Serial.print(F("DMP Initialization failed (code "));
            //Serial.print(devStatus);
            //Serial.println(F(")"));
        }

      delay(20);

    }

    void loop() {

      compass_heading = request_compass_data();

      Serial.print("Raw compass heading is \t");
      Serial.print(compass_heading);

      Serial.print("\t\t");

      request_accel_data();

      Serial.print("YAW\t:");
      Serial.print(ypr[0] * 180/M_PI);
      Serial.print("\tROLL\t:");
      Serial.print(ypr[1] * 180/M_PI);
      Serial.print("\tPITCH\t:");
      Serial.print(ypr[2] * 180/M_PI);

      prevoius_corrected_reading = corrected_reading;

      Serial.print("\tCorrected compass heading is \t");
      float Xhor =  X*cos(ypr[2]) + Z*sin(ypr[2]);
      float Yhor =  Y*cos(ypr[1]) - Z*sin(ypr[1])*cos(ypr[2]) + X*sin(ypr[1])*sin(ypr[2]);

      corrected_reading = rad_to_deg(rad_ang(Yhor, Xhor));
      Serial.print(corrected_reading);

      Serial.print("\tFiltered compass heading is \t");

      Serial.print(0.1 * corrected_reading + 0.9 * prevoius_corrected_reading);
      Serial.println();

    }

    float rad_ang(float a, float b){
      float ang = atan2(a, b);
      if(ang<0){ang += 2*PI;}
      if(ang>2*PI){ang -= 2*PI;}
      return ang;
    }

    float rad_to_deg(float rad_in){
      return rad_in / PI * 180;
    }

    float request_compass_data(){
      //return compass heading
      Wire.beginTransmission(Magnetometer_addr);
      Wire.write(0x03);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer_addr,1);
      if (Wire.available()>=1){
      X0 = Wire.read();
      }

      Wire.beginTransmission(Magnetometer_addr);
      Wire.write(0x04);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer_addr,1);
      if (Wire.available()>=1){
      X1 = Wire.read();
      }

      Wire.beginTransmission(Magnetometer_addr);
      Wire.write(0x05);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer_addr,1);
      if (Wire.available()>=1){
      Z0 = Wire.read();
      }

      Wire.beginTransmission(Magnetometer_addr);
      Wire.write(0x06);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer_addr,1);
      if (Wire.available()>=1){
      Z1 = Wire.read();
      }

      Wire.beginTransmission(Magnetometer_addr);
      Wire.write(0x07);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer_addr,1);
      if (Wire.available()>=1){
      Y0 = Wire.read();
      }

      Wire.beginTransmission(Magnetometer_addr);
      Wire.write(0x08);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer_addr,1);
      if (Wire.available()>=1){
      Y1 = Wire.read();
      }

      X0 = X0<<8;
      Z0 = Z0<<8;
      Y0 = Y0<<8;

      X = X1 + X0;
      X -= Xerror;
      Y = Y1 + Y0;
      Y -= Yerror;
      Z = Z1 + Z0;
      Z -= Zerror;

      //Calibrated manually
      X = X * 0.00092 - Xerror;
      Y = Y * 0.00092 - Yerror;
      Z = Z * 0.00092 - Zerror;
      /*
      Serial.print("XYZ\t");
      Serial.print(X);
      Serial.print("\t");
      Serial.print(Y);
      Serial.print("\t");
      Serial.println(Z);
    */
      float dir = rad_to_deg(rad_ang(Y, X));

      return dir;

    }

    void request_accel_data(){
            if (!dmpReady) return;
        mpuInterrupt = true;

        while (!mpuInterrupt && fifoCount < packetSize) {
            if (mpuInterrupt && fifoCount < packetSize) {
              fifoCount = mpu.getFIFOCount();
            }

        }

        mpuInterrupt = false;
        mpuIntStatus = mpu.getIntStatus();
        //Serial.print("INT STATUS:\t");
        //Serial.print(mpuIntStatus);
        fifoCount = mpu.getFIFOCount();
        //Serial.print("\tFIFO COUNT:\t");
        //Serial.print(fifoCount);

        if ((mpuIntStatus & _BV(MPU6050_INTERRUPT_FIFO_OFLOW_BIT)) || fifoCount >= 1024) {

            mpu.resetFIFO();
            fifoCount = mpu.getFIFOCount();
            Serial.println(F("FIFO overflow!"));

        }

        else if (mpuIntStatus & _BV(MPU6050_INTERRUPT_DMP_INT_BIT)) {
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
            mpu.getFIFOBytes(fifoBuffer, packetSize);
            fifoCount -= packetSize;
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            mpu.resetFIFO();

        }
    }

When I have the below sensor orientation my data output(corrected_reading) varies as shown in the below graph on one complete rotation.I'm happy with this output as there is only very little inconsistency and the tilt compensation works fine too.

[![Data variation][1]][1]

[![Sensor Orientation][2]][2]

However keeping them in the above orientation within my car is not practically possible in my case.
So I tried this orientation.
[![Sensor Orientation 2][3]][3]

But no matter how I adjust my code to suit this orientation I always end up getting very inconsistent data like below.

[![second Graph][4]][4]
[![third graph][5]][5]

I'm sure that there is some mistake i'm making in the second orientation i used.The biggest problem is that the raw magnetometer output(compass_heading) also becomes inconsistent in this case.

  [1]: https://i.stack.imgur.com/WYFsp.png
  [2]: https://i.stack.imgur.com/Es7t6.png
  [3]: https://i.stack.imgur.com/3jxye.png
  [4]: https://i.stack.imgur.com/xOTb5.png
  [5]: https://i.stack.imgur.com/Pten9.png

Please give me your suggestions as to what changes I should make in order to get a smooth output with the second orientation.
Thanks in advance.

Microcontroller - Arduino Uno
Magnetometer - HMC 5983
Accelerometer - MPU 6050

title: Tilt Compensated Compass Using HMC5983 gives inconsistent output

Answers: 1

body:
As it is not possible to reproduce the errors and analyse the program in detail, the thing which jumped at me that you have no gliding error correction (or its hidden in a library) for the compass (The MPU6050 has probably one as FIFO is called but you should look it up). The method is easy to explain:

  - You take an array of lets say 20 measure points.
  - You apply FIFO First value in is the last out
  - you do gliding average over the first 15 values -> this is the orientation output
  - the last 2 are used for value validation:
    - if you get a value out of a defined data range AND the next is in the range then ditch the before value (error corection)
   - if you get a value out of a defined data range AND the next 4 values are also in the range compared tothe first out of range this will cause the array to empty and start a new gliding average with these values. (Might not be the case when driving a car but in plane models this can happen -> 180 degree turns)

Its up to you how many values you take as a base reference and how many lead to an aprupt direction change. As we are in hobby electronics you can not expect high quality value delivery sowe have to use math to get to a desired result.
Regarding the changed orientation of the magnetometer.
**EDIT**
In my experience the turning of the magnetometer upside down resultedin weird behavior and more unstable readings. I guess this is due to the elctronics shielding now from the top rather than the bottom.
For reading and error handling I looked [into this library code]((https://github.com/keepworking/Mecha_QMC5883L/blob/master/MechaQMC5883.cpp) and adapted the read routine to my needs. Also lookat the examplesfor valuable input.


body:
I'm trying to build a robot arm based on Arduino UNO and PCA9685 controlled by few potentiometers. The easiest way that I figure out and find on internet is using two Arduino's, one as master and second as slave.
This is where my question comes from, there is a way to use single Arduino UNO instead of two by using at the same time SDA and SCL with analog inputs? Maybe there is another way to do that?

That's my actual code:
```
#include <Arduino.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwmDriver = Adafruit_PWMServoDriver(0x40);

void setup()
{
  pwmDriver.begin();
  pwmDriver.setPWMFreq(51);
}

int tempPotVal = 0;
int adcPin[4] = {A0, A1, A2, A3};
int pwmRisingTime = 0;
int pwmFallingTime = 0;

void loop()
{
  for (int id = 0; id < 4; id++)
  {
    tempPotVal = analogRead(adcPin[id]);
    pwmFallingTime = map(tempPotVal, 113, 842, 102, 512);
    pwmDriver.setPWM(id, pwmRisingTime, pwmFallingTime);
  }
}
```

title: Using SDA and SCL with analog inputs at the same time

Answers: 2

body:
No. You can't. Not unless you could come up with some way of disconnecting one set of devices and connecting the other.

Instead you could add an I2C ADC chip to the existing SCL/SDA bus to expand the number of ADC channels you have available. Or use an analog MUX chip on one of the other ADC pins to expand the number of devices you could connect to it. Or you could add an SPI ADC chip to pins 10-13 (SPI bus) to give you more analog inputs.

body: I2C on Uno/Nano/Mini uses only pins labeled A4 and A5. you can still use 4 ADC pins A0 to A3 on Uno.


body:
I had purchased a simple robot (named Qu-Bot) for a school project a couple of years ago. After the project, it just went into the attic. A few days ago, I purchased an Arduino Uno and started learning the how to operate it. But, before I could purchase LEDs, sensors, LCD, etc, a total lockdown was implemented in my country due to coronavirus.

Is there a way I could program that old robot in Arduino IDE like I program my Uno?

> I'm not sure if this is useful or not, but, when I execute ```$ lsusb``` , the bot appears as ```Bus 001 Device 018: ID 067b:2303 Prolific Technology, Inc. PL2303 Serial Port```

Here's a link to some documentation of the bot:
http://www.technogravity.com/products/qu_bot/qu_bot_downloads.php

Here are photos of all the 3 chips I can see on the board of the bot:

![](https://i.stack.imgur.com/p3Rce.jpg)

![](https://i.stack.imgur.com/NLCHW.jpg)

![](https://i.stack.imgur.com/jyOUF.jpg)

title: Is there a way to reuse an old robot using arduino?

Answers: 2

body:
As to your question can I program in ArduinIDE - Yes.

- The main chip is from AVR ATMEGA16,
- the LCD is a 16x2 (pinout for use with the LCD library is enclosed)
- motor driver is (Big thanks to Juraj not a mystery) a ULN2803. Example to work with can be [found here](https://roboindia.com/tutorials/arduino-stepper-motor/).

The circuit diagram enclosed:

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

How to use in ArduinoIDE:

  - First install the driver for prolific and makes sure your OS finds the robot  (done)
 - Then install the [MightyCore which supports ATMega16](https://github.com/mcudude/MightyCore) - there are detailed instructions how to do it
- Start with a blink led example (pins from the schematic) compile and upload to test
 - Then a simple LCD example and so on.

Another posibility would be tor scrap the bot and salvage most parts.

If its feasable the [Manual](http://robokits.co.in/documentation/Qu-bot_V2_Manual.pdf) will tell you which parts can be removed without soldering

To get started you need the [USB drivers for OS](http://robokitsworld.com/downloads/Qu-Bot USB Drivers All OS.zip) and the original SW to test wether the QBot is still ok from a hardware perspective,
Than you can salvage the parts from it to use with Arduino:
[![enter image description here][2]][2]

Than you have to make a new base plate (google for pics of 2-wheel robot base plates) and get a motor driver (I recommend for a beginner a cheap motor shield like an Adafruit V2 motor shield clone 5-7$).
As you probably have downloaded ArduinoIDE latest version for your OS, get some example programs and start to play around.

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

body:
On your linked website I wasn't able to open the sample programs (404 Not Found). The site seems very outdated (it has news from 2015 on it). So I cannot be sure, how the robot is meant do be programmed.

But: The Atmega16A is a programmable microcontroller and it most likely is the brain of the robot. Depending on how the original bot was programmed, you can have 2 ways to go:

1. If it was originally build around the Arduino platform, meaning, that it already has a fitting bootloader in it, then you might be able to program directly over USB/Serial from the Arduino IDE.

2. If not you can program it with the Arduino IDE over ISP by using your Arduino Uno as a programmer. Look at [this documentation site][1] for a more detailed description, how this is done. Note, that you will most likely have to remove the Atmega from the bot for programming, since the programming can interfere with the circuit of the bot (The Atmega seems to be in a socket, so that you can remove it from there). After programming you can put it into the bot again.

In both cases you need to install the correct core for that chip in the Arduino IDE, for example by following [this guide][2] (found by a quick search, not tested). (Maybe you even can find a core specifically for that robot)

---

The other shown chips seem to be the motor drivers.

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP
  [2]: https://elementztechblog.wordpress.com/2016/10/28/mightycore-an-arduino-core-for-the-atmega16-atmega32-atmega324-and-more/


body:
I have a [Pololu 4x encoder](https://www.pololu.com/product/4761) and am trying to write some code to make it work on my Nano 33 BLE. (Interestingly enough, the issue preventing some pre-existing libraries from working for me is the same issue that I'm about to describe here...)

When I turn the motor shaft clockwise, these are the signals that I get (first bit in each pair is channel A, second bit channel B):

`11 -> 10 -> 11 -> 10 -> 11 -> 10`

Note how channel A's value never changes, and B's value toggles back and forth.

Likewise, for the counterclockwise direction:

`01 -> 11 -> 01 -> 11 -> 01 -> 11`

This is of course wrong, as [the channels' values should be something like `00 -> 10 -> 11 -> 01 -> 00` as the shaft turns](http://4.bp.blogspot.com/-w-6mSdd0s5A/UHULV8RjH_I/AAAAAAAAAok/-FBhle0uW8o/s400/ROTARY-state.png). As a matter of fact, that is exactly what I get when I run the *exact same code* on a regular Arduino Nano.

Does anyone know what's going on? Here's my code. AFAIK I'm not using interrupts incorrectly or anything, at least for the regular Nano.

```
#define PIN_A 2
#define PIN_B 3

volatile int val = 0;
volatile bool newVal = true;

void encoder() {
  int a = digitalRead(PIN_A);
  int b = digitalRead(PIN_B);
  val = ((a << 1) | b);
  newVal = true;
}

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

  pinMode(PIN_A, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(PIN_A), encoder, CHANGE);

  pinMode(PIN_B, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(PIN_B), encoder, CHANGE);
}

void loop() {
  if (newVal) {
    Serial.print(bool(val & 0b10));
    Serial.print(bool(val & 0b01));
    Serial.println();
    newVal = false;
  }
}
```

**EDIT:** After taking a look at the following diagram, it appears that the erroneous encoder patterns match those in which only rising edges are detected. So for some reason, `attachInterrupt()` is acting as if the `CHANGE` argument were `RISING` instead for the Nano BLE.

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

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

title: Problem with interrupts and 4x encoders on Nano 33 BLE

Answers: 2

body:
Best practice would be to use a single interrupt for the encoder.  BLE has a faster processor and your code is not frame-based so that just might affect it also.  This code doesn't do exactly what your code did but it will use val to track position as a number.
It can also be made a bit finer using CHANGE instead of RISING, but for debugging bare bones means less that can go wrong.

    #define PIN_A 2
    #define PIN_B 3

    volatile int val = 0;
    int oldVal;
    //volatile bool newVal = true;

    void encoder() {
      if(digitalRead(PIN_B)) ++val;
      else --val;
    }

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

      pinMode(PIN_A, INPUT_PULLUP);
      pinMode(PIN_B, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(PIN_A), encoder, RISING);
    }

    void loop() {
      if (val != oldVal) {
        oldVal = val;
        Serial.println(oldVal);
      }
      delay(500);
    }

body:
So it turns out the cause of the issue was that `attachInterrupt()`'s implementation in the nRF528x Mbed core does not properly support rising/falling edge detection as required for mode `CHANGE`. I've [opened a pull request](https://github.com/arduino/ArduinoCore-nRF528x-mbedos/pull/69) implementing the changes required and tested them with my encoder, and I can confirm that everything works properly now.

If you'd like to test the updated core yourself, you can follow the installation instructions from the repo's [`README`](https://github.com/arduino/ArduinoCore-nRF528x-mbedos) or from this very well-written [forum post](https://forum.arduino.cc/index.php?topic=634250.msg4297961#msg4297961).


body:
I have blown up 2 Arduino Nanos and I'm trying to figure out what I'm doing wrong.

In both cases, I was powering the boards with a 16V supply (I know this is high, but the regulator datasheet says it is good to 25V, and the regulator was not damaged). I unplug the supply and USB cable and then start soldering to one of the pins (A6). When I plug the board back in, the L LED does not flash, indicating the bootloader has been erased. The POW light is on and I still measure 5V, indicating the regulator is working. When I connect the board to my PC, the serial port pops up just fine. But when I try to upload a sketch, the IDE times out and says it cannot communicate with the board.

I attempted to reprogram the bootloader using a raspberry pi but avrdude also says it cannot find the device either. It looks like the microcontroller is blown.

My iron tip is grounded, so my best guess is some residual power in the supply travels through the microcontroller to my iron and shorts something out. But this seems unlikely seeing as A6 is an input and grounding it should be just fine even when the supply is fully on.

Any ideas what I could be doing wrong? FYI, I am cross-posting this on the Arduino forums.

title: Why do I keep blowing up Nanos when I solder them?

Answers: 1

body: My advice would be not to solder directly to the Nano pins.  Instead, use the appropriately sized DIL socket, and solder to the pins of that instead.   Then plug in the Nano once the soldering is complete.


body:
I am only getting this error on one of my Windows 10 PC's.   On another windows 10 PC and Mac, the board (Mega 2560) is working fine.

Any hellp or advice on this would be appreciated.

**THE PROBLEM**

After uploading the sketch and then attempting to open the serial monitor, **Java error messages (shown below) are displayed in the information window in the IDE**.  The serial monitor fails to open.  Other sketches that do not use the serial monitor work fine.

**ANYTHING UNUSUAL ABOUT THIS PC?**

The only thing that is perhaps unusual about this PC is that Serial Ports COM1: AND COM2: are real RS432 hardware serial ports.

The Ardunio IDE connects to the board via USB Serial Port **COM5**:

**REMEDIES TRIED SO FAR**

- Uninstalled and reinstalled the software (including purging Arduino settings in Documents\ folder

- Trying the board on other PC's / MAC (to verify that it is not a faulty board).  Tests confirm that board itself is fine

**THE ERROR MESSAGES**
> Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2
>  at processing.app.AbstractMonitor.<init>(AbstractMonitor.java:68)
>  at processing.app.AbstractTextMonitor.<init>(AbstractTextMonitor.java:53)
>  at processing.app.SerialMonitor.<init>(SerialMonitor.java:42)
>  at cc.arduino.packages.MonitorFactory.newMonitor(MonitorFactory.java:49)
>  at processing.app.Editor.handleSerial(Editor.java:2193)
>  at processing.app.Editor.lambda$buildToolsMenu$17(Editor.java:723)
>  at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
>  at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
>  at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
>  at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
>  at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
>  at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:842)
>  at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:886)
>  at java.awt.Component.processMouseEvent(Component.java:6539)
>  at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
>  at java.awt.Component.processEvent(Component.java:6304)
>  at java.awt.Container.processEvent(Container.java:2239)
>  at java.awt.Component.dispatchEventImpl(Component.java:4889)
>  at java.awt.Container.dispatchEventImpl(Container.java:2297)
>  at java.awt.Component.dispatchEvent(Component.java:4711)
>  at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)
>  at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
>  at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)
>  at java.awt.Container.dispatchEventImpl(Container.java:2283)
>  at java.awt.Window.dispatchEventImpl(Window.java:2746)
>  at java.awt.Component.dispatchEvent(Component.java:4711)
>  at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
>  at java.awt.EventQueue.access$500(EventQueue.java:97)
>  at java.awt.EventQueue$3.run(EventQueue.java:709)
>  at java.awt.EventQueue$3.run(EventQueue.java:703)
>  at java.security.AccessController.doPrivileged(Native Method)
>  at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
>  at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
>  at java.awt.EventQueue$4.run(EventQueue.java:733)
>  at java.awt.EventQueue$4.run(EventQueue.java:731)
>  at java.security.AccessController.doPrivileged(Native Method)
>  at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
>  at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
>  at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
>  at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
>  at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
>  at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
>  at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
>  at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

title: Java Errors thrown by Ardunio IDE when attempting to open serial monitor

Answers: 0


body:
I am trying to send a Json Object from Arduino UNO to NodeMCU using SoftwareSerial. I am using Arduino IDE. I am getting garbage value on Serial monitor of NodeMCU. Tried it with different garbage values, couldn't receive data from Arduino UNO. Below is the code. PLease help. Thank you in advance. I haven't made a common ground. I have referred this webpage [here](https://engineeringprojectshub.com/serial-communication-between-nodemcu-and-arduino).

Arduino UNO code:

        #include <SoftwareSerial.h>
        #include <ArduinoJson.h>
        SoftwareSerial s(5,6);

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

        void loop() {
         StaticJsonBuffer<1000> jsonBuffer;
         JsonObject& root = jsonBuffer.createObject();
          root["data1"] = 100;
          root["data2"] = 200;
          if(s.available()>0)
          {
           root.printTo(s);
          }
        }

NodeMCU code:

        #include <SoftwareSerial.h>
        SoftwareSerial s(D6,D5);
        #include <ArduinoJson.h>

        void setup() {
          // Initialize Serial port
          Serial.begin(9600);
          s.begin(9600);
          while (!Serial) continue;

        }

        void loop() {
          StaticJsonBuffer<1000> jsonBuffer;
          JsonObject& root = jsonBuffer.parseObject(s);
          if (root == JsonObject::invalid())
            return;

          Serial.println("JSON received and parsed");
          root.prettyPrintTo(Serial);
          Serial.print("Data 1 ");
          Serial.println("");
          int data1=root["data1"];
          Serial.print(data1);
          Serial.print("   Data 2 ");
          int data2=root["data2"];
          Serial.print(data2);
          Serial.println("");
          Serial.println("---------------------xxxxx--------------------");

        }

title: Receiving garbage value when sending a Json object from Arduino Uno to NodeMCU using SoftwareSerial

Answers: 1

body:
The problem with ArduinoJson.h is that it doesn't ensure robust and reliable transfer over UART serial.

Instead, you should use [SerialTransfer.h][1] to automatically packetize and parse your data for inter-Arduino communication without the headace.The library is installable through the Arduino IDE and includes many examples.

Here are the library's features:

> This library:
>
>  - can be downloaded via the Arduino IDE's Libraries Manager (search "SerialTransfer.h")
>  - works with "software-serial" libraries
>  - is non blocking
>  - uses packet delimiters
>  - uses consistent overhead byte stuffing
>  - uses CRC-8 (Polynomial 0x9B with lookup table)
>  - allows the use of dynamically sized packets (packets can have payload lengths anywhere from 1 to 254 bytes)
>  - can transfer bytes, ints, floats, and even structs!!

Example TX Arduino Sketch:

    #include "SerialTransfer.h"

    SerialTransfer myTransfer;

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

    void loop()
    {
      char buff[] = "hi";

      myTransfer.txObj(buff, sizeof(buff));
      myTransfer.sendData(sizeof(buff));
      delay(100);
    }

Example RX Arduino Sketch:

    #include "SerialTransfer.h"

    SerialTransfer myTransfer;

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

    void loop()
    {
      if(myTransfer.available())
      {
        char buff[40];

        myTransfer.rxObj(buff, sizeof(buff));

        Serial.println("New Data: ");
        Serial.write(buff, sizeof(buff));
        Serial.println();
      }
      else if(myTransfer.status < 0)
      {
        Serial.print("ERROR: ");

        if(myTransfer.status == -1)
          Serial.println(F("CRC_ERROR"));
        else if(myTransfer.status == -2)
          Serial.println(F("PAYLOAD_ERROR"));
        else if(myTransfer.status == -3)
          Serial.println(F("STOP_BYTE_ERROR"));
      }
    }

  [1]: https://github.com/PowerBroker2/SerialTransfer


body:
I'm trying to run the [MIDI example from Arduino.CC](https://www.arduino.cc/en/Tutorial/MidiDevice) in Arduino Studio.

I am using an Arduino Leonardo, which has USB HID capabilities. I have installed the library as mentioned:

[![MIDI Library installed][1]][1]

When I press the compile or upload button, it says:

    'D3' was not declared in this scope

What's wrong? How do I fix this?

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

title: C3 not declared in this scope when running MIDI example code

Answers: 1

body:
The pitches for the notes are taken from [pitchToNote.h](https://github.com/arduino-libraries/MIDIUSB/blob/master/src/pitchToNote.h). In there you can see definitions for the notes like:

    #define pitchC3  48

It seems that the names were changed from `C3` to `pitchC3`.

I am not 100% sure, but my guess is that this was done to avoid conflicts between the note `A3` and the analog input `A3` (and silimar).

So, in line 25 of the example code, add `pitch` for all notes:

    const byte notePitches[NUM_BUTTONS] = {pitchC3, pitchD3, pitchE3, pitchF3, pitchG3, pitchA3, pitchB3};


body:
I have an Arduino pro mini and I tested digital write of an pin and it is 3.2V and then I connected it to a 3V motor, but when I connected the motor to it, The voltage drops under 0.2 Volt, Can any one describe the science behind voltage drop ?

I know I've better use a transistor and separate the motor power but, what you should do when you have a single 3V power source? and I know there are some motor driver chips, but is it possible to keep it simple?

title: Why can't I use 3V output of arduino pro mini?

Answers: 2

body:
**NEVER** drive a motor directly from an Arduino IO pin.  You **will** kill the Arduino.

It's not a question of voltage, it's a question of current, and that is where the transistor comes in.  If you have a 3.3V Arduino (as it sounds like you have) then you *may* be able to drive the motor using the 3.3V output of the Arduino (VCC pin? Not sure with that model) and a transistor. That is the *simplest* arrangement.

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

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

<!-- End schematic -->

body:
You can drive the motor from the same 3v supply that powers your Arduino (assuming the supply can deliver enough current for both). What you can't do is power the motor *through* the Arduino, neither from a pin, nor from its on-board voltage-regulator. And especially don't try to use a 5v Arduino's 3v pin to drive it. Their 3v regulators provide only a limited amount of current.

If you try to drive a motor through the Arduino and it needs too much current, you risk frying the Arduino. If you supply the motor from the same power supply but not through the Arduino, and the motor takes too much current, the worst that will happen is the supply voltage will fall and Arduino will shut down.


body: I want to build a remote with Arduino Nano. I have viewed many tutorials in the web, but I don't have the IR Receiver (TSOP1740). Is there any way to use Jjust an IR Led as the receiver?

title: IR Remote with Arduino

Answers: 2

body:
No, you can't use *just* an IR LED as the receiver.  While it is true that an IR LED can also be an IR receiver the voltages it generates are really really small. So you would need an amplification circuit. On top of that the TSOP1740 includes a band-pass filter to isolate the carrier frequency of the transmitted signal from the background light, which you would *also* need to implement.

So yes, while you *could* use an IR LED as a receiver, you need a large amount of support circuitry with it (which takes expertise not relevant to this website) to get it to do anything useful.

body:
You could make a remote without a receiver.  It would require knowing what signals to send.  The receiver is to essentially help in training your arduino by letting it detect the signal from an already working remote and then replay it on the LED.

You can't make a receiver with JUST an LED. (Majenko's got this one covered).


body:
I am trying to use a micro SD card in order to store data sent from an arduino UNO.
My setup consists of:

 - Arduino UNO (5V logic), powered directly from USB cable
 - [Digilent Full-sized SD Card Slot][1]
 - Simple microSD to SD adapter
 - Transcend 4GB microSD card SDHC
 - [TXB104 Logic Level Converter][2]
 - USB-powered PSU, that provides both the 3.3Volts and the 5Volts

The above components are connected as mentioned below:
Pins 1 to 4 of the Digilent SD module are driven to the 3.3Voltage side of the logic level converter. Also the SD module is powered with 3.3Volts. The 4 signals (SS, MOSI, MISO, SCK) are then taken from the 5Volt side of the logic level converter and are driven to the arduino UNO pins 10, 11, 12 and 13 respectively. Also, all the components have a common ground. The card is formatted to FAT32 using the [SD card Formatter][3] from sdcard.org.

In the arduino, I upload the SdInfo sketch of the Sdfat library. The result I get is the following:

[![enter image description here][4]][4]

Let me know if I can provide any more info.

  [1]: https://store.digilentinc.com/pmod-sd-full-sized-sd-card-slot/
  [2]: https://www.ti.com/lit/ds/symlink/txb0104.pdf?ts=1587925861218
  [3]: https://www.sdcard.org/downloads/formatter/eula_windows/index.html
  [4]: https://i.stack.imgur.com/dBW2Q.png

title: SD card with arduino UNO

Answers: 1

body:
I doubt the SDHC card is supported.

I don't have the same card slot reader, however, mine only worked with 'old' SD cards, not SDHC, SDXC etc.

So try an old one to see if it works (at least you rule out this option).