text:
STM32 "Blue Pill" Serial.print freezes Serial Monitor
I am having difficulties when printing any type of variable using the Serial.print(ln) command.
The Serial Monitor becomes inactive after printing for approximately 7 - 15 times.
I currently have the STM32 Blue Pill Board, running Mac OS Mojave and Arduino IDE v 1.8.9
void setup() {
  Serial.begin(9600);
  pinMode(PC13, OUTPUT);

}

void loop() {
  float raw = analogRead(PA0);
  float voltage = (raw * 3.3) / 4096;
  Serial.println(voltage);
  delay(500);
}

isolate the area of the error .... start by changing the print command to Serial.println("voltage"); .... it will print the word "voltage" .... just let it run to see if it also hangs up

Have you made sure to modify the board before using it?
This page mentions at least one resistor that you have to replace for the USB to "work".

The USB standard requires a 1.5 kΩ pullup resistor on D+, but this board is known to have a wrong value (R10 on the board). It ships with either a 10 kΩ resistor or a 4.7 kΩ resistor, but it should be replaced with a 1.5 kΩ resistor, or put an appropriate resistor value (e.g 1.8 kΩ) in between PA12 and 3.3V.
It is also true that some PCs are tolerant of incorrect value so, before you change the resistance, you can try if it works in your case.

I have had issues with bluepill boards myself in the past, but never had an issue like yours after fixing the resistor. (before that, I couldn't even flash the bootloader)
Try printing other things with the board, and see if there's any pattern to it cutting out. e.g. a string over and over again, or the same float over and over again.
Try different baudrates, or even SoftwareSerial to another board.

Printing a float should work (at least with an Arduino), but to test if it cannot handle it correctly, I suggest you convert the float to a string (e.g., with the C function ftoa, and print the characters one by one or as a string.
Since this C function is not available on Arduino, use the function implementation of this article, credits to Martin Waller:
char *ftoa(char *buffer, double d, int precision) {

    long wholePart = (long) d;

    // Deposit the whole part of the number.

    itoa(wholePart,buffer,10);

    // Now work on the faction if we need one.

    if (precision > 0) {

        // We do, so locate the end of the string and insert
        // a decimal point.

        char *endOfString = buffer;
        while (*endOfString != '\0') endOfString++;
        *endOfString++ = '.';

        // Now work on the fraction, be sure to turn any negative
        // values positive.

        if (d < 0) {
            d *= -1;
            wholePart *= -1;
        }

        double fraction = d - wholePart;
        while (precision > 0) {

            // Multipleby ten and pull out the digit.

            fraction *= 10;
            wholePart = (long) fraction;
            *endOfString++ = '0' + wholePart;

            // Update the fraction and move on to the
            // next digit.

            fraction -= wholePart;
            precision--;
        }

        // Terminate the string.

        *endOfString = '\0';
    }

   return buffer;
}


text:
My alterate flashing LED program is not working
I am trying to program my Arduino UNO ATMega 328p in assembler to implement a ﬂashing pattern with two LEDs. When one LED is oﬀ, the other must be on. I have made a program but it is showing errors and I don't know how to fix it. I have done it Atmel Studio 7. Please help if you can.
Here is my program:
main:

sbi 0x04, 5
sbi 0x04, 4

start:

sbi 0x05, 5
ldi r16,1000
rcall delay
cbi 0x05, 5

sbi 0x05, 4
ldi r16,1000
rcall delay
cbi 0x05, 4

rjmp start

delay:

dec r8
brne delay
dec r9
brne delay
dec r16
brne delay
ret

Please show the errors you received.

When I run this I get 2 errors: Operand(s) out of range in 'ldi r16,0x3e8' Operand(s) out of range in 'ldi r16,0x3e8'

I think I found the problem now, thanks anyways :)

@user58745 Then please write an answer to your question, so that others can learn from this.

source: Stack Exchange

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

sort: votes


text:
ESP32 Pins won't fit in solderless breadboard
I bought an Adafrut Huzzah32 ESP32 for an IoT project. When the ESP32 arrived, I attempted to fit it into my existing breadboard, but I immediately noticed that no matter how hard I pushed, the pins wouldn't fit into the solderless breadboard.
I tried to find others with the same problem with no luck, so I went on amazon and purchased another breadboard (an Elegoo 830 tie-points Breadboard). It arrived today and I'm having the exact same problem. I don't want to use a soderable breadboard at this stage of the project as I'm just starting, but I don't know what else to do at this point.
I've Googled images of other peoples' setups and there pins are snug down in the board. What am I doing wrong? I've included photos below:

As you can see, the power module on the end fits fine but the ESP32 won't go down into the board. At this point, I've tried two different boards (one of those small Arduino ones and this one) with no luck.
Any suggestions?
You can see that the pins aren't even close to being down in the board.

It requires quit a bit of force to push them into the breadboard. Imaging the force of just a single pin, and then multiplying that force by 24. Another solution is to try and see if you can push them in some female headers. And then push those female headers in the breadboard.

@Gerben given that the pins on the MCU point down, can you elaborate on how this would work? The benefit of the breadboard is that it sits in a semi sturdy manner while what I’m picturing you describing would have wires coming out the bottom of the MCU, which would be sitting on top of the the wires on my desk. A photo of what you mean would help heaps, thanks!

Are the pins properly aligned above corresponding holes?

I mean these https://www.adafruit.com/product/2830 . Put the huzzaa in the female end, and put the male end in the breadboards. The legs on these headers are a lot thinner than the pins on the Huzzaa.

@Gerben, thanks. That makes sense. I will give this a try later today.

I ended up taking Gerben's suggestion from the comments and ordering the stacking headers (adafruit.com/product/2830) and plugging the ESP32 into that. The reason it works is because the stacking headers (as Gerben mentioned) are thinner and fit down into the breadboard while the female ports on top are big enough for the male pins coming out of the ESP32.
Thanks everyone!

I understand. These breadboards are pretty difficult to work with. Not only fitting an ESP-32 or similar board is difficult, these breadboards are not broad enough to expose all the GPIOs on both the sides.
I had solved this problem in this video. Do have a look. It might be helpful
https://youtu.be/CQlbE1x2i2g

I think the problem they're having really is just the pain of physically inserting the module into the board.  I'm not sure this addresses that, not directly anyway.  That said, it is nice what you're doing there.  When it comes to an answer that's basically a video link, it would help to have something more in the answer, e.g. a still from the video showing the arrangement you've built, so the answer is not entirely dependent on the link.

or you can simply fit two bread boards together and mount the esp on them

(i had to twist the pins a little bit )

Sharing between breadboards halves the force required to push the device into a single breadboard, and also exposes more tie-points per device pin.  Good idea.

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


text:
How to connect two LED strips (APA102/SK9822) to Arduino UNO?
So what I am trying to do is to connect two SK9822 LED strips to Arduino UNO.
I am a bit confused about how to properly set this up so I can individualy control any led. So obviously 5V should go to 5V and GND to GND, but what about the CLOCK and the DATA pin.
According to the tutorials and stuff I found here, CLOCK pin needs to be connected to pin 13 and DATA to pin 10, but they only use one strip... so what I am trying to ask is can LED strips share pins? Can they be connected to the same CLOCK pin and different DATA pins or how can i set this up to use the minimum amount of pins?
I was planning on using FastLED library, where it looks like you can specify which pin is DATA and which is CLOCK,
FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN>(leds, NUM_LEDS);

Is this because different boards have different CLK and MOSI pins or can i use any pin and set it as CLOCK or DATA? This is probably obvious but I am new to this and this is my first project.

Did you give it a try? This FastLED Wiki page gives you some suggestions for Arduino connectivity. Tip: An Arduino Uno uses the 328P MCU. But the wiki page implies that any(?) pins can be used by FastLED. If h/w SPI support is available on the pins it will use it automatically (implying that if h/w support is not available, it will drive them via s/w).

I don't know about SK9822 LED strips, however the other type of led strips can be used with every pin; this is to support multiple LED strips.
Because every LED strip has its own CLK input (wire), it would be inconvenient to share them... I'm not sure if it is possible practically, because the timing is critical and if you have just one 'master' CLK signal than the data signals for all LED strips should be sent in time. Also writing the library would be more difficult, since there is a relation between a (shared) CLK signal and other data lines.

For minimum pins, daisychain them together, with the clock and data outputs on the tail end of the first strip connecting to the clock and data inputs on the second strip.
https://www.pololu.com/product/3089 says:

Multiple LED strips can be chained together by connecting input
connectors to output connectors. When strips are chained this way,
they can be controlled and powered as one continuous strip.


text:
Any reason to acquire more watts than really needed?
Basic question (again):
I have a LED-strip that requires 5V, and each LED (150 in total) requires about 60 milliamps.
Calculating everything, I need 3 of these LED-strips (450 LED in total). This in turn tells me that they require 27 000 milliamps (27 amps), which is about 135W.
Which means I need an external power supply to power them.
I think about buying a 5V 40A (200 W), which should be sufficient(?).
But, is there any reason that I should not buy anything with more watts (250 or 300)?
Thanks for any help!

i would actually rather have 3 different 10A (or 12A for margin) supplies, so that my cables weren't heavy and/or a burn risk.

Are you sure every led is 60 mA? Or you mean maybe each Red, green and blue led inside each led (3 x 20 mA).
You always should buy slightly more than you need (but you think about 200W instead of 135W) already which is more than enough safety overhead.
Why would you need more? If you mean to control it with an Arduino Uno, that MCU (including the LEDs etc) is high likely more than a few hundred mA. So the only reason why you need more, is if you want to control later more LED strips, or any motor or other power hungry external devices.

Thanks for your reply! Yeah, I meant 20 mA each red, green and blue.
Based on what you write it seems fine to go with 200W, so I will try that. Thanks again for making things clear! :)


text:
How to eliminate drift with the magnetometer in the MPU9250
I have a sketch running that uses a complementary filter for my X and Y values.

However, the Z value has no complementary filter (as you can tell by the slight drift when stationary) because I was told that a magnetometer is required to eliminate this drift.
Thus I purchased the MPU9250.
How would a magnetometer be able to eliminate drift it only measures magnetic fields?
How would I be able to help reduce the drift?

I tried to answer this in your other question.

@chrisl yeah I saw thank you. Thought I should create a new post because the problems differ slightly so for anyone in the future needing help, the posts are sorted better


text:
Parsing the data from an HTTP POST request on a ESP8266 / wemos
I'm sending an HTTP Post request on my Android App to my Wemos D1 mini pro and want to parse the incoming data (which is a json). My current code just prints out the whole POST request and I need to trim it so I only get the needed data. There are several examples out there but nothing matched my needs or worked at all.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ArduinoJson.h>

const char* ssid = "myssid";
const char* password = "mypassword";
char c;
String readString = String(100);
WiFiServer wifiServer(80);

