text:
Servo motor troubles

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:
#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
}```

When you say 9V battery, do you mean one of those rectangle shaped alkaline ones with two terminals on top?  Those aren't really good for powering motors or servos.  They can't really produce much current.  They're the equivalent of 6AAAA batteries.  I don't know if this is all of your problem but you should use some AA or AAA and you will have a better time of it.

Show us your circuit.  That should seem obvious since you said that you thought the fault may be in the wiring.  Do you have a pull-down resistor for the buttons?  Why don't you have them wired the normal way to read LOW when pressed so you can use the internal pull-ups and don't have to have extra resistors?

is the servo problem repeatable? ... does the servo work correctly after a reset and then degrades after a few button presses?

@Delta_G Thank you for the info on the 9V battery, yes that's the kind I am using. I'll have to buy a AA or AAA battery pack. How many of those do I need to power the servo then?
As for your second comment, the reasoning behind my white LED's having multiple resistors is that in the future I want them to turn on in sequence with a short time period between each consecutive light, rather than all at once, but I just haven't figured out how to do that yet. I'll leave that to a separate question. I'll attach a photo to my post if that helps.

@jsotola no, it won't work at all currently, even after a reset.

Why are you talking about resistors on leds?  I didn't ask about that.  I asked if you had a pull-down resistor for your button or is your button floating when it isn't pressed?  If that's the case then it may be reading noise and registering presses when you aren't actually pressing it.  The question was, why didn't you wire your button the normal way so that it reads LOW when it is pressed so that you don't need extra resistors for the buttons.  If you wire the right way then you don't need resistors at all for the buttons.  .  Please read carefully.  I never mentioned resistors on leds.

@Delta_G Ok chill. I misunderstood, it's not the end of the world. I have a pull down resistor as you can see in the image. I don't know what you mean by 'extra resistors' if you aren't talking about the LED's, I only have one for the button.

@Delta_G I already fixed the problem so I'm closing the question. Please don't be so blunt in your comments. I'm new and I'm doing my best.

Sorry, I didn't mean to be unchill.  Just to point out that you had misunderstood.  The extra resistors I'm talking about are the ones that are supposed to be on the buttons.
When I asked at first I didn't know if they were there.  If you wired your buttons the right way round you wouldn't need them.  But with the buttons wired to go HIGH when pressed you must have pull-down resistors or you'll get random noise presses of your button when nobody is pressing it.

I think you read my comment with some sort of emphasis in your head and responded to THAT not being chill.  I don't read anything there other than trying to tell you that you had misunderstood me and trying to clarify what I was talking about.  On the internet when speaking in text you can't hear someone's inflection, so it is important not to think that they wrote it in the same voice that you hear in your head.

No matter how it is communicated, saying something like 'Please read carefully' will always bring people's defenses up. Try changing your way of communicating so that doesn't happen. Instead you could say something like "i think you misunderstood, let me clarify.' instead you settled for 'why are you talking about x' and 'read more carefully, i never mentioned x'. I like getting help from people, but the way you said things felt insulting, and i'm sure i wouldn't be alone feeling that way if you said to someone else.

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)

I've connected the three together and still nothing. I have noticed that as soon as i connect the servo to the power module, the green light turns off. Is this a result of the power of the 9V not being enough?

You can see in the photo I attached in the post on the left, the Y connection you mentioned.

Hmm before anything I see a weird thing in your image. In your Y connection you are connecting the yellow wire from servo. Are you sure it's the GND wire?

And I also recommend you do this way. First, remove all LEDS and try to make your servo work. Then, you can add LEDs. That way you can easily figure out where the problem is. Just divide into steps, don't try to combine everything at start.

That was the issue. It worked and began responding again one I fixed the y connection. Then I got my 9v dc plug and using that the servo began working. Thank you so much.

You're welcome!


text:
How to convert four uint16_t to double float IEEE754?
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.

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,

Thanks for reply @JRobert but I am using uint16_t array with 4 elements not a single uint16_t variable, I have to group this four 16 bit containers to a single 64 bit container representing IEEE754 float variable. Could you elaborate how the code would do that

Do you understand how to use a for() loop to execute one or more statements over the members (items) in an array?

Do you mean
uint16_t data_in={2121,1233,3435,2433}; double data_out=0; for(int i=0; i<4;i++) { data_out = data_out | data_in[i]<<16; }

Yes - please see my edited comment above. You would do the same as in my example, but using [i] to address each of the ints and floats.

Is that code correct @JRobert ?

Take out the left shift - all you need is a simple assignment. The compiler knows from your declarations that 'data_out' is double and 'data_in' is uint_16, and how to assign one to the other, including the proper conversion.

Will try as you said in my ESP8266 board and revert back @JRobert

As I expected I am getting the value of last element in array with decimal @JRobert

Let us continue this discussion in chat.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
MLX90129 - SPI protocol
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.

Is there a specific reason why you're not using the SPI library?

Are you saying that you had it connected to 5V at one point?  It may be fried then.

I have also tested with the SPI library, and it gives the same result. I didn't connect it directly to the Arduino. I used a level shifter to drop down the voltage from 5V to 3.3V. However, this MLX90129 was used by another person before me. Possibly it's damaged. I don't know what this person made with the MLX90129. @Delta_G

I have also tested with the SPI library, and it gives the same result. I didn't connect it directly to the Arduino. I used a level shifter to drop down the voltage from 5V to 3.3V. However, this MLX90129 was used by another person before me. Possibly it's damaged. I don't know what this person made with the MLX90129. @Majenko

Not your problem at the moment, bit a hint for the future: set a bit by SS_H|=(1<<SS), clear a bit by SS_L&=~(1<<SS). Otherwise you clear all bits in the register.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Using L298N bridge to control smart lock
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:

https://majenko.co.uk/blog/importance-sharing-grounds

Also: you need to control the direction pins or it won't know what to do.

So I have to ground everything including BLE controller through breadboard like this? https://i.imgur.com/ZueUc82.png (and I'm powering Arduino through USB port)

that item from aliexpress is not a smart lock ... it is a solenoid

It looks to me like you failed to tie the grounds of the Arduino and the H-Bridge together.

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:

simulate this circuit – Schematic created using CircuitLab

I understand that but I dont have time to buy transistor and everything is delayed due to corona. I know that its overkill :D Also I have to apply power to IN1 pin too? IN1 ---- D9 and digitalWrite(9, HIGH); ?

And IN2, which has to be the opposite level to IN1. IN1 and IN2 define the direction of current flow through the load. EN1 defines the level of current through the load.

Ive tried to connect ground pins through breadboard but now L298N is not powered for some reason. Before red LED turn on as I powered adapter. Isnt Arduino powered by USB from laptop a reason?

Don't forget the L239D's ground needs connecting.

Ahh so https://i.imgur.com/ZueUc82.png L239D ground can go to minus pins or straight to the top GND pin in Arduino

Thanks its working. I'm more of a sw guy than hw guy (Android apps) but I had to do this.


text:
Motor for a winch (with controller and external power supply)
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 which has a 5V port. I've tried using a 12V DC stepper motor (24BYJ48) 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?

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.

I'm still unsure how I would power the driver with an external supply (I've only seen power plugged directly in to the arduino). Would the supply connect to a shield (that I connect to the arduino) with its own 12V port? Also, do I really need a driver if I just bought a motor like this one?

The power connection (assuming you still want to power the Arduino over USB) would be: 12V supply + to + of the motor driver, 12V supply - to ground of the motor driver, ground of the motor driver to ground of Arduino. A shield does also exactly this. And yes, you need some kind of driver, since you want to turn the winch both ways. But as I wrote, a driver can be as easy as 4 MOSFET transistors connected together (you can google MOSFET H bridge to find out how exactly). Without driver, the motor is be on the whole time. You need something to control it (interface between Arduino and motor)

Gotcha - actually I would like to power both the driver (e.g. this one) and Arduino using mains power - though they need 12V and 5V respectively. I imagine the MEGA regulator can't handle 12V; is there some shield/transformer combo that will let me power both with a single power adapter (and a split cable)? Furthermore, I can't even find a 12V power shield online - where can I look for these things?

I think the Mega can handle 12V at Vin, though that's about the maximum. If nothing else is powered through the Mega, that should work. Otherwise you can buy an extra voltage regulator, that is rated for these voltages. And shields are not the answer to everything. Don't search for a power shield, but for a 12V wallwart and if you need it for a 12V to 5V voltage regulator (both rated for enough current)

Wew ok I'll try. But don't I need to connect the wallwart to something to integrate it into my setup? I can't stick cables straight into the plug of the power supply.

@AntiEarth I tried to add some notes about that, though I'm not completely clear, what exactly the problem is. It more seems, that you have general missing knowledge in how to build an electronics project.

Your new note says I should strip a wallwart myself and connect it to the motor driver via screw terminal - how on Earth should that be intuitive, given most novice electronics problems are 'plug in play', as is the very cable you suggest? Your info has been very helpful, thanks very much, but your attitude is very strange

@AntiEarth I don't say, that it is intuitive. I just try to sort out, what exactly the core problem is and how I can help you within the structure of this simple Q&A site. I can write a more general answer about how building this, though that would not really fit to your original question and might be worth a new question. The thing with plug&play is, that such kits are made either very general, just for experimentation, or for a very special case. When you want to reach a special goal outside of it, you are mostly tied to do much yourself.

Such a project might not be the best point for starting as a beginner from zero. Most kits are really experimentation kits, so that you can learn the basics without a specific goal in mind.

"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?


text:
Controlling Brickstuff with Arduino
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.

You need a transistor.  Google, "using a transistor as a switch".

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.


text:
How to load scal factor external to the code?
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);
}

You can store it in EEPROM.  Write a method in setup that will see if EEPROM has been written and if it hasn't then it will let you input a number to use.  You set it up on the first powerup at the factory.  From there on out it sees that EEPROM has been written and skips that bit and instead reads the factor out of EEPROM.

By the way, your current code is flawed.  You should look up what types of values an int variable can hold.

Thanks for your reponse. I have indeed used float in my actual code.

You should always post the "actual code" when asking for help.  Otherwise you end up getting answers that don't apply to your "actual code" and then you've wasted both our time and yours.

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...
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.

Thanks for your respnse. As I have not attached complete code here, int is a typo error. I do undertsnd the data structure. I have indeed used float in my code. I wish to know whats the difference here in directly uploading code and uploading code using EPROM? I need to edit in the main code for all 5 boards even if I will be using EPROM right?

Yes either loading the eeprom from the program (5 versions) or via an extra program you flash before loading (5 flash eeprom versions + 1 identical program) or some kind of input (button presses/led blink to enter during first start - 1 program). Thats why I proposed SD as hassle free ;-)

No you wouldn't have to load the EEPROM at compile time.  You could compile the same code for all boards.  What you would need is some code in setup that check if a value has already been set in EEPROM.  If it hasn't then it calls a function that asks you over the serial monitor and lets you enter the number and stores it in EEPROM.  This code would only run the very first time the board is turned on.  After that nobody will ever see that prompt unless you blank the board and reload.


text:
Building projects on the command line using the Bare-Arduino-Project template
I'm trying to program an Adafruit Trinket using avr-gcc et. al. with the Makefile from the 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?

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.Details on using trinket with the avrdude command line can be found here


text:
I am trying to rewrite an RFID with a MEGA2560 and a RFID-RC522
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;
        }
    }
}

Where did you get the second code? It has code outside of any function, so it cannot compile


text:
Is there a way to remove the 8.3 filename limitation on the SD.h library?
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?

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 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.

What about the SDFat library? Is it better than the FatFS? My aim is to not take too much flash memory.

I haven't used it. But as I mention - anything is better than SD.h. If you have it / can get it easily, then use it.


text:
Having trouble assigning colour to my neopixels
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.

What does "not as randomized" mean? The magic number is equal to 2^31 - 1, though that does not make much sense, since the color of an RGB strip only uses 24 bits, thus a random number covering all the RGB color space, that is available, would have 2^24 -1 as maximum value

I would like it to change from red, to blue, to green, to yellow every 2 seconds, but I would like it to be a random pixel that changes rather than a set one.

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.

Good answer. However, you should explain where your color values come from.

Something like: "RGB can be expressed as 3 2-digit hex (hexadecimal) numbers plus 2 leading zeros. (Hex numbers range from 0 to F, so a 2 digit hex number ranges from 00 to FF, or 0 to 255 decimal.) Take an 8 character hex number. The digits would be 00RdGrBl, where "Rd" are the digits for red, "Gr" are the digits for green, and "Bl" are the digits for green. By convention, you write hex numbers with the prefix "0x", which tells the reader (and the compiler) that the number is in hex. So the color 0x00FF0000 has FF, or 255, for red, and 0 for green and blue. This color is bright red.

The color 0x00FFFF00 has FF (255) for red and green, and no blue. In additive colors, red + green = yellow. (LEDs and displays use additive colors. Paint and dies use the subtractive colors we learned in school, where blue + yellow = green)

@DuncanC I added a paragraph about this topic

Outstanding. You might want to add a bit about the difference between additive and subtractive colors, since this confuses the hell out of just about everybody since we learn in art class that blue+yellow=green.

@DuncanC I wouöd prefer not to boat the answer. Color mixing was not a part of the question and the OP did not ask a follow up on this. Also there are many resources that explain that very good


text:
Do Loop query not stopping
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;
   }
}

Move the incrementation statement inside the do while loop

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:

Initializes x to 0 (first part of the for statement)
It checks the condition x < 5' (second part of theforstatement). If false, it continues with the first statement after thefor` body (after the } bracket).
It runs the body of the loop (inside the brackets)
It increases x (third part of the for statement)
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.