void setup() {

  Serial.begin(9600);
  delay(1000);

  WiFi.begin(ssid, password);
  WiFi.mode(WIFI_STA);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting..");
  }

  Serial.print("Connected to WiFi. IP:");
  Serial.println(WiFi.localIP());
  wifiServer.begin();

}

//for parsing the actual JSON later
//you can ignore this at this moment because I don't even get the needed string to parse it from JSON
void handleReceivedMessage(String message){

  StaticJsonBuffer<500> JSONBuffer;                     //Memory pool
  JsonObject& parsed = JSONBuffer.parseObject(message); //Parse message

  if (!parsed.success()) {   //Check for errors in parsing

    Serial.println("Parsing failed");
    return;

  }

  const char * name3 = parsed["name"];           //Get name from HTTP
  Serial.println("name3");
}

void loop() {
  WiFiClient client = wifiServer.available();

  if (client) {
  Serial.println("Client connected");

    while (client.connected()) {

      while (client.available()>0) {
        //instream from mobile device

        char c = client.read();
        if (readString.length() < 100) {

         //store characters to string
         readString.concat(c);
         //Serial.print(c);
}
      Serial.print(c);
//if HTTP request has ended
       if (c == '\n') {
          //Serial.println(readString);
          delay(50);
          //handleReceivedMessage(readString);
          readString = "";
          client.stop();
   }
 }}}}

the request has a protocol part and the payload. the HTTP headers end with an empty line. then the payload, your json string, follows. the ArduinoJson can only process valid JSON, but you feed it with the complete HTTP request. a valid code would parse the headers line by line, read the content-length header and then use this length to read the payload.but a simple version could simply skip the header with client.find("\r\n\r\n"), like in this example https://github.com/jandrassy/WiFiEspAT/blob/595074cc3c17e968ae68ae2e44f448952e8b7b87/examples/Advanced/ConfigurationAP/ConfigurationAP.ino#L80


text:
How do I get my servo to turn using bluetooth, is this a glitch?
I'm very new to coding with arduino so please excuse my naivety, For an electronics assignment I am making a servo turn back and forth using a HM10 BLE however each time I press a button that sends '0' or '1' to the serial it also sends '200, '0' (being whatever i pressed), 250' all on different lines, so the servo tries turning to 200, 0, then 150 in a quick burst, making it spas out for a split second.
Is there any way i can get rid of the 200 and 250 in the serial or somehow make it only send the '0' or '1'
This is my code so far if needed:
  #include<SoftwareSerial.h>
#include<Servo.h>
Servo x;
int bttx=9;    //tx of bluetooth module is connected to pin 9 of arduino
int btrx=10;    //rx of bluetooth module is connected to pin 10 of arduino
SoftwareSerial bluetooth(bttx,btrx); //defines bluetooth as a dim and reads tx and rx from above

void setup()
{
  x.attach(11);        // servo is connected to pin 11 of arduino
  Serial.begin(9600);
  bluetooth.begin(9600);
}
void loop()
{
  if(bluetooth.available()>0)    //if bluetooth module is transmitting data
  {
    int pos=bluetooth.read(); // store the data in pos variable
    Serial.println(pos);
  }
}

Thankyou for the help and sorry again for the inconvenience, as I said I am only about a week into arduino :) anything helps

Sounds like the sending code on your smartphone isn't working correctly. You will have to fix that. As a workaround, if this sequence of bytes is always the same, you can read the whole sequence from the buffer, and only then set the servo to the desired position.

I agree with crisl, you should look at how your bluetooth signal is generated.
Another good practice is to filter your input signal, not send it straight through to an output. In your case that could be as simple as "if I get anything other than a 0 or a 1, discard and don't use it as a position".


text:
How to power and switch on / off multiple boards at the same time?
I have many nodes.
Each node consists of an MPU9250 and ESP32.
Each node functions independently. They don't interact with each other.
How can I power all of them at the same time, and switch them all on / off at the same time easily ?

Do they have a common power source?

@Majenko Right now they all have their own batteries. I have no electronic engineering background, so not sure how to get started in figuring out how to power all of them from the same source.

If they're not on a common power supply, and they don't communicate with each other, there's no way you can control them all together. Especially not for turning them on. To power them all from the same source, just connect them all to that source. Then you have one power switch at the source to turn them all on and off.

@Majenko that’s the design problem. If you connect them all to the same power source won’t they all draw more power? So won’t you have to design some kind of circuit to ensure they all get the same amount of power or something...

No, that's not how it works. A device only draws the power it needs. As long as the power supply can provide at least the total amount of power for all the devices together, that's fine.

So if each device is x volts and need y amperes, how do I figure out how big a battery I need?

One that provides x volts and, at a minimum, y*z amps - where z is the number of devices.

x volts and y*z * 1.2 amps (giving yourself a 20% buffer).

If you do hook them all up to a single battery then the problem is much simpler. Just wire a switch into the battery connection. Turn on the switch and power flows to all of your nodes. Turn off the switch and the flow of current stops, and they all turn off.

You need to provide more details. How many is "many"? How far apart are they physically? Can you run wires between them? Could you use radio control?
You said in the comments that they are each powered by separate batteries.
One possibility would be to put a power MOSFET transistor on each battery, switching the power supply for a given node. Then wire the gates (and grounds) all together and control them with a switch connected to the supply from one of your batteries (or from a 5V logic line.) MOSFETs draw almost no power at idle, and draw very little gate current for switching, so you should be able to drive dozens of them from a single 5V control line. However, this would require that you have a wire running from a central switch to every node, as well as a common ground to all of them.

Not more than six feet between any node. About 30 nodes. I can run wires between them. I don’t know what you mean by radio control. This is all new to me. I’m a software dude, so just trying my hand at surgery for fun. I don’t actually know much about the liver, spleen or what the pancreas does....  Any tips or guidebook I could read really fast?

There's a lot to learn. It sounds like you're fairly new to electronics and electrical circuits, so you need to learn the basics of voltage and current, power supplies, voltage regulation, and analog circuits. Then you should probably read up on CMOS, since most modern computers including Arduinos are mostly CMOS. Then you should learn about microcontrollers in general, and Arduinos and their quirks in particular.

That’s seems like a lot. I’m just going to hook up wires and see what happens.

Consider what you have to learn in order to develop software. You need the basics of programming, (data types, flow control instructions, etc) OO concepts, data structures, and algorithms. Then you need to learn the OS and application framework(s) for your target platform, and one or more programming languages. Electronics and microcontrollers are similarly complex.

Dude I’m like the obi wan of programming... I bet I could lern lectronixs super fast if I had a tutor....

With software when something crashes you just change your code and try again. The problem with "just hooking up wires and seeing what happens" in electronics is that sometimes things start smoking and never work again.

I gotta try man!!!! I just gotta!!!!!


text:
Error Compiling sketch for Arduino Uno(ld return 1)
I have got an telnet server with esp8266 + SoftwareSerial+ UNO, and here I want to on led with command ON  .
 will be 1 or 2. It is for recive 1 or 2 numbered pins.
And I extract pin from request with indexOf and substring functions and write:
pinMode(pin,OUTPUT);
digitalWrite(pin,HIGH);

I write if pin is not 0 or 1 and it is in range 2-9 for type 1 and if pin is in range 10-13. But at compile time it gives me error compiling for uno. And it gives me this error whn I use pinMode. When I write it to setup it don't give me error. Why? What happenes?
Full code:
#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif
 String res = "";
char ssid[] = "ssid";            // your network SSID (name)
char pass[] = "passs";         // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status
int reqCount = 0;                // number of requests received

WiFiEspServer server(23);

 WiFiEspClient client;

void setup() {
  pinMode(2,OUTPUT);

  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");
Serial.println(WiFi.localIP());

WiFi.config(IPAddress(192,168,0,165));

  // start the web server on port 80
  server.begin();
}

void loop(){
  if(!client){
    client = server.available();
    if(client){
      client.println("Welcome to telnet server!, 192.168.0.165:23");
      client.flush();
    }

  }

  if(client){
if(client.available()>0){
  res = "";
  while(client.available()>0){

char c = client.read();

res += c;

  }
  Serial.println(res);

int i = res.indexOf("ON")+3;
int j = i+1;
String hh = res.substring(i,j);
int type = hh.toInt();
Serial.println(hh);
if(type == 1)
{
  int ii = res.indexOf("ON")+5;
int jj = ii+1;
String hhh = res.substring(ii,jj);
Serial.println(hhh);
int ihhh = hhh.toInt();
if(ihhh != 0 && ihhh != 1 && (2 <=ihhh)&& ( ihhh <= 9 ))
{
  pinMode(ihhh,OUTPUT);
  digitalWrite(ihhh,HIGH);
}
else{
  client.print("Pin is TX/RX, or not 2<= pin <=9\r\n");
  client.flush();
}
}else if(type == 2){
    int iii = res.indexOf("ON")+5;
int jjj = iii+2;
String hhhh = res.substring(iii,jjj);
Serial.println(hhhh);
int ihhhh = hhhh.toInt();
if(ihhhh != 0 && ihhhh != 1 && !((2<=ihhhh)&&(ihhhh <= 9)) && (10 <= ihhhh)&&(ihhhh <= 13 ))
{
  pinMode(ihhhh,OUTPUT);
  digitalWrite(ihhhh,HIGH);
}
else{
  client.print("Pin is TX/RX, or not 2<= pin <=9\r\n");
  client.flush();
}
}

}

    if(!client.connected())
    Serial.println("Client disconnected from Telnet Server");

  }

}

Error is:
Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Arduino/Genuino Uno"
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino\HardwareSerial.cpp: In member function 'availableForWrite':
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino\HardwareSerial.cpp:203:1: internal compiler error: Segmentation fault
}
^
Please submit a full bug report,
with preprocessed source if appropriate.
See http://gcc.gnu.org/bugs.html for instructions.
lto-wrapper.exe: fatal error: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avr-gcc returned 1 exit status
compilation terminated.
c:/program files/windowsapps/arduinollc.arduinoide_1.8.21.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe: error: lto-wrapper failed
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Uno.
Arduino IDE version is:  1.8.9(Windows Store 1.8.21.0)

You forgot to include the error message. Please format your code correctly (use autoformat in the IDE, delete unnecessary empty lines, and fix the indentation).

What is the exact text of the error (all the error, not just the last line). Also, what version of the IDE are you using, and what version of the AVR boards package, and how did you install the IDE?

I thought it might be the "windows store" version. Known to be broken. Delete it. Download the IDE properly from the Arduino website.

@Majenko I didn't know that, what's the difference compared to the "normal" version?

It bundles a broken version of the compiler.

@Majenko I thought the compiler was a part of the AVR Core, not of the IDE itself.

They are separate, but bundled. When you download the IDE it also contains the AVR core and AVR-GCC compiler.

This is a bug in the compiler (linker) used by the Arduino AVR Core. It's not because of a bug in your code, and there's not much you can do about it except using a different version of the AVR Core.
See this forum post:

Here's the traditional workaround:

Tools > Board > Boards Manager
Wait for downloads to finish.
When you move the mouse pointer over "Arduino AVR Boards", you will see a "Select version" dropdown menu appear. Select "1.6.21".
Click "Install".
Wait for installation to finish.
Click "Close".


text:
Communication between Arduino and Can Bus
Function mcp2515_get_message appears the following instruction:
 uint32_t i1 = (uint32_t) spi_putc(0xff),
          i2 = (uint32_t) spi_putc(0xff),
          i3 = (uint32_t) spi_putc(0xff),
          i4 = (uint32_t) spi_putc(0xff);

This instruction is used to fetch data used for determining the message id. Supposing the 32 bit source data contains
Hex 0xAA3A6060, which values will appear in i1, i2, i3, i4?
Any help will be much appreciated.

Is the "32 bit source" big or little endian?

Is this a school assigment?


text:
Problems / doubts on battery-powered Arduino Nano WiFi weather station I built
I've almost finished my first Arduino project and I'm realizing I might have gone a bit over my head - I'm a web programmer, I have a very basic electronics knowledge and started tinkering with Arduino with just a couple simple, tutorial-like small circuits.
I then started building this project of a battery-powered Weather Station that sends sensors data via WiFi to my server - I managed to have a working product but I'm bumping into issues that are starting to look a bit bigger than what they initially seemed.
The workflow (schematics follow):
On the +5V pin of the Arduino Nano (actually a cheap chinese clone) I've put an AMS1117 to stabilize down the voltage to 3.3V (the 3.3V ArduinoNano output wasn't powerful enough), and from there I power several modules; a DS3232 wakes up the Arduino (pin 2) when put in deep sleep mode (every 30 mins); when woken up I read data from the DHT11 (humidity), the BMP085 (pressure), the DS18B20 (temperature) and FC-37 (rain), I connect to my WiFi using the ESP-01, send data to my server, and put the Arduino back to sleep until the next cycle.

Everything worked when on the breadboard, worked after building the circuit with a perfboard; heck, it worked even when connected to my power supply, which is something similar to this project:
https://www.arduinolab.net/solar-li-ion-charger-and-power-supply-for-arduino/

My battery is a 3,7V 2500mA  instead, but all components are almost the same and I use a regular USB - type B cable to connect this to my Arduino Nano
But after an hour or so it stopped working - I checked again by connecting the Arduino to my PC and it appeared to be fine, but when connected to the battery everything was powered up (all leds on!) but the ESP wasn't trasmitting (never saw the flashing blue led).
So I started some reading around and I tought it might be a problem of too much current needed, and the battery wasn't enough anymore after it got under a certain voltage (I still measured 3.80V on the battery terminals though..)...
This is what I'm thinking:

to cut/remove the LEDSs from all the modules (dht, rtc, fc-37 has two!, AMS1117) to save power (it's 5 LEDs + the arduino power on LED). Is it safe? Will they still work with the LED circuitry interrupted?
connect my power source directly to the Vin+ of the AMS1117, instead of using the +5v Arduino output pin (but I read it can safely outsource 500mA, which is the limit for the USB power in anyway, so it shouldn't be an issue...)
for the "long run", use a transistor to power on the sensors when Arduino is awaken, keeping them off the rest of time to spare battery juice, if nothing else...But I really don't know how to start for this, I thought of an NPN transistor (I have a PN222A available) with Base to Arduino (through a 1k Ohm Resistor), Collector to +5V and Emitter to the AMS1117 Vin+, is this sensible?
increase power output? but how? the power source lets 5V 600mA through a regulated DC-DC booster, it should be ideal in theory...How do I understand if it's right for me?
Ditch the ESP01 in favor of the NRF24L01 (I already have a couple of these, but any other suggestion is appreciated)...but that would require a new setup, new coding (never used those modules), a "receiver" that then sends to wifi, and btw I don't know if the signal can make it from the balcony (where I plan to put the WeatherStation) to the inside of the house (I think it will, as the WiFi does - at least I think it does)

I don't really know how to actually measure the consumption of my circuit...I've read something around but, as I said, my electronics knowledge is limited, I don't have much spare time to dedicate on this, and therefore I cannot figure out without a clear guidance, sorry...
I'm not attaching my code because I don't think it's necessary - the sleep mode I'm using is SLEEP_MODE_PWR_DOWN from the avr/sleep.h library, other than that it works fine as it is.
Can someone give me suggestions or pointers on how to analyze my problem? Am I on the right track or my reasonings are off?
Thanks for any help you could provide, if you need any more info I'll do my best (in due time though, as I said I've not that much time to work on this...if I could muster 1 or 2 hours a week it would be a dream!)

You are wasting a lot of power in your system. You need to be far more efficient when running off battery.

Don't boost your battery voltage to 5V. Instead use a system that runs entirely at 3.3V.
Never use a linear voltage regulator like the AMS1117 since it just wastes power as heat. Instead use a switching "buck" regulator.
Turning off modules when not being used is a very good idea. Sleeping the Arduino only saves some of the power - the modules will all still consume power.

I would suggest the ideal way forward would be:

Remove the Arduino from the schematic completely
Replace the ESP-01 with an ESP8266 module with more pins, or better still an ESP32 module.
Connect all the sensors (optionally with P-channel MOSFETs to control the 3.3V supply to them) direct to the ESP32
Remove the 5V boost from the power supply
Connect the power supply through a 3.3V switching regulator to power the whole circuit.

I knew I was doing something wrong with power management; you know, if you look at many popular "maker" websites you often find such solutions which are good for many projects but when start biting back they do it strong. I like your suggestion of using an ESP module, I think I'll consider the ESP8266 for this (It seems the ESP32 is too much for my project). About the 3), can you point to some resources for examples or some component name? (so I can buy the right parts. Same for the 5, so I won't buy the wrong regulator). Thanks a lot, great answer

Any P-channel MOSFET that has a threshold voltage between 0V and -2V would do the job. You don't need much current handling capacity. I usually work with surface mount SOT-23 devices, so any part number I would have to hand would probably not be suitable for you.

As for a regulator, there's LM2596 based adjustable modules readily available on eBay (be sure to adjust the voltage properly ;) ) - but again, any part numbers that I use would probably not be suitable for you since they would be small surface mount ones.

I think I'll follow your advices and look into ESP8266 modules. NodeMCU, Weimos D1, any favorite? Anyway, thanks a lot for the answer!

If you replace the Arduino with an ESP32 don't use an ESP32 development board, use the module! All development boards still use a lot of power even in deep sleep. Check YouTube Andreas Spiess - https://www.youtube.com/watch?v=3O_vrKAmshA  (I deleted my previous comment with the wrong name)


text:
Using software Serial for Adafruit Thermal library and more general cpp question
I'm working on a proof of concept for using the Adafruit_Thermal printer library with an ATTiny85.
The ATTiny85 does not come with hardware serial capability, so I started looking into using SoftwareSerial to create the serial port necessary. I started down this path and ran into an error in the thermal library's constructor:
// thermal-printer.ino example file

#include "SoftwareSerial.h"
#define TX_PIN 3
#define RX_PIN 4

SoftwareSerial mySerial(RX_PIN, TX_PIN);

#include "Adafruit_Thermal.h"

Adafruit_Thermal printer(&mySerial); // Pass addr to printer constructor

// Adafruit_Thermal.h

class Adafruit_Thermal : public Print
{

public:
    // IMPORTANT: constructor syntax has changed from prior versions
    // of this library.  Please see notes in the example code!

    Adafruit_Thermal(Stream *s = &Serial, uint8_t dtr = 255);

Documents/Arduino/libraries/Adafruit_Thermal_Printer_Library/Adafruit_Thermal.h:125:33: error: 'Serial' was not declared in this scope
     Adafruit_Thermal(Stream *s = &Serial, uint8_t dtr = 255);

If I understand correctly, the verification process is failing because the compiler is looking for a global Serial value in the Adafruit_Thermal.hfile that doesn't exist because the ATTiny85 does not have HardwareSerial.
But, going by the Adafruit_Thermal class' constructor signature the reference passing of Serial is just a default value (right?) so I should be able to remove it and pass in my software serial reference. The SoftwareSerial class inherits from Stream, so it should still be a valid reference pass:
// this:
Adafruit_Thermal(Stream *s = &Serial, uint8_t dtr = 255);

// changes to this:
Adafruit_Thermal(Stream *s, uint8_t dtr = 255);

But when I do that, I start getting verification errors that make it look like the thermal instance wasn't constructed, like:

undefined reference to `Adafruit_Thermal::begin(unsigned char)'

and

undefined reference to `Adafruit_Thermal::Adafruit_Thermal(Stream*, unsigned char)'

Does this mean the class isn't getting constructed?
I looked at the underlying constructor definition to see if something was blowing up in there, but there doesn't seem to be anything fancy at the constructor level:
// Constructor
Adafruit_Thermal::Adafruit_Thermal(Stream *s, uint8_t dtr) :
  stream(s), dtrPin(dtr) {
  dtrEnabled = false;
}

This should still work with the software serial reference pass, right?
I'm a bit lost on how to debug this now. Any ideas?
Update
After a reply from Majenko I pulled up the cpp file and looked at the header reference:

So this means the cpp file was still referring to the include path header file instead of the lib version?
I updated my cpp file to use:
#include "lib/Adafruit_Thermal.h"

and I still get undefined reference errors, so it may still be something else, but I wanted to share this additional info.

On the face of it, removing = &Serial is exactly what you want to do, and behaves exactly as you expect. I suspect the other errors you are now getting are unrelated.

Ah ok. I'll keep digging then. If I figure out exactly what was happening I'll post back. Thanks for the confirmation!

It looks like the IDE might not be compiling the .cpp file from the library.

OH! Holy cow I totally didn't think of that! I'm adding an update to show a screen shot.

What IDE is that then?

Ah, this is VSCode (https://code.visualstudio.com) using the arduino extension (https://marketplace.visualstudio.com/items?itemName=vsciot-vscode.vscode-arduino). I'm a web app dev and I already had vscode set up the way I wanted, so switching to the arduino IDE was rough. Luckily the arduino extension allows for doing pretty much everything you'd want to do in the arduino IDE in vscode instead :)

Ah. So is there something you have to do in that IDE to say "Include the files in lib in the compilation`?

Your last comment helped me figure it out. I posted a detailed explanation in the answers section. Thanks for your help @Majenko

:'( it's a bitter sweet solution.
After @majenko's last comment:

Ah. So is there something you have to do in that IDE to say "Include the files in lib in the compilation`?

I remembered that this issue has bitten me before. Specifically, the issue of including subfolders into a sketch.
Normally in programming languages (at least all of the ones I work in normally), you can use relative paths or namespaces to include files from subfolders, but for some reason with Arduino if you want to include files from subfolders you have to put the files in a directory named src.
And it specifically needs to be src. You can't use lib or libs or source or whatevernameyouwant, it needs to be src.
I can't find a spot in the arduino reference docs or the IDE's github repository that explains that you need to use src for the subfolder name, but you can find various mentions in the forums. E.g.
https://arduino.stackexchange.com/a/54655/35534
So yeah, the solution to my problem was three parts.

Adopting the Adafruit_Thermal library into my codebase so that I could edit the source code without worrying about those changes polluting the orginal.
Removing the &Serial reference pass in the constructor declaration of Adafruit_Thermal.h
using the src directory name to include things from a subfolder.

After doing this, the sketch passes verification.
But here's the bittersweet part. After getting past all of this and seeing the compiler get past the sketch verification the bombshell dropped; the sketch is too big for the attiny:

I guess it was not meant to be :'(
Well, at least I know what was causing the linker/compiler errors and I'll be able to sleep at night :P
Thanks for your help Majenko :bows:.


text:
Motor with sinusoidal motion
I need to run a  motor to have a harmonic motion with specified amplitude and frequency ( harmonic motion mean that the angular position of the motor is a sine function of the time). I’m Looking to do a specified number of sinusoidal oscillations.
I don't know how to tell the motor that I want the speed to be a sine function of the time. Any ideas?
Also, I’m still beginning of the project?  Hence I’m pretty flexible to choose any motors (DC/servo/stepper/ brushless motor) or any controller but the system has to be precise.
If you guys know what controllers that allow that kind of motion, please let me know! Thank you :)
EDIT:
so what I'm trying to do is making rheometer which measures the rheological properties of a material. Basically, there are two measuring methods available: Rotational tests and oscillatory tests. With rotational measurements, the measuring bob turns in one direction. In an oscillatory test, the measuring bob "oscillates" around the axis.

what my focus is to with oscillatory tests with set sinusoidal oscillation.
The basic principle of an oscillatory rheometer is to induce a sinusoidal shear deformation in the sample and measure the resultant stress response; the time scale probed is determined by the frequency of oscillation, ω, of the shear deformation. In a typical experiment, the sample is placed between two plates, as shown in the below image While the top plate remains stationary, a motor rotates the bottom plate, thereby imposing a time-dependent strain γ(t)=γ ·sin(ωt) on the sample. Simultaneously, the time-dependent stress σ (t) is quantified by measuring the torque that the sample imposes on the top plate.

So to able to do above testing I need to run the motor with sinusoidal oscillation with exact angle.Hope you get it what im trying to say? does anyone know any  motor controllers that allow that kind of motion ? or any hints how do i wet my feet? cheers!!

what does precise mean?

it is unclear how you want the motor to behave .... please draw a diagram that explains what you are asking ... if possible, describe the project

Sounds like a stepper with lots of microsteps (TMC with interpolation) to me.

A servo may be the simplest option, assuming you can cope with its limited accuracy (aka “dead band”).

A motor with constant speed produces a precise sinusoidal movement if you look at it form the side :)