Thanks for the answers. As I am learning this I am trying to complete an excercise such as the one below:
Green LED On
Wait 1 sec
Green LED Off Yellow LED on
Wait 1 sec
Yellow LED Off Red LED on..
Do this for 5 iterations. It does state in the exercise that I must use a do while loop.
As I am specifically limited to the above conditions

@MrDigs ok if the exercise has that limitation, than do so. It's just not the most usual way in this case. You can try both for yourself to see the difference if you have time.


text:
Data type explanation regarding analogRead of a photoresistor
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?

You should keep it uint16_t.
See: analogRead.
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).


text:
Condition in a while loop not updated on my mkr1010
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 !

 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.

Yeah. As a rule you don't want to use while loops inside your sketch's loop function. It's almost always the wrong approach.

You don't want to use while loops anywhere in your code waiting for things in the outside world to happen.  A while loop is for like, while I still have more characters in this string or while I haven't cleared the whole array.  You should never have while loops blocking your code waiting on things to physically happen.  That traps you so that you can't have anything else happen during the wait.

Good way of explaining it.

thanks a lot to both of you! it's working now. I was not aware of that (no whiles when detecting outside events).


text:
Linux not recoginizing Arduino Mega2560 Clone
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

Have you 1) added yourself to the dialout group, and 2) disabled ModemManager?