See https://en.m.wikipedia.org/wiki/Scotch_yoke

Your best option would be:

To have a DC motor with a reduction box so that it spins at lower speeds (Lets say 300 rpm) and have an encoder to count the steps. Either put the encoder before the reduction box (here it can be used a low resolution encoder, like 16 positions) or after the reduction (here you would like a more precise one, such as those 1024 positions).
To have a Stepper motor, which will give a good angular control as long as it doesn't misses steps (if there is too much torque it will halt its movement, and you will lose count of the angle you have already displaced).

Now, to get the motor to move in a way that its angular position is of the form theta(t) = A*sin(ωt) you would have to write some code that moves the motor to each position you want. And the difficulty of it will depend a lot on the amplitude (A) and angular speed (ω) you require.
Obs: feel free to alter/add info here


text:
MQTT PubSubClient connection problem with ESP32
I am experiencing some problems with string in Arduino application with ESP32.
I don't understand why this code works:
mqtt.setServer ("m20.cloudmqtt.com", port);  //is OK
and this does not work does not connect
String strSBM = "m20.cloudmqtt.com";
mqtt.setServer (strSBM.c_str (), port);  //no OK
I use library PubSubClient 2.7
Any of you can help me
Many thanks

When you set the server from a C string it doesn't copy the string - it just retains a pointer to it:
PubSubClient& PubSubClient::setServer(const char * domain, uint16_t port) {
    this->domain = domain;
    this->port = port;
    return *this;
}

If the string it's pointing to goes out of scope (it's a local variable and the function finishes) the data for the string will be invalidated and lost.
It is really intended to work with string literals and global constant variables that never change.
If this is the one and only time that you ever set the server you could get away with using strdup() to duplicate the string data on the heap, but without direct access to the domain member variable of the PubSubClient class you have no way to free() the memory again should you ever wish to change the server.
String strSBM = "m20.cloudmqtt.com";
mqtt.setServer (strdup(strSBM.c_str()), port);

To make it so you can free the value you need to keep track of it separately:
static char *temp = NULL;
if (temp != NULL) {
    free(temp);
    temp = NULL;
}
temp = strdup(strSBM.c_str());
mqtt.setServer(temp, port);

same problem for the port number
what function should i use for the port?
Thanks for your help

No, not the same problem for the port number - that's just a number and gets copied. The problem only exists for the server name because that is a pointer.

Ok now everything seems to work with client.setServer (strdup (strSBM.c_str ()), (int) strPSBM.toInt ());

As long as you only ever do that once it's fine - if you do it more than once you have created a memory leak and you will crash after a while. Why exactly do you want the server name in a String though?

Ohh, then this is not good for me, because in my project I save the name of the server and number port to an external EEPROM and I have the possibility to change the configuration parameters. So having static parameters is not good. Do you have any suggestions?

Create a global char array to store the data in. Read it from the EEPROM into that char array, then pass that to the setServer as is.  Any time you change the contents of that char array the PubSubClient library will instantly see the new data - all that is left is then to connect again.

Nice idea but my project is too complicated for this change.
What do you think of this lease
char * temp;
free(temp);
temp = strdup(strSBM.c_str ());
client.setServer (temp, 15534);
so that each time I change the parameters of the empty server with free() ??? an idea help help help

Sure, that could work - as long as temp is global or static so it remains all the time. static char *temp = NULL; if (temp != NULL) { free(temp); temp = NULL; } temp = strdup(strSBM.c_str()); - It's important to check that temp actually has something allocated to it before trying to free it...


text:
Setting up I2C with HTU21D, no response after beginTransmission
I'm playing with the temperature/humidity sensor HTU21D. Datasheet: https://www.te.com/commerce/DocumentDelivery/DDEController?Action=showdoc&DocId=Data+Sheet%7FHPC199_6%7FA6%7Fpdf%7FEnglish%7FENG_DS_HPC199_6_A6.pdf%7FCAT-HSC0004
The sensor is properly wired and yields reasonable values if I use the library and example here: https://github.com/sparkfun/SparkFun_HTU21D_Breakout_Arduino_Library/blob/master/examples/SparkFun_HTU21D_Demo/SparkFun_HTU21D_Demo.ino
But I'm more interested in how I2C works, so I'm trying to write a small sketch from scratch to communicate with the sensor. Here is what I have right now:
#include <Wire.h>

#define SensorAddress 0x40
#define SoftReset 0xFE
#define TriggerTemperatureNoHold 0xF3
#define TriggerHumidityNoHold 0xF5

void setup(){

    Serial.begin(9600);
    Serial.println("HTU21D library");

    //delay(50);

    //Wire.beginTransmission(SensorAddress);
    //Wire.write(SoftReset);
    //Wire.endTransmission();

    //delay(50);
    Serial.println("init finished");

}

void loop(){

    Serial.println("entering");
    Wire.beginTransmission(0x40);
    Wire.write(0xF3);
    Wire.endTransmission();
    Serial.println("hello");

    //Hang out while measurement is taken. datasheet says 50ms, practice may call for more
    bool validResult;
    byte counter;
    for (counter = 0, validResult = 0 ; counter < 10 && !validResult ; counter++){
        delay(100);

        //Comes back in three bytes, data(MSB) / data(LSB) / Checksum
        validResult = (3 == Wire.requestFrom(0x40, 3));
        Serial.println(validResult);

    }
    Serial.println("here");
}

I'm in the middle of debugging the sketch. When the sketch is uploaded, I'm reading on the serial connection, and all I can see is:
HTU21D library
init finished
entering

It seems the program hangs on the first communication attempt, when I send the TriggerTemperatureNoHold command.
Could you give me a hand please? I don't understand why it's hanging there.

You forgot Wire.begin()...

ah...Indeed....thanks

Post an answer, so I can accept it. Even if my question was slightly dumb...

You forgot Wire.begin();.  You should add it in setup().
Wire.begin(); will configure the IO pins for I2C usage. Without that the signals don't get in or out of the MCU, so I2C functions that wait for an ACK signal never see it and don't complete.


text:
How do you determine Lead Screw position using Absolute Encoder?
I need to control the position of a lead Screw Stepper motor using EMS22A Absolute Encoder? I've seen James Bruton do this in his video. can anyone help me?
James Bruton Video: https://www.youtube.com/watch?v=ngazw18f6zw
edit: What i did was to determine the "Largest Change" to count the number of cycle that has occurred. However, with fast rotation the program was not able to detect the change.
void loop(){

unsigned long currentMillis = millis();
pos = encoder.ReadAngle();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    pos2 = encoder.ReadAngle();
    }
int change = pos2-pos;
if (change > 200){
  cycle--;
}
if (change < -200){
  cycle++;
}
if(change > 1){
  motor.Forward();
}
if(change < -1){
  motor.Reverse();
}
if(change <= 1 && change >= -1){
  motor.Stop();
}
Serial.print(pos);
Serial.print(" ");
Serial.println(cycle);
}

I've offered some general How-To, but you'll get better answers, and more to the point, if you can be specific about what kind of help you need, where you're stuck, etc.

What exactly is your problem in doing so?

What library do you use for the encoder? Please provide a link.

The encoder attaches to the motor (or other) shaft and sends a 10-bit rotational position for a precision of 0.35 deg, and a claimed accuracy of +/- 0.7 degrees. It will be up to the application to keep track of number of rotations, detecting when the shaft has completed a rotation in either direction.
In a lead-screw application there will always be a little bit of backlash or "play". The leadscrew and nut cannot be perfect and must have a little bit of slop (technical term!) to keep the rotational friction low. This means that the nut will have some linear play, leaving that much uncertainty in the linear postion, even if the leadscrew angular position is perfectly known. Most applications manage this by turning the leadscrew back, to behind the target position, and then approaching the target in the forward direction. The leadscrew and nut position will have been calibrated for this direction. Of course it could be calibrated separately for each direction. The key is that the nut must be driven "behind" (for the particular direction) the target by more than the known linear play, to be sure the play will be entirely taken up during the approach to the target.