Oh, man I am dumb. I did add myself to dialout but completely forgot I needed to re-login after.

Running avrdude as root works.
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


text:
Will L293D arduino shield lose functionality if I connect it with jumpers instead of mounting on arduino?
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.

As long as you connect all the pins that need to be connected there is no reason the shield has to be mounted on top of the Arduino.

Thank you for answering, missing headers confused me on this shield.


text:
how do i connect my Arduino Nano to my Linux Laptop
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.

https://www.arduino.cc/en/Guide/Linux#toc6

Hey I just thought of an interesting Idea: what if I can use something like moserial to see a raw output from the Arduino? maybe then, I can see if it is at least talking to the laptop

I'm having the same issue on my installation with Ubuntu 22.04. My Arduino Mega 2560 was working normally, but the Arduino Nano was not recognized.
I managed to solve it with this answer here about "CH34x USB to serial converter chip": https://askubuntu.com/a/1048980/1631587

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.

Is any of this helpful? https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/arduino/readme--arduino.md. If the Arduino runs fine on another computer, I promise you it is capable of running fine on Linux too.

In the Arduino IDE, 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 sounds to be a good read to start.

+1
that is a legitimate answer... and that also brings up the kicker. I forgot about the exact errors and issues I was having, because this was months ago, but it's all flooding back to me. the board is next to me now. the green light is steady, and the port drop-down is greyed out/ not clickable. what do I do?

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)

in my conclusion, i stated I ran it both normally, and in super user mode (sudo arduino), but gave no results.

I hate to be that person who kicks down every answer and return it with another issue. i am not doing this for attention. I legitimately don't know what is wrong.

actually the more i think of it, i think the cable was not made for data transfer. it was a cable i found in a pile of wires so it may just be a charge cable for something else. I will try to find one guarenteed for data transfer and see if it gives better results


text:
Using different variables in a function
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?

Please show a full code example with your problem

So 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?

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.

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.


text:
Tilt Compensated Compass Using HMC5983 gives inconsistent output
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.

However keeping them in the above orientation within my car is not practically possible in my case.
So I tried this orientation.

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

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.
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

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. EDITIn 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.

Yeah I'll try that..and the orientation is changed by 180° about the y axis in the second case I have mentioned..so how can changing x and y solve the problem?

The question is did you turn the hardware sensor 90 degree or flip upside down (there is a difference!)

I have turned it 180 degrees.Ideally the y axis will be oh the same direction it was while the z and x axes will be reversed.

See my edit and the link


text:
Using SDA and SCL with analog inputs at the same time
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);
  }
}

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

Yes, you are right! I have absolutely no idea why it didn't work for me before and why I found so many sources on the internet saying that using these two things at the same time is impossible.

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.