text:
Merge two 8 bit arrays to one 16 bit array
I am an absolute newbie to Arduino and C++ and try to go through some tutorials to gain a minimal insight. However I stuck already at some tiny Points. What I want to do? Merge two 8 bit integer Arrays in to one 16 bit Array:
int summand_one[8] = {0,0,0,1,1,0,0,0};
int summand_two[8] = {1,0,0,0,0,0,0,1};

int * summand = new int[16];
std::copy(summand_one, summand_one+8, summand);
std::copy(summand_two, summand_two+8, summand+8);

The result should be
{0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1}

However it's not working at all. Constructor/destructor/type errors…
Any helpful idea how to do this?

If you get errors, please include them into your question. They are normally very helpful

It's better to avoid dynamic memory allocation on an Arduino, with only 2 KB of SRAM memory.
Note that your arrays cost 2 (bytes/int) * (8 + 8 + 16) = 64 bytes.
And it seems you are only storing booleans, which could be stored in one bit. So consider another alternative (I will not work that out, since maybe memory consumption is not a problem).
However, an easy solution is to use uint8_t.
Also, I would use a simple memcpy. Very naively it would look like:
uint8_t summand_one[8];
uint8_t summand_two[8];
uint8_t summand[16];

void setup()
{
}

void loop()
{
  memcpy(summand, summand_one, 8);
  memcpy(summand + 8, summand_two, 8);
}

Using some constants for the sizes, you get more flexible/readable and maintainable code:
static const uint8_t SummandOneSize = 8;
static const uint8_t SummandTwoSize = 8;

uint8_t summand_one   [SummandOneSize];
uint8_t summand_two   [SummandTwoSize];
uint8_t summand_merged[SummandOneSize + SummandTwoSize];

void setup()
{
}

void loop()
{
  memcpy(summand_merged                 , summand_one, SummandOneSize);
  memcpy(summand_merged + SummandOneSize, summand_two, SummandTwoSize);
}

Thanks, that did it. Also thanks for the extra explanation on the dynamic memory allocation!

You're welcome.


text:
Remote Controlled Self-Balancing Robot - how to mix control input with IMU input?
I'm building a two-wheeled, self-balancing, remote-controlled robot. I'm familiar enough with the IMU and PID to get it working to just stand up but I need to drive it via remote control.
I've got no code written yet; trying to understand the concepts before diving in.
This much I understand: [IMU] -> [Kalman filter] -> [PID] -> [Motors]
Where I'm getting tripped up is where to mix the RC component into that control chain?

The PID get's a set point from you. For a standing still robot this a basically an angle of zero in respect to the gravity direction (which variable you use for the PID depends on your actal implementation, but it always be something derived from the angle to gravity direction). For driving forward, the robot must lean forward. So you set the new angle set point to let's say 2 degrees. The PID will try to hold that value by driving forward constantly, with a speed depending on the set angle.
So, via the remote control you simply change the angle setpoint.

Seems so obvious now, thanks!


text:
Error: "'lcd' does not name a type" using LiquidCrystal library
I'm following an online Arduino tutorial/course and trying to make a simple moving character on an LCD screen, but for some reason I get the following error: "error: 'lcd' does not name a type". I'm using the Tinkercad simulator because my PC's USB ports died recently.
Here's my code:
#include <LiquidCrystal.h>

byte character[8] {
   B01111,
   B01111,
   B01111,
   B00110,
   B01111,
   B01111,
   B01001,

} ;

  LiquidCrystal lcd(12, 11, 2, 3, 4, 5);

  lcd.createChar(0, character); //error is on this line

const int Lbtnpin = 6;
const int Rbtnpin = 7;
int Lbtnprev = HIGH;
int Rbtnprev = HIGH;
int pos = 0;

void setup(){
  lcd.begin(16, 2);
  lcd.clear();
  pinMode(6, INPUT_PULLUP);
  pinMode(7, INPUT_PULLUP);
}

void loop(){
  lcd.clear();
  int Lbtnstate;
  Lbtnstate = digitalRead(6);
  int Rbtnstate;
  Rbtnstate = digitalRead(7);

  if ((Lbtnprev == HIGH) && (Lbtnstate == LOW) && (pos > 0)) {
     pos--;
  }
  if ((Rbtnprev == HIGH) && (Rbtnstate == LOW) && (pos < 16)) {
     pos++;
  }
  lcd.setCursor(pos, 1);
  lcd.write(byte(0));
  Lbtnprev = Lbtnstate;
  Rbtnprev = Rbtnstate;
}

You cannot call methods outside of a function.
Move lcd.createChar(0, character); into setup.


text:
SD card creating "extra" file?
So, maybe I'm too tired to see the obvious issue here, but my SD card script is causing a "blank" file to be created, then a secondary file to be correctly created.
I'm trying to store data logs, and I don't want to overwrite old logs, I just want to "move" them to the back of the queue.  So I start with six files on the SD card:

DATA.TXT
  DATA~1.TXT
  DATA~2.TXT
  DATA~3.TXT
  DATA~4.TXT
  DATA~5.TXT

Everything writes to DATA.TXT, and DATA~1.TXT through DATA~5.TXT are "old" logs, from oldest to newest.  This means that, the next time I boot up the Arduino, I want the contents of DATA.TXT to be read into a new file called DATA~6.TXT, I want the old DATA.TXT to be deleted, and I want a new DATA.TXT to be created for the rest of the program.  It should look like this:

DATA.TXT     <=== New, blank file, primed for logging new data
  DATA~1.TXT
  DATA~2.TXT
  DATA~3.TXT
  DATA~4.TXT
  DATA~5.TXT
  DATA~6.TXT   <=== "Old" DATA.TXT

In reality, it's creating two files: instead of DATA~6.TXT holding the contents it should, it's blank -- and a file called DATA~7.TXT is created with the contents of the "old" DATA.TXT.  After that, it's writing to the "new" DATA.TXT as it should.  Something is lost (or added) in shifting the data, for some reason, looking like this:

DATA.TXT     <=== New, blank file, primed for logging new data
  DATA~1.TXT
  DATA~2.TXT
  DATA~3.TXT
  DATA~4.TXT
  DATA~5.TXT
  DATA~6.TXT   <=== Blank, unused "new" file?
  DATA~7.TXT   <=== "Old" DATA.TXT

EDIT: Each file contains test data ( e.g. - file DATA~1.TXT contains a line like This is "DATA~1.TXT") So I can track which files are "moved," and where they go. That's how I know where the "old" DATA.TXT file is going, and how I know DATA~6.TXT is "blank." It's actually a blank file, with no data in it.
EDIT #2: As stated in the comments below, the Uno doesn't actually wait for a serial connection.  I just tested this, and it is true... that being said: I'm still getting a blank DATA~6.TXT and DATA.TXT is being moved into DATA~7.TXT without cause.
Now that you know the goal, and (probably) see the issue, here's the code:
/*
 * Tests the SD card slot, assuring no functional code is missing
 * for BIB process to correctly log data.
 *
 */

#include <SPI.h>
#include <SD.h>

String fileName = "DATA.TXT";                       // Declare a filename with FAT 8.3 naming conventions
File dataLog;                                       // Store our "opened" file in an object

void setup(){
    Serial.begin( 115200 );
    while( !Serial ){                               // Wait for serial port to open before doing anything
    }

    Serial.println( "\nInitializing SD card..." );  // Start SD card
    if( !SD.begin( 4 ) ){
        Serial.println( "Initialization failed!" );
        while( 1 );
    }
    Serial.println( "Initialization done." );

    Serial.println( "\nChecking if we have a unique filename..." );
    if( SD.exists( fileName ) )                     // Give our data log a unique filename if the current filename already exists
        moveFiles();

    dataLog = SD.open( fileName, FILE_WRITE );      // Open our file for editing if it doesn't already exist
    Serial.println( "Created save file!" );

    // Write to file the first time
    if( dataLog ){
        Serial.println( "\nWriting int test to file..." );
        dataLog.println( "Testing Sequence1..." );
        dataLog.println( "\tSequence1 complete." );
        Serial.println( "\tFirst test written!" );
        dataLog.close();
        Serial.println( "\tData log closed." );
    }
    else
        Serial.println( "---Error opening data log file!---" );
}

void loop(){
}

// Moves the last `DATA.TXT` to `DATA~x.TXT` where `x` is the largest integer.
// This makes the "highest" numbered file the last data log, and `DATA.TXT` the current data log.
// Follows SFN8.3 standards of naming, with 8 chars for filename, 4 chars for extension, and preceeding
// periods converted to `~` chars.
// This leaves us with only 999 possible "backup" data logs.
void moveFiles(){
    bool sdCardFull = false;                            // Keep track of if our SD card is "full" or not
    byte num = 1;
    File newFile;

    String existingFile = String( "DATA~" ) + String( num ) + String( ".TXT" );     // Creates a filename of `DATA~num.TXT` to test

    // Check if this filename exists, too.  Iterate `num` to avoid overwriting currently existing files
    while( SD.exists( existingFile ) ){
        if( num == 999 ){          // If the SD card is full
            sdCardFull = true;
            noMoreRoom( sdCardFull );
        }

        num++;
        existingFile = String( "DATA~" ) + String( num ) + String( ".TXT" );
    }

    dataLog = SD.open( fileName );
    // Create the new file, with the new filename
    newFile = SD.open( existingFile, FILE_WRITE );

    // Move the old data log into the new filename
    while( dataLog.available() )
        newFile.write( dataLog.read() );

    // Close, remove, then re-open the data log
    newFile.close();
    dataLog.close();
    SD.remove( fileName );                          // Deletes the old data log
}

// We cannot find a good filename for the SFN8.3 format, since all of the available filenames have been
// used up, so we will stop the program from running until the SD card is cleaned up, before we "destroy"
// the last backup file.
void noMoreRoom( bool sdCardFull ){
    /*
    lcd.setCursor( 0, 0 );
    lcd.print( "   SD card is   " );
    lcd.setCursor( 0, 1 );
    lcd.print( "   too full!!   " );
    */

    Serial.println( "The SD card is full and we will not proceed until it is cleaned up." );

    while( sdCardFull ){}       // Do absolutely nothing until the SD card is "cleaned up"
}

Let me guess... you plug the board in (or program the board), then you open the serial terminal, and the program "starts running"...?  What about the period between plugging it in (or programming it) and you opening the serial terminal? It runs then too you know... (assuming an Uno - but you don't specify which board you are using...)

Yes, it's an Uno... and a Nano... and a Pro-Mini.  And the sketch should be caught in the while( !Serial ) loop until the Serial Monitor is attached, right?

No, that line is only for native USB boards as I remember. It will not wait for anything on an Uno or Nano

Maybe you should first test for the file to actually contain data, before you move it.

while (!Serial) works only for MCU with native USB (32u4, SAMD), not for Uno, Nano, Mega, Mini. Uno & co. reset on new connection. they start to run and then they are reset on new connection

All files contain data with their respective filenames ( e.g. - File "DATA~1.TXT" ).  They're being moved correctly.  That's how I know that DATA~6.TXT is blank.

Even if the MCU runs without delay, DATA.TXT should still be going to DATA~6.TXT, a new DATA.TXT should be created with the "test data" per the code, then the Serial Monitor should reset things, moving the "test data" file to DATA~7.TXT and duplicate "test data" to DATA.TXT, right? But this isn't happening... I still can't explain what's happening.

Do you also see that behavior with a complete new setup? (Meaning all files deleted, letting the code start from the known startpoint) Maybe the Arduino was once interrupted by a reset, before he could write the actual data to the file

On a fresh setup (formatted SD card with no files on it), I get two files: DATA.TXT and DATA~1.TXT, with both having the "test sequence data" written to both.  Other than filename, they're identical, according to cmp and md5sum.  I'm still not 100% sure why it's creating two files... usually one is blank, but they're identical in this instance.

You can do multiple resets, by pressing the reset button or reopening the serial monitor, to check, if it works under the correct circumstances. A reset during writing to the SD card can lead to corrupt data. Maybe it is suitable to disable the reset from serial by adding a capacitor between Reset and ground. That prevents the serial interface to reset the microcontroller. Though it also prevents programming, so you would have to remove the capacitor again for programming

try to use - instead of ~

@Juraj I was following the SFN8.3 format, which is recommended by Arduino.  It should work with the ~, but it should also work with the - as well.  Trying both, neither are producing the desired outcome.


text:
Rocket deploy system
I found a code from Astronomica Messier that allows to activate a servo from a Gyroscope MPU 6050 change in direction. I followed the wiring and uploading correctly. The thing is that the MPU is initializing but the connection is failing. Could you help me please to figure out whats happening here? I'm using a GY-86, an Arduino Nano and a Micro Servo 9g. Here's the code. Thank you.
#include "Wire.h"
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Servo.h"

MPU6050 mpu;
int16_t ax, ay, az;
int16_t gx, gy, gz;
Servo servo1;

int val1;
int prevVal1;

void setup()
{
Wire.begin();
Serial.begin(38400);
Serial.println("Initialize MPU");
mpu.initialize();
Serial.println(mpu.testConnection() ? "Connected" :
"Connection failed");
servo1.attach(9);
}

void loop()
{
mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
val1 = map(ax, -17000, 17000, 120, 10);
if (val1 != prevVal1)
{
servo1.write(val1);
prevVal1 = val1;
}
delay(50);
}

Have you tried using an i2c scanner to see if the gyro is detected on the bus?

Missing pullups are a common problem when struggling with i2c, but they might be included on the sensor module. Giving a link to the module you ctually use will help to odd this out.


text:
Use Arduino as transmitter and receiver UART
I know UART and serial communication model and data frame. But I want to ask about something else, when I searched in internet just found examples of one Arduino as (receiver) and another Arduino as (transmitter).
So my question is how can I implement two Arduino and both of arduinos can communicate each other when after transferring data from one to another
(example A->B). If the interpretation of the received data has to be forwarded to the first sender again(B->A).

UART is full duplex. It has 2 lines, one for sending, 1 for receiving. So this is automatically implemented

So can you give me an code sample, in one Arduino acting differently in transmitting or receiving moments?

If you know how to make A talk to B then you already know how to make B talk to A - it's exactly the same.

But how should call transmit and receive function in main function? Just separate with delay? Or after transmit data should switch my position as receiver until the data come in?

You sure now Serial.write() and Serial.read(). That's already what you want. A hint to make it clear to you: When using the common Serial.print() function only the RxD line is in charge an thus only "half" of the serial interface is used. If you connect TxD of arduino A to RxD of another arduino B and RxD to TxD respectively you have full-duplex communication which is what you're asking.

Oh gotcha. So I just should use write and read functions for full duplex. Print is for half duplex. You saved my day man. Thank you

I recommend looking for a simple example to see how the reading actually has to be implemented. This tutorial might help you: https://robotic-controls.com/learn/arduino/arduino-arduino-serial-communication

No, print is not only for half duplex. The whole connection is always duplex, and you can send and receive at any time. print and write are doing nothing else but putting the data into the buffer. The transmitting is done in the background by the Serial library and the hardware. And all read commands are just reading data, that was already received, from the buffer. If you want one arduino to react to the other, just read the data from the first Arduino on the second, and let it send corresponding data back directly (you don't need a delay there)

@chrisl hmm, was your comment meant to be a reply to the OP's comment in the question? Otherwise, what exactly of what I wrote is incorrect? You can Serial.print() without RxD connected. I'm aware of the routine executed in hardware, but I think that info doesn't help the OP very much at this point.

Your answer isn't wrong. I wanted to answer to ghe OPs comme t above, since it seemed to me, that he thinks, he cannot use print if he wants to communicate in both directions. I wanted to prevent a misunderstanding. And it is always good to know, what the called functions really do. That helps in understanding. If this is too complex for a comment, I can also write an answer, to explain it better, than in my comment


text:
Can I determine if I have been pinged?
I have a project using a Wemos D1 Mini.  Is there a way for the sketch running on the Wemos to know when it's been pinged?

I am sure there is. But, what do you mean by "pinged"? Are you doing something with radar or sonar or ethernet? What have you done so far and what exactly did not work (I.e. what did you expect to happen and what actually happened)? It will also probably help if you posted a minimal example of code that recreates the problem. Please refer to the Tour....

I assume you mean if you have received (and responded to) an ICMP PING packet...?

you can't at Arduino level. deeper may be, but I don't see anything related in the SDK API

I don't know if LWIP (leightweight IP stack) is built from source or provided as a binary blob for the Arduino ESP8266 core.. This is where you would handle ping requests / responses. Maybe it's also possible via LWIP APIs which hook these calls? Anyway it's for sure possible in the esp-open-rtos SDK (which build LWIP from source so you can also modify it)

just use http instead. you can curl it from the command line just like a ping.

Dandavis: ?? I don't understand.  I have a device that it on the local WiFi.  I want it to respond to a ping with an LED or bell or some other notification.  I think juraj had the correct answer.


text:
Waking Arduino from sleep with an ultrasonic sensor
I have a parking guide using an ultrasonic sensor (HC-SR04), based on the instructions here. I'm trying to modify the code so that the Arduino goes to sleep after a certain period of inactivity (say, 30 seconds), and wake again when the sensor 'sees' a car drive into the garage. The code here shows how to wake it with a solar panel.
However, the way I understand it, the solar panel is able to wake the Arduino because it doesn't need external power to work (because it's a solar panel). Would it be possible to do the same with an ultrasonic sensor (HC-SR04), which does need power?
It'll be running off mains power, but I don't want it to be drawing power when it's not needed.

In order to make the ultrasonic sensor work, the Arduino has to run some code to control it.  So it won't do anything while the Arduino is asleep.
What you can do is have the Arduino sleep for some reasonable amount of time, wake up and read the sensor, and then go back to sleep.  Maybe wake it up once every few seconds.  Do you really need to react to a car in the lot the millisecond it pulls in?


text:
CHSV arguments with FastLED
I'm trying to use CHSV with FastLED library and as I understand hue, value and saturation in the CHSV type are of type uint8_t, or 1 byte.
My problem is with using variables:

CHSV led = (hue, sat, val);

with:
uint8_t hue;
uint8_t sat;
uint8_t val;

Is there a difference between uint8_t and byte data types? what is it and how does one use it with the context of arduino and FastLED library?
Am I getting the syntax wrong?
I get an error - convertion from 'uint8_t' to non scalar type 'CHSV' requasted.
I thought the library does that on its own, do I need to add more code? If yes, what code?

Thank you

Is there a difference between uint8_t and byte data types?

There is no difference in the datatype. byte is defined in Arduino.h:
typedef uint8_t byte;

So, uint8_t and byte are exactly the same. The uintX_t types and their siblings are specifically meant for having the same size on every platform (in difference to for example double which is only 16 bits on Arduino Uno, but can be 32 bits on bigger chips). But byte will also be 8 bits on every platform, so there is really no difference.

Am I getting the syntax wrong? I get an error - convertion from 'uint8_t' to non scalar type 'CHSV' requasted. I thought the library does that on its own, do I need to add more code? If yes, what code?

You get the error, because you use the wrong syntax here. A CHSV color is not just 3 byte values, it is a class with member variables and methods. So you cannot simply assign 3 byte values directly to the object. You need to actually create the object, using the values as parameters for the constructor:
CHSV led = CHSV( hue, sat, val);

This creates a CHSV object, executes it's constructor, which uses the values from the parameters to set the internal values. That is the context, how this is used in the FastLED library. You can also find such lines in the examples of the library (I found such use in line 15 of the example ColorPalette, but there might be more). Also this is the same principle, as with the other color classes, like CRGB.


text:
SPI receive register size of ESP32
ESP32 has 64 byte SPI FIFO size, but I could not find what is the largest bit size it can receive over SPI?
P.S. I need to interface a sensor, which returns 32 bit response.
EDIT to clarify why I am asking:
I am sending 32 bit request by splitting it into 4 bytes, but do not know how to recieve 32 bit response.
This function is for sending:
uint32_t SendRequest(uint32_t Request)
{
    uint32_t Response;
    digitalWrite(PIN_CSB, LOW);
    SPI.transfer(Request >> 24);
    SPI.transfer(Request >> 16);
    SPI.transfer(Request >> 8);
    Response = SPI.transfer(Request);
    digitalWrite(PIN_CSB, HIGH);
    return (Response);
}

SPI.transfer() returns the respond after data send completely. Can I read the SPI register?
Datasheet of the sensor: https://www.murata.com/~/media/webrenewal/products/sensor/pdf/datasheet/datasheet_scc2230-e02.ashx?la=en
EDIT to update SendRequest() function:
uint32_t SendRequest(uint32_t Request)
{
    uint32_t Response = 0x00;
    digitalWrite(PIN_CSB, LOW);
    // Send the request in 8-bit sections
    SPI.transfer(Request >> 24);
    SPI.transfer(Request >> 16);
    SPI.transfer(Request >> 8);
    SPI.transfer(Request);
    digitalWrite(PIN_CSB, HIGH);
    delay(1);
    // Capture the response in 8-bit sections
    digitalWrite(PIN_CSB, LOW);
    Response = SPI.transfer(0x00);
    Response = (Response << 8) | SPI.transfer(0x00);
    Response = (Response << 8) | SPI.transfer(0x00);
    Response = (Response << 8) | SPI.transfer(0x00);
    digitalWrite(PIN_CSB, HIGH);
    delay(1);
    return (Response);
}

1 byte has 8 bits. 32 bits are 4 bytes. what is the problem?

Why I am asking, because, 32 bit data can be send by splitting it into 4 bytes. But I do not know how to capture full 32 bit  respond. I will edit my question to specify.

like 4 bytes and then <<

You don't receive the 32-bit response. You receive the 4 bytes you sent. It's then your job to recombine those bytes into the correct 32-bit value.

You mean receiving 1 byte after each 1 byte transfer? How slave device knows what to respond until command not send completely?

No, receiving the reply after you have sent the request. You send 4 bytes in the request - you then read 4 bytes for the response. Read the datasheet of the (unspecified) "device" - it will contain a protocol diagram detailing exactly what happens on each and every clock cycle of the transfer.

Exactly. But I do not know how to capture the reply after 32 bit transfer is completed. I think SPI.Transfer receives only 8 MSB of the response.

Are you sure you don't first start receiving the response after you have fully transferred your request? Just do four SPI.transfer(0x00) calls after the final request transmit to get the 4 bytes, then, depending on the byte order (little or big endian) of the 32 bit word, shift them back together. It's however not possible to know when your sensor sends the answer because you have provided no datasheet to us.

Yes, you have right. I was also doing it right know. But again I receive 0xFF.
Response = SPI.transfer(0x00);     Response = (Response << 8) | SPI.transfer(0x00);     Response = (Response << 8) | SPI.transfer(0x00);     Response = (Response << 8) | SPI.transfer(0x00);

So what are you inputting as Request?

I have updated the function in my question above. To capture the data I send zero. But for Request I am sending 32 bit SPI frames for different operations. It might have also some timing problem.

If you only ever receive all 0xFF for the response then MISO might be permanently high. Check that with a multimeter, you might have a wrong wiring


text:
Delay stops execution forever sometimes
I have an arduino to control an irrigation system, consisting on one pump (called "bomba" on the code) and 5 12V water valves.
Each valve controls one irrigation circuit and the idea is to open each one sequentially during one minute and then move on to the next one.
The code is this:
const int TIEMPO_RIEGO = 64; // seconds

const int TRIGGER = 5;

const int BOMBA = 6;
const int CIRCUITO_1 = 8;
const int CIRCUITO_2 = 9;
const int CIRCUITO_3 = 10;
const int CIRCUITO_4 = 11;
const int CIRCUITO_5 = 12;

const int CIRCUITOS_ACTIVOS[] = {
  CIRCUITO_1,
  CIRCUITO_2,
  CIRCUITO_3,
  CIRCUITO_4,
  CIRCUITO_5,
};

void _abrirValvula(int circuito, int t) {
    digitalWrite(circuito, HIGH);
    digitalWrite(BOMBA, HIGH);
    unsigned long waitTime = t * 1000L;
    delay(waitTime);
    digitalWrite(BOMBA, LOW);
    digitalWrite(circuito, LOW);
}

void cicloRiegoCompleto() {
  int numeroDeCircuitos = sizeof(CIRCUITOS_ACTIVOS) / sizeof(CIRCUITOS_ACTIVOS[0]);
  for (int i=0; i<numeroDeCircuitos; i++){
    _abrirValvula(CIRCUITOS_ACTIVOS[i], TIEMPO_RIEGO);
  }
}

void setup() {
  pinMode(BOMBA, OUTPUT);
  pinMode(CIRCUITO_1, OUTPUT);
  pinMode(CIRCUITO_2, OUTPUT);
  pinMode(CIRCUITO_3, OUTPUT);
  pinMode(CIRCUITO_4, OUTPUT);
  pinMode(CIRCUITO_5, OUTPUT);
  pinMode(TRIGGER, INPUT);
}

void loop() {
  if (digitalRead(TRIGGER) == HIGH) {
   cicloRiegoCompleto();
  }
}

On the pin 5 (TRIGGER) I have a raspberry pi connected that is connected to the internet also, so, when I send it a message from mi phone, it puts 3.3V on that pin and starts the process.
It has been working great for like a month or so but, a few days ago, the pump didn't stop when it should, and was still working hours after it started.
I pull the plug and, when I turn it on again, it worked correctly again for another 2 or 3 days.
But today it hasn't stop again. I have check that the pump has been working for around 15 minutes until I pulled the plug, and the first valve (CIRCUITO_1) has been opened the whole time, looks like the for loop is stuck in the first iteration.
So can it be some problem with the delay function?
For some reason it is waiting way more than it should?
It works sometimes and sometimes it doesn't so it makes me think: can it be some weird overflow issue?

The code seems legit to me. Can you log on the pi, when exactly it turns it's output on and off? Just to see, if that works correctly.

When you have this problem, what is the state of the logic output of the Pi?

The pi turns its output HIGH during only one second, and then it is LOW again. But, even if it were HIGH the whole time, it should loop through each valve instead of being stuck in the first one forever.

How are you interfacing the pumps to the Arduino? Can you post a circuit diagram?
Also, how are you powering the pumps? Are they powered separately from the Arduino, or is the Arduino sourcing its power from the same circuit that the pumps are?

The valves are controlled via mosfets IRL510 (or IRL540? don't remember right now), the pump with a 5V arduino relay. Everything is powered from a 15A 12V power supply, using a step-down for the raspberry and the relay power. I'll try to upload a diagram this evening.

Is it a cheap $1 Chinese nano or a genuine Arduino nano?

Bought it on amazon.es in a pack of 6 for around 15€, so it is probably the Chinese version. I'm not sure how to spot the differences, here is a photo: https://imgur.com/03C2WyB

Cheap Chinese crap. Do you know how they get them so cheap? Simple: the MCUs come out of the reject bin. Instead of the factory in China throwing them out they sell them cheap on the local market. So you can expect them to be substandard and fail randomly...

Based on your experience with the system and the source of the Nanos, the best and quickest test I can think of is to swap in a another Nano to find out whether if the problem remains or disappears.

Do you have 10k resistors between gate and ground on your MOSFETs? You might be suffering from residual charge on your MOSFET gate keeping it on when it should be off.

Yep, and also flyback diodes on each valve.

It has been working great for like a month or so ... it makes me think: can it be some weird overflow issue?

It's hardly a software issue then. Nothing in your code would change after a month of operating. And if you turn the power off and on again then it would "forget" about the previous month.

So can it be some problem with the delay function?

No.

I suggest looking at the hardware, or the code on the Pi.

That makes sense. The pi code looks fine but, should I just check the mosfet circuit part or the arduino itself too? What I mean: Is it possible for an arduino to break in some way that it gets stuck randomly on a line of code? Or if the arduino was broken it wouldn't work at all?

I doubt it would get "stuck" on a line of code. The processor runs or it doesn't. I would use a meter to test that the output is being set in the way you expect.

You may have a problem in the casting of the variable t vs the variable waittime.  t is an int and waittime is a long so when you multiply t by 1000L you may be picking up a couple of extra bytes used by other parts of the code:
For instance if t is stored at location 0x100:0x101 in RAM, and some other variable or random data is stored at 0x102:0x103, you pass 100 to the function in variable t which you expect multiplies into waittime as 100,000mS or 100S, but if the data stored at 0x102:0x103 for instance is randomly 0xFFFF, the multiplication into waittime actually works out to (100*65536)+65535 = 6,619,135mS or 1.83 hours.
The way around this is to either pass a long in the function or recast t to match waittime:
waittime = (long) t * 1000L;
Note that the order of the bytes depends on how the compiler handles variable storage.

Compilers don't overwrite memory just because you cast something. That would be pretty bad behaviour if they did. Maybe if you cast a pointer into a different sort of pointer, but this is just an ordinary variable.

The cast and multiply are almost certainly done in registers, and the variable waitTime is unlikely to ever have any discrete existence, as the product of the multiply will be left in registers or immediately pushed onto the stack as the argument to delay(), and is never referred to again.


text:
Have I damaged my arduino?
I was trying to build a finger print lock system.. While my arduino was connected with my pc, I mistakenly plugged the adapter and turned it on. I immediately switched it off. It was working fine (port 3?) Now suddenly port 3 disappeared and the only available option I have is port 1, which is not working! My window is also alerting me that it didn't recognize the device. I searched for it in device manger but no others devices option is available

or you damaged the USB port. what adapter and how did you plug it?

12v 2A power adapter. I plugged it into the port in the board that is given for adapter.

on genuine Arduino Uno it shouldn't cause a problem

I probably didn't burn it as the solinoid lock and the sensor is perfectly working and when I connect the USB, my arduino uno gets power. Im not just able to upload any code as there is no port 3 option to select.

Which model of Arduino?
The design of most models has circuitry that handles getting power from both the barrel connector and the USB port, and switches between them intelligently.
Thus the answer should be "no, no problem." However, what else does your 12 adapter power? You might want to post a full circuit diagram of your project.
Also, as Juraj says, Arduino brand microcontrollers are designed to handle this situation. Knockoff models may cut corners.

https://drive.google.com/drive/mobile/folders/1JWxkBoONwUHxvn-4A6pfhs0_0sCHIo5Q?usp=drive_open     I'm following the circuit and the codes given in this drive. Its arduino uno r3. The Solenoid lock and the sensor is perfectly working as i already uploaded my codes. But I was trying to reload it again so that I can start everything from the beginning. Collecting ids and all that ... but r3 port has completely disappeared from the option and this is why I'm not able to upload any new code.


text:
What can I do to increase the amount of LEDs I can power with a pro micro?
I am new to arduino and have a sparkfun pro micro that I'm using to power a one meter (60 pixels) APA 102 strip. I currently power it via USB and have a program that sends lighting instructions to it. I can only seem to power ~15 pixels with full range of brightness and ~30 if I keep the brightness at about half.
Anything more and the pro micro will stop recieving data and either freeze at the last color it's recieved or turn a bright red (which I assume is a visual indication of the fail because I didn't code that). At this point, the COM port will also become inaccessible until the code is either re-uploaded or in some cases, I simply disconnect the strip. This leads me to believe that the amount of power that I am demanding is too much for the board to put out.
So am I right in this assumption? and If so, what can I do to increase the amount of pixels I can power at full range?
I'll also post my code below in case there is something I can do there to increase the pixel amount:

#include <Adafruit_DotStar.h>
#include <SPI.h>

#define NUMPIXELS 60
#define DATAPIN    4
#define CLOCKPIN   5

Adafruit_DotStar strip(NUMPIXELS, DOTSTAR_BRG);

// Variables
int mode;
int numColors;
int fadeSpeed;
int BBCC;
int R;
int G;
int B;
int Bright;

void setup() {

#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
  clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
#endif

  strip.begin(); // Initialize pins for output
  strip.show();  // Turn all LEDs off ASAP
}

int      head  = 0, tail = -10; // Index of first 'on' and 'off' pixels
uint32_t color = 0xFFFFFF;      // 'On' color (starts red)

void loop() {

  //strip.setPixelColor(head, color); // 'On' pixel at head
  //strip.setPixelColor(tail, 0);     // 'Off' pixel at tail
  strip.show();                     // Refresh strip
  delay(20);                        // Pause 20 milliseconds (~50 FPS)

  getData();

  if (mode == 1)
  {
    for (int i = 0; i < (60); i++)
    {
      if (i % 2 == 0)
        strip.setPixelColor(i, G, R, B);
    }
    strip.setBrightness(Bright);
    strip.show();
  }
  else
  {
    for (int i = 0; i < (60); i++)
    {
      if (i % 2 == 0)
        strip.setPixelColor(i, 150, 200, 40);
    }
    strip.setBrightness(255);
    strip.show();
  }
}

int readLine(int readch, char * buffer, int len)
{
  static int pos = 0;
  int rpos;

  if (readch > 0)
  {
    switch(readch)
    {
      case '\r':
      {
        break;
      }
      case '\n':
      {
        rpos = pos;
        pos = 0;
        return rpos;
      }
      default:
      {
        if (pos < len-1)
        {
          buffer[pos++] = readch;
          buffer[pos] = 0;
        }
      }
  }

  return 0;
}
}

void getData()
{
  char buf[80];
  bool redo = true;

  if(readLine(Serial.read(), buf, 80) > 0)
  {
    int i = 0;
    int j = 0;
    bool skip = false;
    char fin[3];
    if (skip == false)
    {
    do//                                mode
    {
      switch (buf[i])
      {
        case '\n':
        {
          skip = true;
          redo = false;
          break;
        }
        case '|':
        {
          mode = atoi(fin);
          //Serial.print(mode);
          i++;
          redo = false;
          break;
        }
        default:
        {
          fin[j] = buf[i];
          i++;
          break;
        }
      }
      j++;
    }while(redo);
    redo = true;
    j = 0;
    }

    if (skip == false)
    {
    do//                     number of colors
    {
      switch (buf[i])
      {
        case '\n':
        {
          skip = true;
          redo = false;
          break;
        }
        case '|':
        {
          numColors = atoi(fin);
          //Serial.print(numColors);
          i++;
          redo = false;
          break;
        }
        default:
        {
          fin[j] = buf[i];
          i++;
          break;
        }
      }
      j++;
    }while(redo);
    redo = true;
    j = 0;
    }

    if (skip == false)
    {
    do//
    {
      switch (buf[i])
      {
        case '\n':
        {
          skip = true;
          redo = false;
          break;
        }
        case '|':
        {
          fadeSpeed = atoi(fin);
          //Serial.print(fadeSpeed);
          i++;
          redo = false;
          break;
        }
        default:
        {
          fin[j] = buf[i];
          i++;
          break;
        }
      }
      j++;
    }while(redo);
    redo = true;
    j = 0;
    }

    if (skip == false)
    {
    do
    {
      switch (buf[i])
      {
        case '\n':
        {
          skip = true;
          redo = false;
          break;
        }
        case '|':
        {
          BBCC = atoi(fin);
          //Serial.print(BBCC);
          i++;
          redo = false;
          break;
        }
        default:
        {
          fin[j] = buf[i];
          i++;
          break;
        }
      }
      j++;
    }while(redo);
    redo = true;
    j = 0;
    }

    if (skip == false)
    {
    do
    {
      switch (buf[i])
      {
        case '\n':
        {
          skip = true;
          redo = false;
          break;
        }
        case '|':
        {
          R = atoi(fin);
          //Serial.print(R);
          i++;
          redo = false;
          break;
        }
        default:
        {
          fin[j] = buf[i];
          i++;
          break;
        }
      }
      j++;
    }while(redo);
    redo = true;
    j = 0;
    }

    if (skip == false)
    {
    do
    {
      switch (buf[i])
      {
        case '\n':
        {
          skip = true;
          redo = false;
          break;
        }
        case '|':
        {
          G = atoi(fin);
          //Serial.print(G);
          i++;
          redo = false;
          break;
        }
        default:
        {
          fin[j] = buf[i];
          i++;
          break;
        }
      }
      j++;
    }while(redo);
    redo = true;
    j = 0;
    }

    if (skip == false)
    {
    do
    {
      switch (buf[i])
      {
        case '\n':
        {
          skip = true;
          redo = false;
          break;
        }
        case '|':
        {
          B = atoi(fin);
          //Serial.print(B);
          i++;
          redo = false;
          break;
        }
        default:
        {
          fin[j] = buf[i];
          i++;
          break;
        }
      }
      j++;
    }while(redo);
    redo = true;
    j = 0;
    }

    if (skip == false)
    {
    do
    {
      switch (buf[i])
      {
        case '\n':
        {
          Bright = atoi(fin);
          //Serial.println(Bright);
          i++;
          redo = false;
          break;
        }
        default:
        {
          fin[j] = buf[i];
          i++;
          break;
        }
      }
      j++;
    }while(redo);
    redo = true;
    j = 0;
    }
  }
}

As Majenko already mention, use a separate power supply.

Use that power to power the LED strip(s).
Use the MCU to control the data and clock lines.
Connect grounds together.

MCU? I'm really new so I don't know what that is. I'm using the SCK and MISO pins. Is that the same thing?

An MCU is a Micro Controller Unit, your Arduino is one (example of an ) MCU.  The SCK is the clock line (Serial Clock) and MISO (Master In Slave Out) are data lines. If you google for SPI  you will find out what SCK and MISO are meant for.

Managing your power budget is a normal part of electronics projects. You can only draw about 500 mA total from the USB port, and less than that from the 5V line if your Arduino is powered from USB. If you drive your Arduino with ≈7V into the barrel connector you might be able to pull a full amp from the 5V rail, but it depends on how hot the voltage regulator gets. The higher the input voltage into the regulator, the more heat you generate for a given amount of current. On a genuine Arduino board the voltage regulator should have an overheat protection circuit, which will cause it to shut off when it gets too hot. Cheap knockoffs may just burn out.
When you start using higher current devices like motors or LED strips, it's usually a good idea to switch to a separate (regulated) power supply for those devices. Tie the ground lines together, and since you use separate power supplies for the Arduino and your other devices, they don't affect each other's supply voltages.

So am I right in this assumption?

Yep.

and If so, what can I do to increase the amount of pixels I can power at full range?

Simple: don't power it from the Arduino. Add a proper external power supply that is capable of providing the current you require.


text:
Forward kinematics of a differential drive robot
I've been braking my head over this for the past few days and can't make it work.. So, I have a small robot with a rotary encoder on each wheel and i want to track its position (in x and y) on a flat plane. I know it's called forward kinematics, but i can't seem to get it working. I found a lot of great public sheets, but i think, out of all of them, this is the best one It had the equations of how to calculate the X and Y on page 74:

Vicc=L * (Din / (Dout–Din) + ½) (page 73) //Din is the inner wheel of the turn traveled distance, Dout is the outer wheel
Xtδ=Xt+Vicc*(sin(θt+θΔ) – sinθt)
Ytδ=Yt+Vicc*(cosθt - cos(θt+θΔ))
θtδ=θt+θΔ //angle measurement

Where Xtδ and Ytδ are the position of the robot (x, y); Xt/Yt/θt is the position of the robot when the counting of the position has been started; θΔ is the angle of the robot now;
. Here's The code that I tried to write using the equations. I expected it to write my coordinates in x and y, but when i moved the wheels, it sent me big, random numbers, which are fluctuating up and down, which looks like a sine wave. What am I doing wrong? Could you guide me to the right path? My end result, that I want to reach is controlling 2 both motor speeds and knowing the robots position (doesn't need to be very precise though).
Thanks in advance!
EDIT: Added code from PasteBin
#include <Encoder.h>