text:
Is there a way to reuse an old robot using arduino?
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:

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.

The circuit diagram enclosed:

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 - 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 will tell you which parts can be removed without soldering
To get started you need the USB drivers for OS 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:

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.

do you think it has Optiboot for the MightyCore?

could the ULN2803APG be the motor driver? https://cdn-shop.adafruit.com/datasheets/ULN2803A.pdf

I will look into the MightyCore solution tomorrow morning. Thanks a lot for that. As for salvaging it, I don't think that's possible as the parts as soldered without much margin to remove them

@Codebreaker007 I followed steps as specified. This is the error that occured: https://pastebin.com/b4biZqYE

@FitzWatson, of course. the upload expects Optiboot bootloader in the ATmega

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:

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.
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 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 (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.

you don't know the MightyCore? https://github.com/MCUdude/MightyCore

Here's a link to the sample codes: http://robokitsworld.com/downloads/QBVLab%20Sample%20Codes.zip


text:
Problem with interrupts and 4x encoders on Nano 33 BLE
I have a Pololu 4x encoder 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. 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.

Probably not the source of your issue, but change val from a volatile int to a volatile byte.  You only need one byte and with int you're technically doing a multi-byte read of a volatile variable with all that entails.

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 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 or from this very well-written forum post.

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);
}

Welcome to Arduino:SE.  Please don't post multiple answers to the same question.  Just edit the information into your original answer.

Please evaluate answers as answers without bias for who posted them.

I'm not bothered by who posts the answers, but SE is a Q&A site, rather than the forums you might be used to.  There is rarely any need for anyone to post more than one answer to a given question.  You might find it helpful to review the site tour and Help Centre and, in particular, How do I write a good answer?.