Encoder Left(3, 2);
Encoder Right(0, 1);

float R = 385; //mm
float r = 12.5; //Wheel diameter in mm
float L = 8; //Distance between the wheels in cm

double LeftDist = 0;
long LOldPos  = -999;
float LNewPos;
int Correction;

double RightDist = 0;
long ROldPos  = -999;
float RNewPos;

int angle= 0; // Robots current angle
unsigned long t;

int Xold= 0; //position at the start of the calculation
int Xnew= 0; //new, calculated position
int Ystart= 0; //position at the start of the calculation
int Ynew= 0;//new, calculated position
int OldAngle= 0; //angle at the start of the calculation
int NewAngle= 0;// new angle at the end of the calculation
int Vicc;

void setup() {
  Serial.begin(9600);
  t = millis();
}

void loop() {
  Encoders();
  if ((millis() - t) >= 100) {
    Xold= Ynew; //setting the new position to old
    Yold= Ynew; // setting the new position to old
    OldAngle= NewAngle; //Setting the new angle to old

    Vicc = (L * (LeftDist / (RightDist / LeftDist))) + 0.5;
    Xnew= Xold + (Vicc * (sin(OldAngle + Angle) - sin (OldAngle))); //Calculation of X
    Ynew= Yold+ (Vicc * (cos(OldAngle) - cos(OldAngle+ Angle))); //Calculation of Y
    NewAngle = OldAngle+ Angle;

    t = millis();
  }

  Serial.print(angle);
  Serial.print("        ");
  Serial.print(Xnew);
  Serial.print("        ");
  Serial.println(Ynew);
}

//0.9mm/1 deg
void Encoders() {
  LNewPos = Left.read();
  if (LNewPos != LOldPos) {
    LOldPos = LNewPos;
    LeftDist = ((LNewPos / 840) * (2 * r * 3.14)) / 10; //cm/ Rev
  }
  //-----------------------------------------------------
  RNewPos = Right.read();
  if (RNewPos != ROldPos) {
    ROldPos = RNewPos;
    RightDist = ((RNewPos / 840) * (2 * r * 3.14)) / 10; //cm/ Rev
  }
  angle= (abs(RightDist - LeftDist) * 0.9) - Correction; //calculate the angle the robot has turned
  if (fi >= 360) Correction += 360;
  else if (fi <= -360) Correction -= 360;
}

Please, instead of " I thought will work, but it didn't" state exactly what you expected it to output / do and what you observed. Do you have intermediate values you can check? Isolated test cases? We don't have your hardware here and the code is practically uncommented

@MaximilianGerhardt, okay, sorry, i'll edit it in just a sec

While you’re at it, it might help to change the variable names from things that are easy to type to things that are easy to read and follow.

@Delta_G, okay, I'll do that

What units do you have the angles in?  Degrees or radians?

From your use of the number 360 at the end of the Encoders() function, I am thinking that you are using degrees for the angles.  That won't work with sin and cos.  The trig functions all expect angles in radians.  To convert degrees to radians, multiply by PI/180.

I have just changed it to calculate it in radians, but it does the same thing, the x and y values go up, reaches an integer overflow and goes back down,

Is angle still an int?  I would think radians would probably need to be in floating point.

No, i converted it to a float and I'm trying to take a little different approach and calculating velocities of each wheel/angular velocities and will try out a different equational you are not

OK.  You'll have to update the code here then to get further help.